Skip to content

Visual Studio Code, rebuilt in Rust

Rust
87.6 KB
Raw Blame
//! The Run and Debug view container (debugViewlet.ts) in the side bar: the title with the launch configuration
//! picker (debugActionViewItems.ts `StartDebugActionViewItem`), the welcome view (welcomeView.ts) and the Variables,
//! Watch, Call Stack, Breakpoints and Loaded Scripts views (variablesView.ts, watchExpressionsView.ts,
//! callStackView.ts, breakpointsView.ts, loadedScriptsView.ts).

use std::collections::HashSet;

use gpui::{ClickEvent, Context, Div, KeyDownEvent, MouseButton, MouseDownEvent, Rgba, Window, div, prelude::*, px};
use serde_json::{Value, json};

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;
use crate::menus::{Entry, MenuId};

pub(super) const DEBUG_CONTAINER: &str = "workbench.view.debug";
/// debug.ts view ids and welcomeView.ts `WelcomeView.ID`.
pub(super) const VARIABLES_VIEW: &str = "workbench.debug.variablesView";
pub(super) const WATCH_VIEW: &str = "workbench.debug.watchExpressionsView";
pub(super) const CALL_STACK_VIEW: &str = "workbench.debug.callStackView";
pub(super) const BREAKPOINTS_VIEW: &str = "workbench.debug.breakPointsView";
pub(super) const LOADED_SCRIPTS_VIEW: &str = "workbench.debug.loadedScriptsView";
pub(super) const DEBUG_WELCOME_VIEW: &str = "workbench.debug.welcome";

/// The inline input of the Variables, Watch or Breakpoints view.
#[derive(Clone, Debug, PartialEq)]
pub enum Editing {
    NewWatch,
    Watch(String),
    /// A variable's value by its session, parent `variablesReference` and name; `watch` for a row under a watch expression.
    Variable { session: String, parent_reference: i64, name: String, watch: bool },
    /// A watch expression's value (`setSelectedExpression(expression, settingWatch: true)`).
    WatchValue(String),
    /// A visualized tree item's value (`VisualizedExpression` with `treeItem.canEdit`).
    Visualized { tree_id: String, item_id: i64 },
    NewFunctionBreakpoint,
}

pub struct DebugView {
    /// Tree rows the user expanded, by their path (`<scope reference>/<name>/...`), and the call stack's sessions.
    pub expanded: HashSet<String>,
    pub collapsed_rows: HashSet<String>,
    pub editing: Option<Editing>,
    pub input: InputBox,
    pub input_view: super::input_box_view::InputView,
    pub input_focus: gpui::FocusHandle,
    /// The breakpoint Run to Cursor added, removed at the next stop or session end.
    pub run_to_cursor: Option<String>,
    pub selected: Option<String>,
    /// The list focus (listWidget.ts `setFocus`): the row last clicked or right-clicked.
    pub focused_row: Option<String>,
    /// The row under the mouse, whose action bar shows.
    pub hovered_row: Option<String>,
    /// The DOM focus of each view's tree, which turns its selection active and shows its focused row's outline.
    pub list_focus: std::collections::HashMap<&'static str, gpui::FocusHandle>,
    /// The glyph margin line under the pointer, which shows the breakpoint hint.
    pub hint: Option<(String, usize)>,
    /// The input element of the breakpoint widget, which shows one widget at a time.
    pub widget_view: super::input_box_view::InputView,
    pub widget_focus: gpui::FocusHandle,
    pub toolbar_drag: Option<super::debug_toolbar::ToolbarDrag>,
    /// The Stop button's dropdown chevron, which the `MenuId.DebugToolBarStop` menu opens under.
    pub stop_dropdown_bounds: std::rc::Rc<std::cell::Cell<gpui::Bounds<gpui::Pixels>>>,
    pub focus_session_bounds: std::rc::Rc<std::cell::Cell<gpui::Bounds<gpui::Pixels>>>,
    /// The `workbench.action.debug.focusProcess.{index}` commands the toolbar's session select registered.
    pub focus_session_commands: usize,
    pub exception: Option<super::exception_widget::ExceptionWidget>,
    /// variablesView.ts builds its tree in `renderBody`, the first time the view shows.
    pub variables_view_created: bool,
    /// A focus change expands the first scope only when the Variables view exists by then: `renderBody` sets the
    /// input it finds without expanding (variablesView.ts).
    pub expand_first_scope: bool,
    /// callStackView.ts builds its tree in `renderBody` too, and selects the focused frame only on a focus change after.
    pub call_stack_view_created: bool,
    /// Whether the Call Stack view existed at the last focus change (`updateTreeSelection` ran on it).
    pub call_stack_selects_focus: bool,
    /// variablesView.ts `variableInternalContext`: the variable row of the last variable menu, which Set Value edits.
    pub menu_variable: Option<Editing>,
    /// debugCommands.ts `dataBreakpointInfoResponse`: the last variable menu's `dataBreakpointInfo` answer.
    pub data_breakpoint_info: Option<serde_json::Value>,
    /// `Variable.errorMessage`: the adapter's setVariable error, the input's validation message until it closes.
    pub edit_error: Option<String>,
}

impl DebugView {
    pub fn new(cx: &mut gpui::App) -> Self {
        DebugView {
            expanded: HashSet::new(),
            collapsed_rows: HashSet::new(),
            editing: None,
            input: InputBox::default(),
            input_view: Default::default(),
            input_focus: cx.focus_handle(),
            run_to_cursor: None,
            selected: None,
            focused_row: None,
            hovered_row: None,
            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(),
            toolbar_drag: None,
            stop_dropdown_bounds: Default::default(),
            focus_session_bounds: Default::default(),
            focus_session_commands: 0,
            exception: None,
            variables_view_created: false,
            expand_first_scope: false,
            call_stack_view_created: false,
            call_stack_selects_focus: false,
            menu_variable: None,
            data_breakpoint_info: None,
            edit_error: None,
        }
    }
}

const ROW_HEIGHT: f32 = 22.;
/// debug.contribution.css: `.debug-pane` and `.debug-hover-widget` `.expression` labels use `--monaco-monospace-font` at 11px on
/// macOS; its first family, SF Mono, GPUI cannot load by name, so the editor's Menlo stands in as in walkthrough_part.rs.
pub(super) const EXPRESSION_FONT: &str = "Menlo";
pub(super) const EXPRESSION_FONT_SIZE: f32 = 11.;
const INDENT: f32 = 8.;
/// A tree row with its depth and whether it is selected, for the indent guides.
pub(super) type DebugTreeRow = (gpui::AnyElement, usize, bool);

impl Workbench {
    pub(super) fn mark_debug_views_created(&mut self) {
        if !self.debug_view.variables_view_created && self.is_view_visible(VARIABLES_VIEW) {
            self.debug_view.variables_view_created = true;
        }
        if !self.debug_view.call_stack_view_created && self.is_view_visible(CALL_STACK_VIEW) {
            self.debug_view.call_stack_view_created = true;
        }
    }

    /// `CONTEXT_DEBUG_UX` `simple`: no session and no launch configuration, the welcome view instead of the debug views.
    pub(super) fn debug_ux_simple(&self) -> bool {
        self.debug.state() == State::Inactive && self.debug.sessions.is_empty() && !self.workspace_folders().iter().any(|folder| !self.folder_launch(folder).configurations.is_empty())
    }

    /// The container's own views whose `when` holds, in their `order`, with whether each starts collapsed.
    pub(super) fn debug_views(&self) -> Vec<(&'static str, bool)> {
        if self.debug_ux_simple() {
            let mut views = vec![(DEBUG_WELCOME_VIEW, false)];
            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);
        // debug.contribution.ts view `order`: Loaded Scripts (35, `collapsed: true`) sits between Call Stack and Breakpoints.
        let mut views = vec![(VARIABLES_VIEW, false), (WATCH_VIEW, false), (CALL_STACK_VIEW, false), (BREAKPOINTS_VIEW, false)];
        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
    }

    /// The Run and Debug container: the title with the launch picker, then its panes; the welcome view alone merges
    /// into the container.
    pub(super) fn debug_side_bar(&self, window: &Window, cx: &mut Context<Self>) -> Div {
        let foreground = self.foreground_or("sideBar.foreground");
        let (has_start, actions) = self.debug_container_actions(window, cx);
        let title = self.side_bar_title_shared(self.view_header_text(&crate::nls::localize_in(DEBUG_CONTAINER, "Run and Debug"), false), has_start).child(actions);
        let frame = self.side_bar_frame().text_color(foreground).child(title);
        let container = super::view_panes::PaneContainer::Debug;
        let ids = self.panes(container).view.as_ref().expect("panes are laid out before they draw").ids().to_vec();
        if ids == [DEBUG_WELCOME_VIEW] {
            return frame.child(div().flex_1().min_h_0().flex().flex_col().child(self.debug_welcome(window, cx)));
        }
        let panes = ids.iter().filter(|id| self.debug_views().iter().any(|(view, _)| view == *id)).map(|&id| self.debug_view_pane(id, window, cx)).collect();
        let ordered = self.ordered_panes(&ids, panes, window, cx);
        frame.child(self.pane_view_element(container, ordered, window, cx)).child(div().h(px(5.)).flex_none())
    }

    /// welcomeView.ts contents with the debuggers' `viewsWelcome` for the `debug` view.
    fn debug_welcome(&self, window: &Window, cx: &mut Context<Self>) -> Div {
        let mut content = div().px(px(20.)).py(px(13.)).flex().flex_col().gap(px(13.)).text_size(px(13.));
        let link_color = self.color("textLink.foreground");
        let context = self.key_context(window);
        let key = self.keybindings.resolver.lookup_primary_keybinding("workbench.action.debug.start", &context).map(|item| crate::keybindings::label(&item.keybinding));
        let label = match key {
            Some(key) => format!("Run and Debug ({key})"),
            None => "Run and Debug".into(),
        };
        if !self.debug.debuggers.is_empty() {
            content = content.child(self.debug_welcome_button(&label, "workbench.action.debug.start", cx));
            if self.folder.is_some() {
                content = content.child(div().child(self.welcome_paragraph(&[("To customize Run and Debug ", None), ("create a launch.json file", Some("workbench.action.debug.configure")), (".", None)], link_color, cx)));
            }
        }
        for extension in &self.extensions {
            for welcome in extension.description["contributes"]["viewsWelcome"].as_array().into_iter().flatten().filter(|welcome| welcome["view"] == "debug") {
                if !self.welcome_when_holds(welcome["when"].as_str()) {
                    continue;
                }
                for line in welcome["contents"].as_str().unwrap_or_default().split('\n').filter(|line| !line.trim().is_empty()) {
                    content = content.child(self.welcome_line(line, link_color, cx));
                }
            }
        }
        content
    }

    fn welcome_when_holds(&self, when: Option<&str>) -> bool {
        let Some(when) = when.and_then(crate::contextkey::Expr::deserialize) else { return true };
        let mut context = self.context_keys.clone();
        if let Some(editor) = self.editors.active() {
            context.insert("debugStartLanguage".into(), json!(editor.document().language_id));
        }
        context.insert("isWeb".into(), json!(false));
        when.evaluate(&context)
    }

    /// viewPane.ts `WelcomeView` rendering of one line: a lone link is a button, else a paragraph with links.
    fn welcome_line(&self, line: &str, link_color: Rgba, cx: &mut Context<Self>) -> Div {
        let parts = markdown_links(line);
        if let [(label, Some(command))] = parts.as_slice() {
            return self.debug_welcome_button(label, command, cx);
        }
        let parts: Vec<(&str, Option<&str>)> = parts.iter().map(|(text, command)| (text.as_str(), command.as_deref())).collect();
        div().child(self.welcome_paragraph(&parts, link_color, cx))
    }

    fn debug_welcome_button(&self, label: &str, command: &str, cx: &mut Context<Self>) -> Div {
        let command = command.to_owned();
        let background = self.color("button.background");
        let hover = self.color("button.hoverBackground");
        let foreground = self.color("button.foreground");
        div().child(
            div()
                .id(gpui::SharedString::from(format!("welcome-{command}")))
                .h(px(26.))
                .w_full()
                .flex()
                .items_center()
                .justify_center()
                .rounded(px(4.))
                .bg(background)
                .text_color(foreground)
                .cursor_pointer()
                .hover(move |button| button.bg(hover))
                .child(self.button_label(label, foreground))
                .on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
                    let (id, args) = command_link(&command);
                    workbench.execute_command(&id, args, window, cx);
                })),
        )
    }

    fn welcome_paragraph(&self, parts: &[(&str, Option<&str>)], link_color: Rgba, cx: &mut Context<Self>) -> Div {
        let mut paragraph = div().flex().flex_wrap();
        for (index, (text, command)) in parts.iter().enumerate() {
            match command {
                None => paragraph = paragraph.child(text.to_string()),
                Some(command) => {
                    let command = command.to_string();
                    paragraph = paragraph.child(
                        div()
                            .id(("welcome-link", index))
                            .text_color(link_color)
                            .cursor_pointer()
                            .hover(|link| link.underline())
                            .child(text.to_string())
                            .on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
                                let (id, args) = command_link(&command);
                                workbench.execute_command(&id, args, window, cx);
                            })),
                    );
                }
            }
        }
        paragraph
    }

    /// debugActionViewItems.ts `StartDebugActionViewItem`: the green start button, the configuration name, then
    /// the gear of Open launch.json.
    fn start_debug_item(&self, cx: &mut Context<Self>) -> Div {
        let (_, selected) = self.selected_launch();
        let name = selected.unwrap_or_else(|| "No Configurations".into());
        let start_color = self.color("debugIcon.startForeground");
        let hover = self.color("toolbar.hoverBackground");
        let border = self.color("dropdown.border");
        let foreground = self.color("dropdown.foreground");
        // debugViewlet.css `.start-debug-action-item`: it alone shrinks, its configuration label to an ellipsis.
        div()
            .debug_selector(|| "start-debug-action-item".into())
            .flex()
            .items_center()
            .min_w_0()
            .overflow_hidden()
            .rounded(px(5.))
            .border_1()
            .border_color(border)
            .bg(self.color("dropdown.background"))
            .child(self.icon("debug-start", 22., 16., start_color).flex_shrink_0().id("debug-start").cursor_pointer().hover(move |button| button.bg(hover)).on_click(cx.listener(|workbench, _: &ClickEvent, window, cx| {
                workbench.execute_command("workbench.action.debug.start", Vec::new(), window, cx);
            })))
            .child(
                div()
                    .id("debug-configuration")
                    .flex()
                    .flex_1()
                    .items_center()
                    .min_w_0()
                    .h(px(22.))
                    .gap(px(4.))
                    .pl(px(6.))
                    .pr(px(4.))
                    .border_l_1()
                    .border_color(border)
                    .text_color(foreground)
                    .cursor_pointer()
                    .child(div().flex_1().min_w_0().truncate().text_size(px(12.)).child(name))
                    .child(self.icon("chevron-down", 10., 10., foreground).flex_shrink_0().opacity(0.75))
                    .on_click(cx.listener(|workbench, _: &ClickEvent, window, cx| {
                        workbench.execute_command("workbench.action.debug.selectandstart", Vec::new(), window, cx);
                    })),
            )
    }

    /// The container's `MenuId.ViewContainerTitle` (viewMenuActions.ts `ViewContainerMenuActions`): its `navigation`
    /// items, Start Debugging as the launch picker (debugViewlet.ts `getActionViewItem`), then the `...`.
    fn debug_container_actions(&self, window: &Window, cx: &mut Context<Self>) -> (bool, Div) {
        let context = self.view_container_context("debug", window);
        let holds = |expr: &Option<crate::contextkey::Expr>| expr.as_ref().is_none_or(|expr| expr.evaluate(&context));
        let foreground = self.foreground_or("icon.foreground");
        // debugToolBar.ts `debugViewTitleItems`: the toolbar's items, docked in the title while a session runs.
        let docked = context["debugState"] != "inactive" && context["config.debug.toolBarLocation"] == "docked";
        let mirrored = |item: &crate::menus::MenuItem| item.menu == MenuId::DebugToolBar && docked;
        let mut items: Vec<&crate::menus::MenuItem> = self.menus.iter().filter(|item| (item.menu == MenuId::ViewContainerTitle || mirrored(item)) && item.group == "navigation" && holds(&item.when)).collect();
        let stop_actions = if docked { crate::menus::menu_actions(&self.menus, MenuId::DebugToolBarStop, &context) } else { Vec::new() };
        items.sort_by(|a, b| a.order.total_cmp(&b.order).then_with(|| a.title.cmp(&b.title)));
        // debugViewlet.css `.has-start-debug-action-item > .title-actions`, padding.css `flex: 2`: only the launch picker
        // shrinks inside them.
        let has_start = items.iter().any(|item| matches!(&item.entry, Entry::Command { id, .. } if id == "workbench.action.debug.start"));
        let mut actions = div().debug_selector(|| "debug-title-actions".into()).flex().items_center().justify_end().gap(px(4.)).when(has_start, |actions| actions.flex_grow(2.).flex_basis(px(0.)).min_w_0());
        for item in items {
            actions = actions.child(match &item.entry {
                Entry::Command { id, precondition, alt, .. } if item.menu == MenuId::DebugToolBar => {
                    let (id, title, enabled) = match alt.as_ref().filter(|alt| window.modifiers().alt && holds(&alt.precondition)) {
                        Some(alt) => (alt.id.clone(), alt.title.clone(), true),
                        None => (id.clone(), item.title.clone(), holds(precondition)),
                    };
                    self.debug_toolbar_item(id, title, enabled, &context, &stop_actions, window, cx)
                }
                Entry::Command { id, .. } if id == "workbench.action.debug.start" => self.start_debug_item(cx).into_any_element(),
                Entry::Command { id, precondition, .. } if id == "workbench.action.debug.configure" => self.search_action("gear", "workbench.action.debug.configure", holds(precondition), cx).flex_shrink_0().into_any_element(),
                Entry::Command { id, .. } => self.command_button(id, item.title.clone(), Vec::new(), foreground, cx).flex_shrink_0().into_any_element(),
                Entry::Submenu { submenu, .. } => self.submenu_button(*submenu, self.submenu_icons.get(submenu), item.title.clone(), context.clone(), Vec::new(), foreground, cx).flex_shrink_0().into_any_element(),
            });
        }
        let more = self.has_view_toggle("debug") || !self.view_container_secondary_menu(&context).is_empty();
        (has_start, actions.when(more, |actions| actions.child(self.view_container_more_actions("debug", cx).flex_shrink_0())))
    }

    /// 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 => (
                "Breakpoints",
                vec![
                    ("add", "workbench.debug.viewlet.action.addFunctionBreakpointAction", true),
                    ("activate-breakpoints", "workbench.debug.viewlet.action.toggleBreakpointsActivatedAction", true),
                    ("close-all", "workbench.debug.viewlet.action.removeAllBreakpoints", !self.debug.model.breakpoints.is_empty() || !self.debug.model.function_breakpoints.is_empty()),
                ],
            ),
            VARIABLES_VIEW => ("Variables", Vec::new()),
            CALL_STACK_VIEW => ("Call Stack", Vec::new()),
            LOADED_SCRIPTS_VIEW => ("Loaded Scripts", Vec::new()),
            _ => ("Run", Vec::new()),
        };
        let list_focus = self.debug_view.list_focus.get(id);
        let menu_return = self.context_menu.as_ref().and_then(|menu| menu.focus_to_return.as_ref());
        let list_focused = list_focus.is_some_and(|focus| focus.is_focused(window) || menu_return == Some(focus));
        let rows = match id {
            VARIABLES_VIEW => self.variables_rows(list_focused, window, cx),
            WATCH_VIEW => self.watch_rows(list_focused, window, cx),
            CALL_STACK_VIEW => self.call_stack_rows(list_focused, cx),
            BREAKPOINTS_VIEW => self.breakpoint_rows(list_focused, window, cx),
            LOADED_SCRIPTS_VIEW => self.loaded_script_rows(list_focused, cx),
            _ => vec![(self.debug_welcome(window, cx).into_any_element(), 0, false)],
        };
        let bar = (!actions.is_empty()).then(|| {
            let bar = div().flex().gap(px(2.)).children(actions.into_iter().map(|(icon, command, enabled)| self.action_bar_item(id, command, self.search_action(icon, command, enabled, cx), cx)));
            bar.into_any_element()
        });
        // The tree takes the focus in the capture phase, before a row's menu records it as the focus to return to.
        let body = div().id(id).when_some(list_focus.cloned(), |body, focus| {
            body.track_focus(&focus).capture_any_mouse_down(move |_, window, cx| window.focus(&focus, cx))
        });
        let depths = rows.iter().map(|(_, depth, _)| *depth).collect();
        let active: Vec<usize> = rows.iter().enumerate().filter(|(_, (_, _, selected))| *selected).map(|(index, _)| index).collect();
        let group = gpui::SharedString::from(format!("{id}-tree"));
        let guides = self.tree_guides_in_group(group.clone(), depths, &active);
        let inset = self.pane_row_inset();
        let rows = rows.into_iter().enumerate().map(|(index, (row, _, _))| div().relative().child(row).children(guides.row(index, inset)));
        let body = self.scrollable(id, None, body.group(group).children(rows), cx).flex_1().into_any_element();
        super::view_panes::ViewPane { id, title: title.into(), description: None, actions: bar, draws_more: false, show_actions: false, body }
    }

    /// breakpointsView.ts `hintContainer`: `$(warning)` 3px after the title, shown by `update_breakpoints_hint`.
    pub(super) fn breakpoints_hint(&self) -> Option<gpui::AnyElement> {
        let hover = HoverContent::Markdown(json!({ "value": self.debug.breakpoints_hint.clone()?, "isTrusted": true }));
        let hint = div().id("breakpoint-warning").debug_selector(|| "breakpoint-warning".into()).flex().items_center().ml(px(3.)).child(self.icon("warning", 16., 16., self.foreground_or("icon.foreground")));
        Some(hint.child(self.hover_target("breakpoint-warning-hover", hover, HoverOptions::element())).into_any_element())
    }

    /// breakpointsView.ts `updateBreakpointsHint`, run on each breakpoints change and focused session change: while
    /// the warning applies it shows after the 4s `hintDelayer` (each run starts the delay again), else it hides.
    pub(crate) fn update_breakpoints_hint(&mut self, cx: &mut Context<Self>) {
        if self.unverified_breakpoints_message().is_none() {
            self.debug.breakpoints_hint = None;
            self.debug.breakpoints_hint_delay = None;
            return;
        }
        let delay = cx.background_executor().timer(std::time::Duration::from_millis(4000));
        self.debug.breakpoints_hint_delay = Some(cx.spawn(async move |this, cx| {
            delay.await;
            let _ = this.update(cx, |workbench, cx| {
                workbench.debug.breakpoints_hint = workbench.unverified_breakpoints_message();
                cx.notify();
            });
        }));
    }

    /// debugModel.ts `Breakpoint.verified`'s `textFileService.isDirty(uri)`: the file's model in any group is dirty.
    pub(super) fn breakpoint_file_is_dirty(&self, breakpoint: &crate::debug::Breakpoint) -> bool {
        self.editors.all_editors().any(|editor| editor.document().uri_string() == breakpoint.uri_string() && editor.is_dirty())
    }

    /// The focused session's debugger's `strings.unverifiedBreakpoints` while breakpoints are active and an enabled
    /// breakpoint in one of its languages is unverified.
    fn unverified_breakpoints_message(&self) -> Option<String> {
        let model = &self.debug.model;
        if !model.breakpoints_activated {
            return None;
        }
        let debugger = self.debug.debugger(self.debug.focused_session()?.configuration["type"].as_str()?)?;
        let message = debugger.contribution["strings"]["unverifiedBreakpoints"].as_str()?;
        let unverified = model.breakpoints.iter().any(|breakpoint| {
            let dirty = self.breakpoint_file_is_dirty(breakpoint);
            let path = crate::editor_history::file_path(&breakpoint.uri_string());
            let language = path.and_then(|path| self.languages.guess_language(&path, "").map(str::to_owned));
            breakpoint.base.enabled && !breakpoint.verified(dirty) && language.is_some_and(|language| debugger.interested_in_language(&language))
        });
        unverified.then(|| message.to_owned())
    }

    /// A tree row; listWidget.ts `MouseController` moves the list focus to a clicked or right-clicked row and the
    /// selection to a clicked one.
    pub(super) fn debug_row(&self, key: String, depth: usize, twistie_expanded: Option<bool>, selected: bool, list_focused: bool, cx: &Context<Self>) -> gpui::Stateful<Div> {
        let is_focus = self.debug_view.focused_row.as_deref() == Some(key.as_str());
        let (clicked, right_clicked, hovered) = (key.clone(), key.clone(), key.clone());
        let row = div()
            .id(gpui::SharedString::from(key.clone()))
            .debug_selector(move || key)
            .h(px(ROW_HEIGHT))
            .mx(px(self.pane_row_inset()))
            .rounded(px(4.))
            .flex()
            .items_center()
            .cursor_pointer()
            // abstractTree.ts `DefaultIndent` (8px) plus the twistie's translateX(3px) (tree.css).
            .pl(px(INDENT * depth as f32 + 11.))
            .on_mouse_down(MouseButton::Left, cx.listener(move |workbench, _: &MouseDownEvent, _, cx| {
                workbench.debug_view.focused_row = Some(clicked.clone());
                workbench.debug_view.selected = Some(clicked.clone());
                cx.notify();
            }))
            .on_mouse_down(MouseButton::Right, cx.listener(move |workbench, _: &MouseDownEvent, _, cx| {
                workbench.debug_view.focused_row = Some(right_clicked.clone());
                cx.notify();
            }))
            .on_hover(cx.listener(move |workbench, entered: &bool, _, cx| {
                set_hovered(&mut workbench.debug_view.hovered_row, &hovered, *entered);
                cx.notify();
            }));
        let row = self.list_row_selection(row, selected, is_focus, list_focused);
        let foreground = self.foreground_or("icon.foreground");
        // tree.css `.monaco-tl-twistie`: 16px and `padding-right: 6px` less the 3px shift, before the contents.
        let twistie = div().w(px(19.)).flex_none();
        row.child(match twistie_expanded {
            Some(true) => twistie.child(self.icon("chevron-down", 16., 16., foreground)),
            Some(false) => twistie.child(self.icon("chevron-right", 16., 16., foreground)),
            None => twistie,
        })
    }

    /// debugExpressionRenderer.ts `renderExpressionValue`: numbers, strings and booleans in their token colors.
    pub(super) fn value_color(&self, variable: &Variable) -> Rgba {
        let value = variable.value.as_str();
        if variable.error {
            return self.color("debugTokenExpression.error");
        }
        if value.parse::<f64>().is_ok() {
            return self.color("debugTokenExpression.number");
        }
        if value == "true" || value == "false" {
            return self.color("debugTokenExpression.boolean");
        }
        if value.starts_with('"') || value.starts_with('\'') || value.starts_with('`') {
            return self.color("debugTokenExpression.string");
        }
        self.color("debugTokenExpression.value")
    }

    /// `name: value` of a variable, watch or REPL result row; a lazy row's button sits between them.
    pub(super) fn expression_label(&self, variable: &Variable, highlights: &[std::ops::Range<usize>], lazy_button: Option<gpui::AnyElement>) -> Div {
        self.expression_label_in(variable, highlights, lazy_button, None)
    }

    /// `expression_label` whose name and value take part in `selectable`'s text selection.
    pub(super) fn expression_label_in(&self, variable: &Variable, highlights: &[std::ops::Range<usize>], lazy_button: Option<gpui::AnyElement>, selectable: Option<super::text_selection::TextSurface>) -> Div {
        let mut label = div().flex().min_w_0().overflow_hidden().whitespace_nowrap();
        if !variable.name.is_empty() {
            // debugExpressionRenderer.ts `renderVariable`: the name label is `name =`; debug.contribution.css puts the value 6px after it.
            let hint = &variable.presentation_hint;
            let dimmed = hint["kind"] == "virtual" || hint["visibility"] == "internal";
            let name = match variable.value.is_empty() {
                true => variable.name.clone(),
                false => format!("{} =", variable.name),
            };
            // Only the debug hover passes matches: outside a `.pane-body`, style.css recolors them with `list.highlightForeground`.
            let color = self.color("list.highlightForeground");
            let byte = |chars: usize| name.char_indices().nth(chars).map_or(name.len(), |(byte, _)| byte);
            let styles: Vec<_> = highlights.iter().map(|range| (byte(range.start)..byte(range.end), gpui::HighlightStyle { color: Some(color.into()), ..Default::default() })).collect();
            let name = gpui::SharedString::from(name);
            let text = gpui::StyledText::new(name.clone()).with_highlights(styles);
            let selection = selectable.map(|surface| self.selectable_text(surface, text.layout(), name, "\n"));
            label = label.child(div().relative().text_color(self.color("debugTokenExpression.name")).when(dimmed, |name| name.opacity(0.5)).children(selection).child(text));
        }
        let value = gpui::SharedString::from(variable.value.clone());
        let text = gpui::StyledText::new(value.clone());
        let separator = if variable.name.is_empty() { "\n" } else { "" };
        let selection = selectable.map(|surface| self.selectable_text(surface, text.layout(), value, separator));
        label.children(lazy_button).child(div().relative().when(!variable.name.is_empty(), |value| value.ml(px(6.))).text_color(self.value_color(variable)).overflow_hidden().text_ellipsis().children(selection).child(text))
    }

    /// baseDebugView.ts `lazyButton`: `$(eye)` 3px after the name, debug.contribution.css's 5px corners and
    /// debugColors.ts's `toolbar.hoverBackground` under the mouse.
    pub(super) fn lazy_button(&self, session: &str, parent_reference: i64, variable: &Variable, key: &str, cx: &mut Context<Self>) -> gpui::AnyElement {
        let (session, name, row_key) = (session.to_owned(), variable.name.clone(), key.to_owned());
        self.icon("eye", 16., 16., self.foreground_or("icon.foreground"))
            .id(gpui::SharedString::from(format!("{key}/lazy")))
            .flex_none()
            .self_center()
            .ml(px(3.))
            .rounded(px(4.))
            .hover(|button| button.bg(self.color("toolbar.hoverBackground")))
            .on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
                cx.stop_propagation();
                workbench.evaluate_lazy_row(&session, parent_reference, &name, &row_key, window, cx);
            }))
            .child(self.hover_target(gpui::SharedString::from(format!("{key}/lazy-hover")), super::hover::HoverContent::Text("Click to expand".into()), super::hover::HoverOptions::mouse()))
            .into_any_element()
    }

    fn variables_rows(&self, list_focused: bool, window: &Window, cx: &mut Context<Self>) -> Vec<DebugTreeRow> {
        let Some(session) = self.debug.focus.session.clone() else { return Vec::new() };
        let mut rows = Vec::new();
        let first_cheap = self.debug.scopes.iter().position(|scope| !scope.expensive);
        for (index, scope) in self.debug.scopes.iter().enumerate() {
            let key = format!("scope/{}", scope.name);
            let expanded = self.row_expanded(&key, self.debug_view.expand_first_scope && Some(index) == first_cheap);
            let reference = scope.variables_reference;
            let row_key = key.clone();
            let session_id = session.clone();
            let row = self
                .debug_row(key.clone(), 0, Some(expanded), self.row_selected(&key), list_focused, cx)
                .child(div().debug_selector(|| format!("{key}/label")).font_weight(gpui::FontWeight::BOLD).text_size(px(11.)).child(scope.name.clone()))
                .on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| workbench.toggle_debug_row(&row_key, expanded, &session_id, reference, window, cx)));
            rows.push((row.into_any_element(), 0, self.row_selected(&key)));
            if expanded {
                self.variable_children(&session, reference, &key, 1, false, list_focused, &mut rows, window, cx);
            }
        }
        rows
    }

    #[allow(clippy::too_many_arguments)]
    fn variable_children(&self, session: &str, reference: i64, parent: &str, depth: usize, in_watch: bool, list_focused: bool, rows: &mut Vec<DebugTreeRow>, window: &Window, cx: &mut Context<Self>) {
        let Some(children) = self.debug.children.get(&(session.to_owned(), reference)) else { return };
        for variable in children {
            let key = format!("{parent}/{}", variable.name);
            let visualizer_row = (session.to_owned(), reference, variable.name.clone());
            if let Some(visualized) = self.debug.visualizers.visualized.get(&visualizer_row) {
                self.visualized_rows(&visualized.tree_id, &visualized.item, Some(&visualizer_row), key, depth, list_focused, rows, window, cx);
                continue;
            }
            let expandable = variable.has_children();
            let expanded = expandable && self.row_expanded(&key, false);
            let (row_key, session_id, child_reference) = (key.clone(), session.to_owned(), variable.variables_reference);
            let edit = Editing::Variable { session: session.to_owned(), parent_reference: reference, name: variable.name.clone(), watch: in_watch };
            if self.debug_view.editing.as_ref() == Some(&edit) {
                rows.push((self.debug_input_row(key, depth, list_focused, window, cx), depth, false));
                continue;
            }
            let lazy_button = variable.is_lazy().then(|| self.lazy_button(session, reference, variable, &key, cx));
            let group = gpui::SharedString::from(key.clone());
            let menu_row = match in_watch {
                true => VariableMenuRow::WatchVariable { session: session.to_owned(), parent_reference: reference, variable: variable.clone() },
                false => VariableMenuRow::Variable { menu: MenuId::DebugVariablesContext, session: session.to_owned(), parent_reference: reference, variable: variable.clone() },
            };
            let actions = self.row_action_bar(self.row_shows_actions(&key)).child(self.variable_inline_actions(&menu_row, window, cx)).children(self.visualizer_actions(&visualizer_row, cx));
            let mut row = self.debug_row(key.clone(), depth, expandable.then_some(expanded), self.row_selected(&key), list_focused, cx).group(group).child(self.expression_label(variable, &[], lazy_button).font_family(EXPRESSION_FONT).text_size(px(EXPRESSION_FONT_SIZE))).child(actions);
            // variablesView.ts `onMouseDblClick`: a variable that `canSetExpressionValue` opens its value's input.
            let editable = !in_watch && self.can_set_variable_value(variable);
            row = row.on_click(cx.listener(move |workbench, event: &ClickEvent, window, cx| {
                if editable && event.click_count() == 2 {
                    workbench.start_debug_view_edit(edit.clone(), window, cx);
                    return;
                }
                if expandable {
                    workbench.toggle_debug_row(&row_key, expanded, &session_id, child_reference, window, cx);
                }
            }));
            row = row.on_mouse_down(MouseButton::Right, cx.listener(move |workbench, event: &MouseDownEvent, window, cx| {
                workbench.show_variable_menu(menu_row.clone(), gpui::Bounds::new(event.position, Default::default()), window, cx);
            }));
            rows.push((row.into_any_element(), depth, self.row_selected(&key)));
            if expanded {
                self.variable_children(session, variable.variables_reference, &key, depth + 1, in_watch, list_focused, rows, window, cx);
            }
        }
    }

    /// debugViewlet.css `.monaco-list-row:hover .monaco-action-bar, .monaco-list-row.focused .monaco-action-bar`.
    pub(super) fn row_shows_actions(&self, key: &str) -> bool {
        self.debug_view.focused_row.as_deref() == Some(key) || self.debug_view.hovered_row.as_deref() == Some(key)
    }

    pub(super) fn row_selected(&self, key: &str) -> bool {
        self.debug_view.selected.as_deref() == Some(key)
    }

    pub(super) fn row_expanded(&self, key: &str, default: bool) -> bool {
        if self.debug_view.expanded.contains(key) {
            return true;
        }
        default && !self.debug_view.collapsed_rows.contains(key)
    }

    fn toggle_debug_row(&mut self, key: &str, expanded: bool, session: &str, reference: i64, window: &mut Window, cx: &mut Context<Self>) {
        if expanded {
            self.debug_view.expanded.remove(key);
            self.debug_view.collapsed_rows.insert(key.to_owned());
        } else {
            self.debug_view.collapsed_rows.remove(key);
            self.debug_view.expanded.insert(key.to_owned());
            self.fetch_children(session, reference, window, cx);
        }
        self.debug_view.selected = Some(key.to_owned());
        cx.notify();
    }

    fn watch_rows(&self, list_focused: bool, window: &Window, cx: &mut Context<Self>) -> Vec<DebugTreeRow> {
        let mut rows = Vec::new();
        let session = self.debug.focus.session.clone().unwrap_or_default();
        for expression in &self.debug.model.watch_expressions {
            let key = format!("watch/{}", expression.id);
            if [Some(Editing::Watch(expression.id.clone())), Some(Editing::WatchValue(expression.id.clone()))].contains(&self.debug_view.editing) {
                rows.push((self.debug_input_row(key, 0, list_focused, window, cx), 0, false));
                continue;
            }
            let value = self.debug.watch_values.get(&expression.id).cloned().unwrap_or_else(|| Variable { name: expression.name.clone(), value: "not available".into(), ..Variable::default() });
            let expandable = value.has_children();
            let expanded = expandable && self.row_expanded(&key, false);
            let (row_key, session_id, reference, id) = (key.clone(), session.clone(), value.variables_reference, expression.id.clone());
            let menu_row = VariableMenuRow::WatchExpression { id: expression.id.clone(), name: expression.name.clone() };
            let actions = self.row_action_bar(self.row_shows_actions(&key)).child(self.variable_inline_actions(&menu_row, window, cx));
            let mut row = self.debug_row(key.clone(), 0, expandable.then_some(expanded), self.row_selected(&key), list_focused, cx).child(self.expression_label(&Variable { name: expression.name.clone(), ..value.clone() }, &[], None).debug_selector(|| format!("{key}/label")).font_family(EXPRESSION_FONT).text_size(px(EXPRESSION_FONT_SIZE))).child(actions);
            row = row.on_click(cx.listener(move |workbench, event: &ClickEvent, window, cx| {
                if event.click_count() == 2 {
                    workbench.start_debug_view_edit(Editing::Watch(id.clone()), window, cx);
                    return;
                }
                if expandable {
                    workbench.toggle_debug_row(&row_key, expanded, &session_id, reference, window, cx);
                }
            }));
            row = row.on_mouse_down(MouseButton::Right, cx.listener(move |workbench, event: &MouseDownEvent, window, cx| {
                workbench.show_variable_menu(menu_row.clone(), gpui::Bounds::new(event.position, Default::default()), window, cx);
            }));
            rows.push((row.into_any_element(), 0, self.row_selected(&key)));
            if expanded {
                self.variable_children(&session, value.variables_reference, &key, 1, true, list_focused, &mut rows, window, cx);
            }
        }
        if self.debug_view.editing == Some(Editing::NewWatch) {
            rows.push((self.debug_input_row("watch/new".into(), 0, list_focused, window, cx), 0, false));
        }
        rows
    }

    fn call_stack_rows(&self, list_focused: bool, cx: &mut Context<Self>) -> Vec<DebugTreeRow> {
        let mut rows = Vec::new();
        let call_stack_menu = |item: CallStackItem| cx.listener(move |workbench, event: &MouseDownEvent, window, cx| workbench.show_call_stack_menu(&item, gpui::Bounds::new(event.position, Default::default()), window, cx));
        let sessions = &self.debug.sessions;
        // callStackView.ts `getChildren`: one session shows its threads; more show the root sessions as rows.
        // shortcut: no sticky `isMultiSessionView`, a parent left alone by its ended child loses its row.
        let several = sessions.len() > 1;
        let mut shown = Vec::new();
        match several {
            true => sessions.iter().filter(|session| session.parent.is_none()).for_each(|root| shown_call_stack_sessions(sessions, root, 0, &mut shown)),
            false => shown.extend(sessions.first().map(|session| (session, 0))),
        }
        let label_background = self.color("debugView.stateLabelBackground");
        let label_foreground = self.color("debugView.stateLabelForeground");
        // callStackView.ts: the state labels are `.monaco-count-badge.long`, which modernUI padding.css and
        // roundedCorners.css pad 2px 4px to an 18px minimum height with 4px corners.
        let state_label = |text: String| div().ml_auto().mr(px(8.)).px(px(4.)).py(px(2.)).min_h(px(18.)).flex().items_center().rounded(px(4.)).text_size(px(10.)).bg(label_background).text_color(label_foreground).child(text.to_uppercase());
        for (session, session_depth) in shown {
            let depth = session_depth + usize::from(several);
            if several {
                // `SessionsRenderer`: the state of the session's first stopped thread.
                let state = session.threads.iter().find(|thread| thread.stopped).map_or_else(|| "Running".to_owned(), |thread| thread.state_label());
                // modernUI fontRamp.css: session state labels are `text-transform: capitalize` at `fontSize.label2`, and
                // padding.css drops their right margin.
                let state = super::capitalize_words(&state);
                let state = div().flex_none().ml_auto().px(px(4.)).py(px(2.)).min_h(px(18.)).flex().items_center().rounded(px(4.)).text_size(px(11.)).bg(label_background).text_color(label_foreground).child(state);
                let item = CallStackItem::Session(session.id.clone());
                rows.push((self.debug_row(format!("session/{}", session.id), session_depth, Some(true), false, list_focused, cx).child(self.icon("bug", 16., 16., self.foreground_or("icon.foreground"))).child(div().min_w_0().truncate().child(session.name.clone())).child(state).on_mouse_down(MouseButton::Right, call_stack_menu(item)).into_any_element(), session_depth, false));
            }
            for thread in &session.threads {
                let thread_key = format!("thread/{}/{}", session.id, thread.id);
                // "Only show the threads in the call stack if there is more than 1 thread."
                let show_thread = session.threads.len() > 1;
                if show_thread {
                    let item = CallStackItem::Thread(session.id.clone(), thread.id);
                    rows.push((self.debug_row(thread_key.clone(), depth, Some(true), false, list_focused, cx).child(thread.name.clone()).child(state_label(thread.state_label())).on_mouse_down(MouseButton::Right, call_stack_menu(item)).into_any_element(), depth, false));
                }
                let frame_depth = depth + usize::from(show_thread);
                let frames = &thread.frames;
                let mut index = 0;
                while index < frames.len() {
                    let frame = &frames[index];
                    index += 1;
                    // callStackView.ts `getThreadChildren`: two or more deemphasized frames in a row fold into one row.
                    let shown_key = format!("deemphasized/{}/{}", session.id, frame.id);
                    let run = frames[index - 1..].iter().take_while(|frame| frame.deemphasized() && frame.source.is_object()).count();
                    if run > 1 && !self.debug_view.expanded.contains(&shown_key) {
                        let folded = &frames[index - 1..index - 1 + run];
                        let keys: Vec<String> = folded.iter().map(|frame| format!("deemphasized/{}/{}", session.id, frame.id)).collect();
                        let label = show_more_label(folded);
                        rows.push((
                            self.debug_row(format!("more-frames/{}/{}", session.id, frame.id), frame_depth, None, false, list_focused, cx)
                                .justify_center()
                                .text_color(self.color("textLink.foreground"))
                                .child(div().opacity(0.5).child(label))
                                .on_click(cx.listener(move |workbench, _: &ClickEvent, _, cx| {
                                    workbench.debug_view.expanded.extend(keys.iter().cloned());
                                    cx.notify();
                                }))
                                .into_any_element(),
                            frame_depth,
                            false,
                        ));
                        index += run - 1;
                        continue;
                    }
                    let frame_menu = call_stack_menu(CallStackItem::Frame(session.id.clone(), thread.id, index - 1));
                    if frame.presentation_hint.as_deref() == Some("label") {
                        rows.push((self.debug_row(format!("frame/{}/{}", session.id, frame.id), frame_depth, None, false, list_focused, cx).justify_center().italic().text_color(self.color("descriptionForeground")).child(frame.name.clone()).on_mouse_down(MouseButton::Right, frame_menu).into_any_element(), frame_depth, false));
                        continue;
                    }
                    let focused = self.debug_view.call_stack_selects_focus && self.debug.focus.session.as_deref() == Some(session.id.as_str()) && self.debug.focus.frame == Some(frame.id);
                    let (session_id, thread_id, frame_id) = (session.id.clone(), thread.id, frame.id);
                    let row = self
                        .debug_row(format!("frame/{}/{}", session.id, frame.id), frame_depth, None, focused, list_focused, cx)
                        .when(frame.deemphasized(), |row| row.opacity(0.7))
                        .overflow_hidden()
                        .child(div().flex_1().flex_shrink_0().whitespace_nowrap().font_family(EXPRESSION_FONT).text_size(px(EXPRESSION_FONT_SIZE)).child(frame.name.clone()))
                        .child(self.frame_file(frame, focused))
                        .on_mouse_down(MouseButton::Right, frame_menu)
                        .on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
                            let focus = super::debug_service::DebugFocus { session: Some(session_id.clone()), thread: Some(thread_id), frame: Some(frame_id) };
                            workbench.set_debug_focus(focus, super::debug_service::Reveal::PreservingFocus, window, cx);
                        }));
                    rows.push((row.into_any_element(), frame_depth, focused));
                }
                if thread.stopped && thread.total_frames.is_some() {
                    let (session_id, thread_id) = (session.id.clone(), thread.id);
                    let row = self
                        .debug_row(format!("more/{}/{}", session.id, thread.id), frame_depth, None, false, list_focused, cx)
                        .text_color(self.color("textLink.foreground"))
                        .child("Load More Stack Frames")
                        .on_click(cx.listener(move |workbench, _: &ClickEvent, _, cx| workbench.fetch_more_frames(&session_id, thread_id, cx)));
                    rows.push((row.into_any_element(), frame_depth, false));
                }
            }
        }
        rows
    }

    /// callStackView.ts `StackFramesRenderer`: the source name 0.8em before the `line:column` count badge, which
    /// debugColors.ts draws at 60% opacity outside the selected row.
    fn frame_file(&self, frame: &StackFrame, selected: bool) -> Div {
        let alpha = if selected { 1. } else { 0.6 };
        let faded = |color: Rgba| Rgba { a: color.a * alpha, ..color };
        let line = match frame.column {
            0 => frame.line.to_string(),
            column => format!("{}:{column}", frame.line),
        };
        let badge = div()
            .flex_none()
            .min_w(px(18.))
            .min_h(px(18.))
            .px(px(4.))
            .rounded(px(11.))
            .flex()
            .items_center()
            .justify_center()
            .text_size(px(11.))
            .bg(faded(self.color("badge.background")))
            .text_color(faded(self.color("badge.foreground")))
            .when_some(self.theme.color("contrastBorder"), |badge, border| badge.border_1().border_color(border))
            .child(line);
        let name = div().min_w_0().mr(px(10.4)).overflow_hidden().whitespace_nowrap().text_ellipsis().child(frame.source_name());
        div().flex().min_w_0().ml(px(10.4)).mr(px(12.)).justify_end().items_center().overflow_hidden().child(name).child(badge)
    }

    /// breakpointsView.ts `updateSize` and debugViewlet.ts `updateBreakpointsMaxSize`: the body fits up to
    /// `MAX_VISIBLE_BREAKPOINTS` (9) rows and grows no further while another debug view is expanded.
    pub(super) fn limit_breakpoints_pane(&mut self) {
        let model = &self.debug.model;
        let new_function = usize::from(self.debug_view.editing == Some(Editing::NewFunctionBreakpoint));
        let rows = model.exception_breakpoints_for(self.debug.focus.session.as_deref()).count() + model.function_breakpoints.len() + new_function + model.breakpoints.len() + model.instruction_breakpoints.len();
        let minimum = (9. * ROW_HEIGHT).min(rows as f32 * ROW_HEIGHT);
        let Some(view) = self.panes_mut(super::view_panes::PaneContainer::Debug).view.as_mut() else { return };
        let Some(index) = view.ids().iter().position(|&id| id == BREAKPOINTS_VIEW) else { return };
        let all_others_collapsed = (0..view.ids().len()).all(|other| other == index || !view.is_expanded(other));
        view.set_body_limits(index, minimum, if all_others_collapsed { f32::INFINITY } else { minimum });
    }

    fn breakpoint_rows(&self, list_focused: bool, window: &Window, cx: &mut Context<Self>) -> Vec<DebugTreeRow> {
        let mut rows = Vec::new();
        let model = &self.debug.model;
        let focused = self.debug.focus.session.as_deref();
        let description = self.color("descriptionForeground");
        let debug_active = matches!(self.debug.state(), State::Running | State::Stopped);
        for breakpoint in model.exception_breakpoints_for(focused).collect::<Vec<_>>() {
            let id = breakpoint.base.id.clone();
            let enabled = breakpoint.base.enabled;
            rows.push(
                self.debug_row(format!("exception/{id}"), 0, None, self.row_selected(&format!("exception/{id}")), list_focused, cx)
                    .child(self.debug_checkbox(&id, enabled, cx))
                    .child(div().child(breakpoint.label.clone()))
                    .into_any_element(),
            );
        }
        for breakpoint in &model.function_breakpoints {
            let id = breakpoint.base.id.clone();
            let icon = if !breakpoint.base.enabled || !model.breakpoints_activated { "debug-breakpoint-function-disabled" } else { "debug-breakpoint-function" };
            rows.push(
                self.debug_row(format!("function/{id}"), 0, None, self.row_selected(&format!("function/{id}")), list_focused, cx)
                    .child(self.breakpoint_row_icon(icon))
                    .child(self.debug_checkbox(&id, breakpoint.base.enabled, cx))
                    .child(div().child(breakpoint.name.clone()))
                    .into_any_element(),
            );
        }
        if self.debug_view.editing == Some(Editing::NewFunctionBreakpoint) {
            rows.push(self.debug_input_row("function/new".into(), 0, list_focused, window, cx));
        }
        for breakpoint in &model.breakpoints {
            let id = breakpoint.id().to_owned();
            let dirty = self.breakpoint_file_is_dirty(breakpoint);
            let (icon, _) = super::breakpoint_widget::breakpoint_icon(breakpoint, model, debug_active, dirty);
            let path = crate::uri::json_fs_path(&breakpoint.uri);
            let name = path.rsplit(std::path::is_separator).next().unwrap_or_default().to_owned();
            let folder = self.relative_folder_label(&path);
            let line = breakpoint.line_number();
            let uri = breakpoint.uri.clone();
            rows.push(
                self.debug_row(format!("breakpoint/{id}"), 0, None, self.row_selected(&format!("breakpoint/{id}")), list_focused, cx)
                    .child(self.breakpoint_row_icon(icon))
                    .child(self.debug_checkbox(&id, breakpoint.base.enabled, cx))
                    .child(div().flex_none().child(name))
                    .child(div().flex_1().min_w_0().ml(px(6.)).overflow_hidden().whitespace_nowrap().text_ellipsis().text_size(px(12.)).text_color(description).child(folder))
                    .child(div().flex_none().mr(px(8.)).px(px(4.)).rounded(px(11.)).text_size(px(11.)).bg(self.color("badge.background")).text_color(self.color("badge.foreground")).child(line.to_string()))
                    .on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
                        let Some(path) = (uri["scheme"] == "file").then(|| std::path::PathBuf::from(crate::uri::json_fs_path(&uri))) else { return };
                        workbench.open_file(path.clone(), false, window, cx);
                        let line = line as usize;
                        workbench.select_range(&path, crate::anything_quick_access::TextRange { start_line_number: line, start_column: 1, end_line_number: line, end_column: 1 }, cx);
                    }))
                    .into_any_element(),
            );
        }
        // breakpointsView.ts `renderInstructionBreakpoint`: the address, the regular icon unless disabled or unsupported.
        for breakpoint in &model.instruction_breakpoints {
            let id = breakpoint.base.id.clone();
            let icon = if !breakpoint.base.enabled || !model.breakpoints_activated {
                "debug-breakpoint-disabled"
            } else if !breakpoint.supported() {
                "debug-breakpoint-unverified"
            } else {
                "debug-breakpoint"
            };
            rows.push(
                self.debug_row(format!("instruction/{id}"), 0, None, self.row_selected(&format!("instruction/{id}")), list_focused, cx)
                    .child(self.breakpoint_row_icon(icon))
                    .child(self.debug_checkbox(&id, breakpoint.base.enabled, cx))
                    .child(div().child(format!("0x{:x}", breakpoint.address)))
                    .into_any_element(),
            );
        }
        // A flat list: no row has a parent whose guides it could make active.
        rows.into_iter().map(|row| (row, 0, false)).collect()
    }

    fn loaded_script_rows(&self, list_focused: bool, cx: &mut Context<Self>) -> Vec<DebugTreeRow> {
        let Some(session) = self.debug.focused_session() else { return Vec::new() };
        session
            .loaded_sources
            .iter()
            .map(|source| {
                let name = source["name"].as_str().or(source["path"].as_str()).unwrap_or_default().to_owned();
                let key = format!("source/{name}");
                (self.debug_row(key.clone(), 0, None, self.row_selected(&key), list_focused, cx).child(name).into_any_element(), 0, self.row_selected(&key))
            })
            .collect()
    }

    /// The folder of a breakpoint's file relative to the workspace (`labelService.getUriLabel(dirname, { relative })`).
    fn relative_folder_label(&self, path: &str) -> String {
        let parent = std::path::Path::new(path).parent().unwrap_or(std::path::Path::new(""));
        for folder in self.workspace_folders() {
            if let Ok(relative) = parent.strip_prefix(&folder) {
                return relative.to_string_lossy().into_owned();
            }
        }
        parent.to_string_lossy().into_owned()
    }

    pub(super) fn breakpoint_icon(&self, icon: &str, size: f32) -> Div {
        let (file, color) = super::breakpoint_widget::icon_file_and_color(icon);
        self.icon(file, size, size, self.color(color))
    }

    /// debugViewlet.css `.breakpoint > .codicon`, 19px wide in the twistie's place (`.breakpoint { margin-left: -19px }`).
    fn breakpoint_row_icon(&self, icon: &str) -> Div {
        div().w(px(19.)).ml(px(-19.)).flex_none().flex().justify_center().child(self.breakpoint_icon(icon, 16.))
    }

    /// The enablement checkbox of a breakpoint row (breakpointsView.ts `createCheckbox`).
    fn debug_checkbox(&self, id: &str, enabled: bool, cx: &mut Context<Self>) -> Div {
        let id = id.to_owned();
        let border = self.color("checkbox.border");
        let background = self.color("checkbox.background");
        // debugViewlet.css `.breakpoint .monaco-custom-toggle.monaco-checkbox`: 18px, `margin-right: 4px`.
        let mut checkbox = div().id(gpui::SharedString::from(format!("check-{id}"))).debug_selector({
            let id = id.clone();
            move || format!("check-{id}")
        }).size(px(18.)).flex_none().mr(px(4.)).rounded(px(3.)).border_1().border_color(border).bg(background).flex().items_center().justify_center();
        if enabled {
            checkbox = checkbox.child(self.icon("check", 14., 14., self.color("checkbox.foreground")));
        }
        div().child(checkbox.on_mouse_down(MouseButton::Left, cx.listener(move |workbench, _: &MouseDownEvent, _, cx| {
            cx.stop_propagation();
            let change = workbench.debug.model.set_enablement(&id, !enabled);
            workbench.breakpoints_changed(change, true, cx);
        })))
    }

    pub(super) fn start_debug_view_edit(&mut self, editing: Editing, window: &mut Window, cx: &mut Context<Self>) {
        let mut input = InputBox::default();
        let initial_value = match &editing {
            Editing::Watch(id) => self.debug.model.watch_expressions.iter().find(|expression| expression.id == *id).map(|expression| expression.name.clone()),
            Editing::WatchValue(id) => self.debug.watch_values.get(id).map(|value| value.value.clone()),
            Editing::Variable { session, parent_reference, name, .. } => self.debug.children.get(&(session.clone(), *parent_reference)).and_then(|children| children.iter().find(|child| child.name == *name)).map(|variable| variable.value.clone()),
            Editing::Visualized { tree_id, item_id } => self.visualized_item(tree_id, *item_id).map(|item| item["description"].as_str().unwrap_or_default().to_owned()),
            Editing::NewWatch | Editing::NewFunctionBreakpoint => None,
        };
        if let Some(value) = initial_value {
            input.set_value(value);
            input.select_all();
        }
        self.debug_view.input = input;
        self.debug_view.editing = Some(editing);
        window.focus(&self.debug_view.input_focus, cx);
        cx.notify();
    }

    /// The inline input of the Variables, Watch and Breakpoints views: Enter accepts, Escape cancels, as the trees'
    /// `renderInputBox` does; a failed setVariable's message shows under it (inputBox.css `.monaco-inputbox-message`).
    pub(super) fn debug_input_row(&self, key: String, depth: usize, list_focused: bool, window: &Window, cx: &mut Context<Self>) -> gpui::AnyElement {
        let focused = self.debug_view.input_focus.is_focused(window);
        let error = self.debug_view.edit_error.as_ref().filter(|_| matches!(self.debug_view.editing, Some(Editing::Variable { .. })));
        let border = self.color(if error.is_some() { "inputValidation.errorBorder" } else { "focusBorder" });
        let message = error.map(|message| {
            // Deferred, so it paints over the rows below as the reference's context view does.
            gpui::deferred(
                div()
                    .absolute()
                    .top(px(21.))
                    .left_0()
                    .right_0()
                    .p(px(4.8))
                    .text_size(px(12.))
                    .line_height(px(17.))
                    .bg(self.color("inputValidation.errorBackground"))
                    .text_color(self.foreground_or("inputValidation.errorForeground"))
                    .border_1()
                    .border_color(border)
                    .child(message.clone()),
            )
        });
        self.debug_row(key, depth, None, false, list_focused, cx)
            .child(
                div()
                    .relative()
                    .flex_1()
                    .h(px(20.))
                    .mr(px(4.))
                    .px(px(4.))
                    .flex()
                    .bg(self.color("input.background"))
                    .border_1()
                    .border_color(border)
                    .on_key_down(cx.listener(|workbench, event: &KeyDownEvent, window, cx| match event.keystroke.key.as_str() {
                        "enter" => workbench.accept_debug_view_input(window, cx),
                        "escape" => {
                            workbench.debug_view.editing = None;
                            workbench.debug_view.edit_error = None;
                            cx.notify();
                        }
                        _ => {}
                    }))
                    .child(self.input_text(InputId::DebugView, InputLook { password: false, placeholder: None, focused }, cx))
                    .children(message),
            )
            .into_any_element()
    }

    fn accept_debug_view_input(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        self.debug_view.edit_error = None;
        let value = self.debug_view.input.value.trim().to_owned();
        match self.debug_view.editing.take() {
            Some(Editing::NewWatch) if !value.is_empty() => _ = self.debug.model.add_watch_expression(&value),
            Some(Editing::Watch(id)) if value.is_empty() => self.debug.model.remove_watch_expressions(Some(&id)),
            Some(Editing::Watch(id)) => self.debug.model.rename_watch_expression(&id, &value),
            Some(Editing::NewFunctionBreakpoint) if !value.is_empty() => {
                let change = self.debug.model.add_function_breakpoint(&value, &json!({}), None);
                self.breakpoints_changed(change, true, cx);
            }
            Some(target @ (Editing::Variable { .. } | Editing::WatchValue(_))) => {
                let value = self.debug_view.input.value.clone();
                return self.set_variable_value(target, value, window, cx);
            }
            Some(Editing::Visualized { tree_id, item_id }) => return self.edit_visualized_item(tree_id, item_id, self.debug_view.input.value.clone(), window, cx),
            _ => {}
        }
        self.store_debug_model();
        self.refresh_focus(window, cx);
    }

    pub(super) fn edit_debug_view_input(&mut self, edit: impl FnOnce(&mut InputBox), cx: &mut Context<Self>) {
        edit(&mut self.debug_view.input);
        cx.notify();
    }
}

/// The session rows under `session` with their depth, merging a session into its only child session when that one is
/// compressible, as `CallStackCompressionDelegate` does: the merged row shows the last session.
fn shown_call_stack_sessions<'a>(sessions: &'a [Session], session: &'a Session, depth: usize, shown: &mut Vec<(&'a Session, usize)>) {
    let children = |parent: &Session| sessions.iter().filter(|child| child.parent.as_deref() == Some(parent.id.as_str())).collect::<Vec<_>>();
    let compressible = |session: &Session| session.options["compact"] == true || sessions.iter().any(|child| child.parent.as_deref() == Some(session.id.as_str()) && child.options["compact"] == true);
    let mut last = session;
    loop {
        let child_sessions = children(last);
        let other_children = match last.threads.as_slice() {
            [thread] => thread.frames.len(),
            threads => threads.len(),
        };
        match child_sessions.as_slice() {
            [only] if other_children == 0 && compressible(only) => last = only,
            _ => break,
        }
    }
    shown.push((last, depth));
    for child in children(last) {
        shown_call_stack_sessions(sessions, child, depth + 1, shown);
    }
}

/// `ShowMoreRenderer`: the folded frames' common source `origin`, as js-debug's "Skipped by skipFiles", else their count.
fn show_more_label(frames: &[StackFrame]) -> String {
    let origin = frames[0].source["origin"].as_str().filter(|origin| frames.iter().all(|frame| frame.source["origin"].as_str() == Some(*origin)));
    match origin {
        Some(origin) => format!("Show {} More: {origin}", frames.len()),
        None => format!("Show {} More Stack Frames", frames.len()),
    }
}

/// `command:` links of welcome content: the id and its JSON arguments.
fn command_link(link: &str) -> (String, Vec<Value>) {
    let link = link.strip_prefix("command:").unwrap_or(link);
    match link.split_once('?') {
        Some((id, query)) => {
            let decoded = crate::debug::session::percent_decode(query);
            let args = match serde_json::from_str::<Value>(&decoded) {
                Ok(Value::Array(args)) => args,
                Ok(arg) => vec![arg],
                Err(_) => Vec::new(),
            };
            (id.to_owned(), args)
        }
        None => (link.to_owned(), Vec::new()),
    }
}

/// `[label](target)` links of one welcome line, with the text between them.
fn markdown_links(line: &str) -> Vec<(String, Option<String>)> {
    let mut parts = Vec::new();
    let mut rest = line.trim();
    while let Some(start) = rest.find('[') {
        let Some(middle) = rest[start..].find("](") else { break };
        let Some(end) = rest[start + middle..].find(')') else { break };
        if start > 0 {
            parts.push((rest[..start].to_owned(), None));
        }
        parts.push((rest[start + 1..start + middle].to_owned(), Some(rest[start + middle + 2..start + middle + end].to_owned())));
        rest = &rest[start + middle + end + 1..];
    }
    if !rest.is_empty() {
        parts.push((rest.to_owned(), None));
    }
    parts
}

/// A row's `on_hover`: entering it marks it hovered, leaving it clears the mark it still holds.
pub(super) fn set_hovered(hovered: &mut Option<String>, key: &str, entered: bool) {
    if entered {
        *hovered = Some(key.to_owned());
    } else if hovered.as_deref() == Some(key) {
        *hovered = None;
    }
}

#[cfg(test)]
mod tests {
    use std::path::Path;

    use gpui::TestAppContext;

    use super::*;
    use crate::host_sync::HostSync;
    use crate::languages::Languages;
    use crate::theme::load_theme;

    /// breakpointsView.ts `updateSize`: beside expanded debug views the Breakpoints body is as tall as its rows, and the
    /// others share the rest by weight, as `restoreViewSizes` runs after it.
    #[gpui::test]
    fn the_breakpoints_pane_is_as_tall_as_its_rows(cx: &mut TestAppContext) {
        let (workbench, cx, _host) = super::super::variable_menu::tests::stopped_session(cx, json!({}));
        workbench.update(cx, |workbench, cx| {
            workbench.debug.model.add_breakpoints(&json!({ "scheme": "file", "path": "/app.js" }), vec![crate::debug::BreakpointData::at(5)]);
            workbench.show_debug_view(cx);
        });
        cx.update(|window, cx| drop(window.draw(cx)));
        let sizes = workbench.read_with(cx, |workbench, _| {
            let view = workbench.panes(super::super::view_panes::PaneContainer::Debug).view.as_ref().unwrap();
            view.ids().iter().copied().zip(view.sizes().iter().copied()).collect::<Vec<_>>()
        });
        assert_eq!(sizes, [(VARIABLES_VIEW, 392.), (WATCH_VIEW, 238.), (CALL_STACK_VIEW, 294.), (BREAKPOINTS_VIEW, super::super::view_panes::HEADER_SIZE + ROW_HEIGHT)]);
    }

    /// debugViewlet.css: a breakpoint's icon takes the twistie's place (`margin-left: -19px`), so its checkbox lines up
    /// with the exception rows' 30px into the row.
    #[gpui::test]
    fn a_breakpoint_checkbox_starts_where_the_twistie_ends(cx: &mut TestAppContext) {
        let (workbench, cx, _host) = super::super::variable_menu::tests::stopped_session(cx, json!({}));
        let id = workbench.update(cx, |workbench, cx| {
            workbench.debug.model.add_breakpoints(&json!({ "scheme": "file", "path": "/app.js" }), vec![crate::debug::BreakpointData::at(5)]);
            workbench.show_debug_view(cx);
            workbench.debug.model.breakpoints[0].id().to_owned()
        });
        cx.update(|window, cx| drop(window.draw(cx)));
        let row = cx.debug_bounds(format!("breakpoint/{id}").leak()).expect("the breakpoint row");
        let checkbox = cx.debug_bounds(format!("check-{id}").leak()).expect("the breakpoint's checkbox");
        assert_eq!(checkbox.left() - row.left(), px(30.));
    }
    #[gpui::test]
    fn every_section_header_shows_while_a_session_runs(cx: &mut TestAppContext) {
        let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
        let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
        let theme = load_theme(&[themes], "Dark Modern").unwrap();
        let (workbench, cx) = cx.add_window_view(|_, cx| {
            let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), crate::default_settings(), HostSync::new(std::sync::mpsc::channel().0), cx);
            let mut session = crate::debug::session::Session::new("s".into(), 1, json!({ "name": "Launch", "type": "node", "request": "launch" }), json!({}), None, json!({}));
            session.capabilities = json!({ "supportsLoadedSourcesRequest": true });
            session.set_threads(&[json!({ "id": 1, "name": "main" })]);
            for index in 0..40 {
                session.accept_loaded_source(&json!({ "reason": "new", "source": { "name": format!("s{index}.js"), "path": format!("/s{index}.js") } }));
            }
            workbench.debug.sessions.push(session);
            workbench.debug.sessions.push(crate::debug::session::Session::new("c".into(), 2, json!({ "name": "Child", "type": "pwa-node", "request": "launch" }), json!({}), None, json!({ "parentSessionId": "s" })));
            workbench.debug.focus.session = Some("s".into());
            workbench.show_debug_view(cx);
            workbench
        });
        cx.run_until_parked();
        let (ids, sizes) = workbench.read_with(cx, |workbench, _| {
            let view = workbench.panes(super::super::view_panes::PaneContainer::Debug).view.as_ref().unwrap();
            (view.ids().to_vec(), view.sizes())
        });
        assert_eq!(ids, [VARIABLES_VIEW, WATCH_VIEW, CALL_STACK_VIEW, LOADED_SCRIPTS_VIEW, BREAKPOINTS_VIEW]);
        assert!(sizes.iter().all(|size| *size >= super::super::view_panes::HEADER_SIZE), "{sizes:?}");
    }

    #[gpui::test]
    fn the_breakpoints_header_warns_of_an_unverified_breakpoint_in_the_debuggers_language(cx: &mut TestAppContext) {
        let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
        let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
        let javascript = exthost::scan::scan_extension(&app_root.join("extensions/javascript"), true).unwrap();
        let theme = load_theme(&[themes], "Dark Modern").unwrap();
        let (workbench, cx) = cx.add_window_view(|_, cx| {
            let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[javascript]), crate::default_settings(), HostSync::new(std::sync::mpsc::channel().0), cx);
            let contribution = json!({ "languages": ["javascript"], "strings": { "unverifiedBreakpoints": "Some breakpoints are unbound." } });
            workbench.debug.debuggers.push(crate::debug::configuration::Debugger { debug_type: "node".into(), contribution, extension_id: "a.node".into() });
            workbench.debug.sessions.push(crate::debug::session::Session::new("s".into(), 1, json!({ "name": "Launch", "type": "node", "request": "launch" }), json!({}), None, json!({})));
            workbench.debug.focus.session = Some("s".into());
            let uri = json!({ "scheme": "file", "path": "/a.js" });
            workbench.debug.model.add_breakpoints(&uri, vec![crate::debug::BreakpointData::at(5)]);
            workbench.show_debug_view(cx);
            workbench
        });
        cx.update(|window, cx| drop(window.draw(cx)));
        assert!(cx.debug_bounds("breakpoint-warning").is_none(), "a breakpoint without session data counts as verified");
        workbench.update(cx, |workbench, cx| {
            let id = workbench.debug.model.breakpoints[0].id().to_owned();
            let change = workbench.debug.model.set_breakpoint_session_data("s", &json!({}), Some(&[(id, json!({ "verified": false }))]));
            workbench.breakpoints_changed(change, false, cx);
        });
        let hint_after = |ms: u64, cx: &mut gpui::VisualTestContext| {
            cx.executor().advance_clock(std::time::Duration::from_millis(ms));
            cx.run_until_parked();
            cx.update(|window, cx| drop(window.draw(cx)));
            cx.debug_bounds("breakpoint-warning").is_some()
        };
        assert!(!hint_after(3999, cx), "the hint waits for the 4s hintDelayer");
        assert!(hint_after(1, cx));
    }

    /// listWidget.ts `MouseController.onContextMenu`: a right-click moves the list focus to the row and focuses the
    /// tree, which outlines the row with `list.focusOutline`.
    #[gpui::test]
    fn a_right_clicked_call_stack_row_takes_the_list_focus(cx: &mut TestAppContext) {
        let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
        let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
        let theme = load_theme(&[themes], "Dark Modern").unwrap();
        let (workbench, cx) = cx.add_window_view(|_, cx| {
            let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), crate::default_settings(), HostSync::new(std::sync::mpsc::channel().0), cx);
            let mut session = crate::debug::session::Session::new("s".into(), 1, json!({ "name": "Launch", "type": "node", "request": "launch" }), json!({}), None, json!({}));
            session.set_threads(&[json!({ "id": 1, "name": "main" })]);
            let thread = session.thread_mut(1).unwrap();
            thread.stopped = true;
            let frame = |id: i64, name: &str| StackFrame { id, name: name.into(), source: json!({ "path": "/app.js" }), line: 5, column: 2, ..Default::default() };
            thread.frames = vec![frame(1, "main"), frame(2, "<anonymous>")];
            workbench.debug.sessions.push(session);
            workbench.debug.focus = super::super::debug_service::DebugFocus { session: Some("s".into()), thread: Some(1), frame: Some(1) };
            workbench.show_debug_view(cx);
            workbench
        });
        cx.update(|window, cx| drop(window.draw(cx)));
        assert!(cx.debug_bounds("list-focus-outline").is_none());
        let row = cx.debug_bounds("frame/s/2").expect("the second frame's row");
        cx.simulate_mouse_down(row.center(), MouseButton::Right, gpui::Modifiers::none());
        cx.simulate_mouse_up(row.center(), MouseButton::Right, gpui::Modifiers::none());
        cx.update(|window, cx| drop(window.draw(cx)));
        let returns_to_tree = workbench.read_with(cx, |workbench, _| workbench.context_menu.as_ref().and_then(|menu| menu.focus_to_return.clone()) == Some(workbench.debug_view.list_focus[CALL_STACK_VIEW].clone()));
        assert!(returns_to_tree, "the frame menu returns the focus to the Call Stack tree");
        let outline = cx.debug_bounds("list-focus-outline").expect("the focused row's outline");
        assert_eq!(outline, row);
    }

    /// callStackView.ts: a Call Stack view first shown after the stop (`openOnDebugBreak`) builds its tree without the
    /// selection; `updateTreeSelection` selects the focused frame from the next focus change on.
    #[gpui::test]
    fn the_call_stack_selects_the_focused_frame_only_after_a_focus_change_it_saw(cx: &mut TestAppContext) {
        let (workbench, cx, _host) = super::super::variable_menu::tests::stopped_session(cx, json!({}));
        let focus = super::super::debug_service::DebugFocus { session: Some("s".into()), thread: Some(1), frame: Some(9) };
        let selects = |workbench: &gpui::Entity<Workbench>, cx: &mut gpui::VisualTestContext| workbench.read_with(cx, |workbench, _| workbench.debug_view.call_stack_selects_focus);
        workbench.update_in(cx, |workbench, window, cx| workbench.set_debug_focus(focus.clone(), super::super::debug_service::Reveal::No, window, cx));
        assert!(!selects(&workbench, cx), "the view does not exist yet");
        workbench.update(cx, |workbench, cx| workbench.show_debug_view(cx));
        cx.update(|window, cx| drop(window.draw(cx)));
        assert!(!selects(&workbench, cx), "showing the view keeps the selection empty");
        workbench.update_in(cx, |workbench, window, cx| workbench.set_debug_focus(focus, super::super::debug_service::Reveal::No, window, cx));
        assert!(selects(&workbench, cx));
    }

    /// debugViewlet.css `.debug-pane .scope`: font-weight bold, font-size 11px.
    #[gpui::test]
    fn scope_rows_draw_at_11px(cx: &mut TestAppContext) {
        let (workbench, cx, _host) = super::super::variable_menu::tests::stopped_session(cx, json!({}));
        workbench.update(cx, |workbench, cx| {
            workbench.debug.scopes = vec![Variable { name: "Local: main".into(), variables_reference: 4, ..Variable::default() }];
            workbench.show_debug_view(cx);
        });
        cx.update(|window, cx| drop(window.draw(cx)));
        let width = cx.debug_bounds("scope/Local: main/label").expect("the scope row's label").size.width;
        let shape = |weight, cx: &mut gpui::VisualTestContext| cx.update(|window, _| {
            let font = gpui::Font { weight, ..gpui::font(".SystemUIFont") };
            let run = gpui::TextRun { len: "Local: main".len(), font, color: gpui::black(), background_color: None, underline: None, strikethrough: None };
            window.text_system().shape_line("Local: main".into(), px(11.), &[run], None).width
        });
        // The test text system shapes bold .SystemUIFont as wide as regular, so this checks the 11px; ui-pair checks the weight.
        let bold = shape(gpui::FontWeight::BOLD, cx);
        assert!((width - bold).abs() < px(0.5), "debugViewlet.css `.debug-pane .scope`: {width:?} for bold 11px {bold:?}");
    }

    /// abstractTree.ts `DefaultIndent` 8px, then tree.css's 16px twistie with its 6px padding: a scope's label starts
    /// 30px into its row, as ui-pair `debug/visualizer.json` local.png measures in the reference.
    #[gpui::test]
    fn a_scope_label_starts_after_the_tree_s_twistie(cx: &mut TestAppContext) {
        let (workbench, cx, _host) = super::super::variable_menu::tests::stopped_session(cx, json!({}));
        workbench.update(cx, |workbench, cx| {
            workbench.debug.scopes = vec![Variable { name: "Local: main".into(), variables_reference: 4, ..Variable::default() }];
            workbench.show_debug_view(cx);
        });
        cx.update(|window, cx| drop(window.draw(cx)));
        let row = cx.debug_bounds("scope/Local: main").expect("the scope row");
        let label = cx.debug_bounds("scope/Local: main/label").expect("the scope row's label");
        assert_eq!(label.left() - row.left(), px(30.));
    }

    /// abstractTree.ts `_renderIndentGuides` in the Variables tree: a variable under its scope draws its scope's guide
    /// 16px into the row (tree.css `.monaco-tl-indent`).
    #[gpui::test]
    fn a_variable_row_draws_its_scopes_indent_guide(cx: &mut TestAppContext) {
        let (workbench, cx, _host) = super::super::variable_menu::tests::stopped_session(cx, json!({}));
        workbench.update(cx, |workbench, cx| {
            workbench.debug.scopes = vec![Variable { name: "Local".into(), variables_reference: 4, ..Variable::default() }];
            workbench.debug.children.insert(("s".into(), 4), vec![Variable { name: "x".into(), value: "1".into(), ..Variable::default() }]);
            workbench.debug_view.expanded.insert("scope/Local".into());
            workbench.show_debug_view(cx);
        });
        cx.update(|window, cx| drop(window.draw(cx)));
        let row = cx.debug_bounds("scope/Local/x").expect("the variable row");
        let guide = cx.debug_bounds("tree-guide").expect("the variable's guide");
        assert_eq!((guide.left() - row.left(), guide.top(), guide.size.height), (px(16.), row.top(), row.size.height));
    }

    /// debug.contribution.css: a watch row's `.expression` label is 11px monospace on macOS.
    #[gpui::test]
    fn watch_expression_labels_use_the_monospace_font(cx: &mut TestAppContext) {
        let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();
        let themes = exthost::scan::scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();
        let theme = load_theme(&[themes], "Dark Modern").unwrap();
        let (narrow, wide) = (String::from("iiiiiiii"), String::from("MMMMMMMM"));
        let (workbench, cx) = cx.add_window_view(|_, cx| {
            let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), crate::default_settings(), HostSync::new(std::sync::mpsc::channel().0), cx);
            workbench.debug.sessions.push(crate::debug::session::Session::new("s".into(), 1, json!({ "name": "Launch", "type": "node", "request": "launch" }), json!({}), None, json!({})));
            workbench.show_debug_view(cx);
            workbench
        });
        workbench.update(cx, |workbench, cx| {
            let watch = |id: &str, name: &String| crate::debug::WatchExpression { id: id.into(), name: name.clone() };
            workbench.debug.model.watch_expressions = vec![watch("narrow", &narrow), watch("wide", &wide)];
            cx.notify();
        });
        cx.update(|window, cx| drop(window.draw(cx)));
        let narrow_width = cx.debug_bounds("watch/narrow/label").expect("the narrow watch row's label").size.width;
        let wide_width = cx.debug_bounds("watch/wide/label").expect("the wide watch row's label").size.width;
        let menlo = cx.update(|window, _| {
            let text = format!("{wide} =not available");
            let run = gpui::TextRun { len: text.len(), font: gpui::font(EXPRESSION_FONT), color: gpui::black(), background_color: None, underline: None, strikethrough: None };
            window.text_system().shape_line(text.into(), px(EXPRESSION_FONT_SIZE), &[run], None).width
        });
        assert_eq!((narrow_width, wide_width), (wide_width, (menlo + px(6.)).round()));
    }

    /// callStackView.ts `ShowMoreRenderer`.
    #[test]
    fn folded_frames_name_their_common_origin() {
        let frame = |source: Value| StackFrame { source, ..Default::default() };
        let skipped = || frame(json!({ "path": "/n.js", "origin": "Skipped by skipFiles" }));
        assert_eq!(show_more_label(&[skipped(), skipped()]), "Show 2 More: Skipped by skipFiles");
        assert_eq!(show_more_label(&[skipped(), frame(json!({ "path": "/a.js" }))]), "Show 2 More Stack Frames");
        assert_eq!(show_more_label(&[frame(json!({ "path": "/a.js" }))]), "Show 1 More Stack Frames");
    }

    /// callStackView.ts `getChildren` with `CallStackCompressionDelegate`: js-debug's parent session and its compact
    /// child are one row showing the child; a session that is not compact keeps its own row.
    #[test]
    fn a_compact_child_session_merges_into_its_parent_row() {
        let session = |id: &str, options: Value| crate::debug::session::Session::new(id.into(), 1, json!({ "name": id }), json!({}), None, options);
        let mut child = session("app.js", json!({ "parentSessionID": "launch", "compact": true }));
        child.set_threads(&[json!({ "id": 1, "name": "main" })]);
        let sessions = [session("launch", json!({})), child, session("worker", json!({ "parentSessionID": "app.js" })), session("other", json!({}))];
        let mut shown = Vec::new();
        for root in sessions.iter().filter(|session| session.parent.is_none()) {
            shown_call_stack_sessions(&sessions, root, 0, &mut shown);
        }
        let shown: Vec<_> = shown.iter().map(|(session, depth)| (session.id.as_str(), *depth)).collect();
        assert_eq!(shown, [("app.js", 0), ("worker", 1), ("other", 0)]);
    }

    #[test]
    fn welcome_lines_split_into_text_and_links() {
        assert_eq!(markdown_links("[JavaScript Debug Terminal](command:extension.js-debug.createDebuggerTerminal)"), vec![("JavaScript Debug Terminal".into(), Some("command:extension.js-debug.createDebuggerTerminal".into()))]);
        assert_eq!(markdown_links("To customize, [open a folder](command:x) now."), vec![("To customize, ".into(), None), ("open a folder".into(), Some("command:x".into())), (" now.".into(), None)]);
        assert_eq!(command_link("command:a.b?%5B1%5D"), ("a.b".into(), vec![json!(1)]));
    }
}