Skip to content

Visual Studio Code, rebuilt in Rust

Rust
61.8 KB
Raw Blame
//! The Debug Console (repl.ts, replViewer.ts): the REPL elements of the focused session's output and evaluations,
//! and the input that evaluates an expression in the focused frame.

use std::cell::Cell;
use std::collections::HashSet;
use std::rc::Rc;

use gpui::{Bounds, ClickEvent, Context, Div, FocusHandle, MouseButton, MouseDownEvent, Pixels, SharedString, StyledText, Task, Window, div, prelude::*, px};
use serde_json::{Value, json};

use super::Workbench;
use super::debug_commands::REPL_VIEW_ID;
use super::debug_console_find::{FIND_PADDING, repl_output_label};
use super::input_box_view::{InputId, InputLook, InputView};
use crate::commands::Outcome;
use crate::debug::ansi::AnsiColor;
use crate::debug::session::{ReplElement, Severity, Variable};
use super::panel::PanelView;
use super::text_selection::TextSurface;
use super::view_filter::ViewFilter;
use crate::history::HistoryNavigator;
use crate::input_box::InputBox;

/// debug.ts `DEBUG_PANEL_ID`, the panel container of the Debug Console view.
pub const DEBUG_PANEL_ID: &str = "workbench.panel.repl";

/// repl.ts workspace storage keys.
const HISTORY_STORAGE_KEY: &str = "debug.repl.history";
const FILTER_HISTORY_STORAGE_KEY: &str = "debug.repl.filterHistory";
const FILTER_VALUE_STORAGE_KEY: &str = "debug.repl.filterValue";

/// The console's texts in the window's `TextSelection` (repl.css `user-select: text`).
const REPL_TEXTS: TextSurface = "repl";

pub struct DebugConsole {
    pub focus: FocusHandle,
    pub input_focus: FocusHandle,
    pub input: InputBox,
    pub input_view: InputView,
    /// The evaluated inputs, newest last, stored in the workspace for the next window.
    history: HistoryNavigator,
    pub filter: InputBox,
    pub filter_view: InputView,
    pub filter_focus: FocusHandle,
    filter_history: HistoryNavigator,
    /// The `ReplFilter` query, applied 300 ms after the filter input changes.
    filter_query: String,
    filtering: Option<Task<()>>,
    filter_menu_bounds: Rc<Cell<Bounds<Pixels>>>,
    session_menu_bounds: Rc<Cell<Bounds<Pixels>>>,
    /// The `workbench.action.debug.selectRepl.<index>` commands registered so far.
    select_commands: usize,
    /// The tree's input while it is not the focused session's console: an inactive session picked, or the ended one.
    pub(super) selected_session: Option<String>,
    /// repl.ts `sessionsToIgnore`: inactive sessions whose console was cleared.
    ignored_sessions: HashSet<String>,
    pub(super) find: super::debug_hover::TreeFind,
}

impl DebugConsole {
    pub fn new(cx: &mut gpui::App) -> Self {
        DebugConsole {
            focus: cx.focus_handle(),
            input_focus: cx.focus_handle(),
            input: InputBox::default(),
            input_view: InputView::default(),
            history: HistoryNavigator::new(Vec::new(), 100),
            filter: InputBox::default(),
            filter_view: InputView::default(),
            filter_focus: cx.focus_handle(),
            filter_history: HistoryNavigator::new(Vec::new(), 100),
            filter_query: String::new(),
            filtering: None,
            filter_menu_bounds: Rc::default(),
            session_menu_bounds: Rc::default(),
            select_commands: 0,
            selected_session: None,
            ignored_sessions: HashSet::new(),
            find: super::debug_hover::TreeFind::new(cx),
        }
    }
}

impl Workbench {
    /// debug.contribution.ts registers the Debug Console container in the panel at order 2, after Output.
    pub(super) fn register_debug_console_panel_view(&mut self) {
        self.register_panel_view(PanelView {
            id: DEBUG_PANEL_ID,
            view_id: REPL_VIEW_ID,
            title: "Debug Console",
            open: |workbench, window, cx| workbench.open_debug_console(true, window, cx),
            render: |workbench, window, cx| workbench.debug_console_body(window, cx).into_any_element(),
            actions: |workbench, window, cx| {
                let find = workbench.search_action("search", "repl.action.find", true, cx);
                let clear = workbench.search_action("clear-all", "workbench.debug.panel.action.clearReplAction", true, cx);
                div()
                    .flex()
                    .items_center()
                    .when(workbench.view_filter_in_header(REPL_VIEW_ID), |actions| actions.child(workbench.debug_console_filter_box(window, cx)))
                    .child(workbench.action_bar_item(REPL_VIEW_ID, "find", find, cx).debug_selector(|| "repl-title-find".into()))
                    .when(workbench.repl_sessions().len() > 1, |actions| actions.child(workbench.action_bar_item(REPL_VIEW_ID, "session", workbench.repl_session_select(cx), cx)))
                    .child(workbench.action_bar_item(REPL_VIEW_ID, "clear", clear, cx).debug_selector(|| "repl-title-clear".into()))
                    .into_any_element()
            },
            visible: |_| true,
            badge: |_| None,
        });
    }

    /// The Repl view's constructor: the input history, the filter text and its history from workspace storage.
    pub(super) fn restore_debug_console_state(&mut self) {
        let storage = self.workspace_storage.lock().unwrap();
        let input_history = storage.get(HISTORY_STORAGE_KEY).and_then(|raw| serde_json::from_str(raw).ok()).unwrap_or_default();
        let filter_text = storage.get(FILTER_VALUE_STORAGE_KEY).unwrap_or_default().to_owned();
        let history = storage.get(FILTER_HISTORY_STORAGE_KEY).and_then(|raw| serde_json::from_str(raw).ok()).unwrap_or_default();
        drop(storage);
        let console = &mut self.debug_console;
        console.history = HistoryNavigator::new(input_history, 100);
        console.filter = InputBox::default();
        console.filter.set_value(filter_text.clone());
        console.filter_query = filter_text;
        console.filter_history = HistoryNavigator::new(history, 100);
    }

    /// `FilterWidget.onDidChangeFilterText` after its 300 ms delay: the query applies and `saveState` stores it.
    pub(super) fn edit_debug_console_filter(&mut self, edit: impl FnOnce(&mut InputBox), window: &mut Window, cx: &mut Context<Self>) {
        let before = self.debug_console.filter.value.clone();
        edit(&mut self.debug_console.filter);
        cx.notify();
        if self.debug_console.filter.value == before {
            return;
        }
        self.debug_console.filtering = Some(cx.spawn_in(window, async move |workbench, cx| {
            cx.background_executor().timer(std::time::Duration::from_millis(300)).await;
            let _ = workbench.update(cx, |workbench, cx| {
                let console = &mut workbench.debug_console;
                console.filter_query = console.filter.value.clone();
                console.filter_history.add_to_history(&console.filter_query, false);
                let mut storage = workbench.workspace_storage.lock().unwrap();
                match console.filter_query.is_empty() {
                    true => storage.delete(FILTER_VALUE_STORAGE_KEY),
                    false => storage.set(FILTER_VALUE_STORAGE_KEY, console.filter_query.clone()),
                }
                match console.filter_history.elements().is_empty() {
                    true => storage.delete(FILTER_HISTORY_STORAGE_KEY),
                    false => storage.set(FILTER_HISTORY_STORAGE_KEY, json!(console.filter_history.elements()).to_string()),
                }
                drop(storage);
                cx.notify();
            });
        }));
    }

    /// `history.showPrevious` and `history.showNext` in the filter box.
    pub(super) fn show_debug_console_filter_history_value(&mut self, previous: bool, window: &mut Window, cx: &mut Context<Self>) {
        let console = &mut self.debug_console;
        let value = match previous {
            true => console.filter_history.show_previous_value(&console.filter.value),
            false => Some(console.filter_history.show_next_value(&console.filter.value)),
        };
        if let Some(value) = value {
            self.edit_debug_console_filter(|input| input.set_value(value), window, cx);
        }
    }

    fn debug_console_filter_box(&self, window: &Window, cx: &mut Context<Self>) -> Div {
        let shown = self.shown_repl_elements();
        let filtered = shown.iter().filter(|element| self.repl_element_visible(element)).count();
        let total = shown.len();
        let console = &self.debug_console;
        self.view_filter_box(
            ViewFilter {
                container: REPL_VIEW_ID,
                input: InputId::DebugConsoleFilter,
                focused: console.filter_focus.is_focused(window),
                placeholder: "Filter (e.g. text, !exclude, \\escape)",
                more_filters_checked: false,
                badge: (total != filtered && total != 0).then(|| format!("Showing {filtered} of {total}")),
                menu_bounds: console.filter_menu_bounds.clone(),
                show_menu: None,
            },
            cx,
        )
    }

    /// replFilter.ts `ReplFilter.filter`: inputs, results and variables always show; an output shows unless an
    /// `!exclude` term matches it, and, when include terms exist, only if one of them matches.
    fn repl_element_visible(&self, element: &ReplElement) -> bool {
        let text = match element {
            ReplElement::Evaluation { .. } => return true,
            ReplElement::Variable { .. } => return true,
            ReplElement::Output { value, source, count, .. } => repl_output_label(value, source.as_ref().map(|(path, _)| path.as_str()), *count),
        };
        let mut include_present = false;
        let mut include_matched = false;
        for (exclude, query) in parse_repl_filter(&self.debug_console.filter_query) {
            let matched = crate::filters::matches_fuzzy(&query, &text).is_some();
            if exclude && matched {
                return false;
            }
            if !exclude {
                include_present = true;
                include_matched |= matched;
            }
        }
        !include_present || include_matched
    }

    /// repl.ts `selectSession`: the picked or ended session, the focused one, else the first not cleared.
    pub(super) fn shown_repl_session(&self) -> Option<String> {
        let ignored = &self.debug_console.ignored_sessions;
        if let Some(selected) = self.debug_console.selected_session.as_ref().filter(|id| !ignored.contains(*id)) {
            return Some(self.repl_owner(selected));
        }
        if let Some(focused) = &self.debug.focus.session {
            return Some(self.repl_owner(focused));
        }
        let first = self.debug.sessions_including_inactive().into_iter().find(|session| !ignored.contains(&session.id));
        first.map(|session| self.repl_owner(&session.id)).or_else(|| self.debug.repl.last().map(|element| self.repl_owner(repl_element_session(element))))
    }

    /// `mapFocusedSessionToSelected`: a session that merges its console with its parent's writes to the parent's.
    fn repl_owner(&self, session_id: &str) -> String {
        let mut owner = session_id;
        while let Some(session) = self.debug.sessions_including_inactive().into_iter().find(|session| session.id == owner) {
            match &session.parent {
                Some(parent) if session.options["repl"] == "mergeWithParent" => owner = parent,
                _ => break,
            }
        }
        owner.to_owned()
    }

    fn shown_repl_elements(&self) -> Vec<&ReplElement> {
        let shown = self.shown_repl_session();
        self.debug.repl.iter().filter(|element| Some(self.repl_owner(repl_element_session(element))) == shown).collect()
    }

    /// `SelectReplActionViewItem.getSessions`: the sessions with a console of their own.
    fn repl_sessions(&self) -> Vec<&crate::debug::session::Session> {
        let separate = |session: &&crate::debug::session::Session| session.parent.is_none() || session.options["repl"] != "mergeWithParent";
        self.debug.sessions_including_inactive().into_iter().filter(separate).filter(|session| !self.debug_console.ignored_sessions.contains(&session.id)).collect()
    }

    /// `FocusSessionActionViewItem`: the selected console's session, child sessions indented.
    fn repl_session_select(&self, cx: &mut Context<Self>) -> gpui::Stateful<Div> {
        let shown = self.shown_repl_session();
        let label = self.repl_sessions().into_iter().find(|session| Some(&session.id) == shown.as_ref()).map(|session| session.name.clone()).unwrap_or_default();
        let bounds = self.debug_console.session_menu_bounds.clone();
        let foreground = self.foreground_or("dropdown.foreground");
        div()
            .id("repl-session-select")
            .relative()
            // actionbar.css `.select-container`: `flex: 1` up to 170px. shortcut: fixed 170px, where the reference
            // shrinks to 60px in a panel too narrow for its actions; flex it if a narrow panel matters.
            .w(px(170.))
            .overflow_hidden()
            .h(px(24.))
            .flex()
            .items_center()
            .pl(px(8.))
            .pr(px(23.))
            .border_1()
            .rounded(px(4.))
            .cursor_pointer()
            .text_size(px(11.))
            .whitespace_nowrap()
            .bg(self.color("dropdown.background"))
            .border_color(self.color("dropdown.border"))
            .text_color(foreground)
            .child(label)
            .child(self.icon("chevron-down", 16., 16., foreground).absolute().right(px(4.)))
            .child(super::output_view::bounds_tracker(bounds.clone()))
            .on_mouse_down(gpui::MouseButton::Left, cx.listener({
                let bounds = bounds.clone();
                move |workbench, _: &gpui::MouseDownEvent, window, cx| {
                    cx.stop_propagation();
                    workbench.show_repl_session_menu(bounds.get(), window, cx);
                }
            }))
            .on_click(cx.listener(move |workbench, event: &ClickEvent, window, cx| {
                if event.is_keyboard() {
                    workbench.show_repl_session_menu(bounds.get(), window, cx);
                }
            }))
    }

    /// The select box's options, each running `workbench.action.debug.selectRepl` for its session.
    fn show_repl_session_menu(&mut self, anchor: Bounds<Pixels>, window: &mut Window, cx: &mut Context<Self>) {
        let count = self.repl_sessions().len();
        while self.debug_console.select_commands < count {
            let index = self.debug_console.select_commands;
            self.commands.register(format!("workbench.action.debug.selectRepl.{index}"), move |workbench, _, window, cx| {
                let Some(session) = workbench.repl_sessions().get(index).map(|session| session.id.clone()) else { return Outcome::done() };
                workbench.select_repl(&session, window, cx);
                Outcome::done()
            });
            self.debug_console.select_commands += 1;
        }
        let shown = self.shown_repl_session();
        let mut actions = Vec::new();
        for (index, session) in self.repl_sessions().into_iter().enumerate() {
            let title = match session.parent {
                Some(_) => format!("\u{a0}\u{a0}{}", session.name),
                None => session.name.clone(),
            };
            actions.push(crate::menus::MenuAction::Command { id: format!("workbench.action.debug.selectRepl.{index}"), title, enabled: true, checked: Some(&session.id) == shown.as_ref(), alt: None });
        }
        let context = self.key_context(window);
        self.show_context_menu_actions(actions, &context, anchor, Vec::new(), window, cx);
    }

    /// repl.ts `selectRepl`: focus the session, or its stopped or first child (`resolveChildSession`).
    pub(super) fn select_repl(&mut self, session_id: &str, window: &mut Window, cx: &mut Context<Self>) {
        if self.debug.session(session_id).is_none() {
            self.debug_console.selected_session = Some(session_id.to_owned());
            cx.notify();
            return;
        }
        self.debug_console.selected_session = None;
        let target = self.resolve_child_session(session_id);
        let focus = self.debug.focus_target(Some(&target), None);
        self.set_debug_focus(focus, super::debug_service::Reveal::No, window, cx);
    }

    /// debugUtils.ts `resolveChildSession`: the session's stopped child, else its first child, else the session.
    pub(super) fn resolve_child_session(&self, session_id: &str) -> String {
        let children: Vec<_> = self.debug.sessions.iter().filter(|session| session.parent.as_deref() == Some(session_id)).collect();
        let child = children.iter().find(|session| session.state(None) == crate::debug::session::State::Stopped).or(children.first());
        child.map_or(session_id.to_owned(), |session| session.id.clone())
    }

    /// repl.ts `clearRepl`: empties the shown console; a cleared inactive session leaves the picker.
    pub(super) fn clear_repl(&mut self) {
        let Some(shown) = self.shown_repl_session() else { return };
        let repl = std::mem::take(&mut self.debug.repl);
        let kept = repl.into_iter().filter(|element| self.repl_owner(repl_element_session(element)) != shown).collect();
        self.debug.repl = kept;
        if self.debug.inactive_sessions.iter().any(|session| session.id == shown) {
            self.debug_console.ignored_sessions.insert(shown);
            self.debug_console.selected_session = None;
        }
    }

    /// replModel.ts `removeReplExpressions`: empties the session's console, the parent's when it merges with it.
    pub(super) fn remove_repl_expressions(&mut self, session_id: &str) {
        let owner = self.repl_owner(session_id);
        let repl = std::mem::take(&mut self.debug.repl);
        self.debug.repl = repl.into_iter().filter(|element| self.repl_owner(repl_element_session(element)) != owner).collect();
    }

    pub(super) fn debug_console_visible(&self) -> bool {
        self.panel_view_visible(DEBUG_PANEL_ID)
    }

    /// `viewsService.openView(REPL_VIEW_ID, focus)`.
    pub(crate) fn open_debug_console(&mut self, focus: bool, window: &mut Window, cx: &mut Context<Self>) {
        self.open_panel_view(DEBUG_PANEL_ID, cx);
        if focus {
            window.focus(&self.debug_console.input_focus, cx);
        }
    }

    pub(crate) fn close_debug_console(&mut self, cx: &mut Context<Self>) {
        self.close_panel_view(DEBUG_PANEL_ID, cx);
    }

    pub(super) fn register_debug_console_commands(&mut self) {
        // debugViewlet.ts, in the Run and Debug container's Views submenu.
        self.commands.register("debug.toggleReplIgnoreFocus", |workbench, _, window, cx| {
            match workbench.panel_view_visible(DEBUG_PANEL_ID) {
                true => workbench.close_panel_view(DEBUG_PANEL_ID, cx),
                false => workbench.open_debug_console(false, window, cx),
            }
            Outcome::done()
        });
        self.commands.register("repl.action.filter", |workbench, _, window, cx| {
            window.focus(&workbench.debug_console.filter_focus, cx);
            Outcome::done()
        });
        self.commands.register("repl.action.find", |workbench, _, window, cx| {
            workbench.open_repl_find(window, cx);
            Outcome::done()
        });
        for id in ["repl.action.copyAll", "workbench.debug.action.copyAll"] {
            self.commands.register(id, |workbench, _, _, cx| {
                cx.write_to_clipboard(gpui::ClipboardItem::new_string(workbench.repl_visible_content()));
                Outcome::done()
            });
        }
        self.commands.register("debug.replCopy", |workbench, args, window, cx| {
            workbench.copy_repl_row(args, window, cx);
            Outcome::done()
        });
        self.commands.register("debug.replPaste", |workbench, _, window, cx| {
            let Some(pasted) = cx.read_from_clipboard().and_then(|item| item.text()).filter(|text| !text.is_empty()) else { return Outcome::done() };
            let value = format!("{}{pasted}", workbench.debug_console.input.value);
            workbench.edit_debug_console_input(|input| input.set_value(value), cx);
            window.focus(&workbench.debug_console.input_focus, cx);
            Outcome::done()
        });
        // repl.ts `debug.collapseRepl`: the port's console rows do not expand, so only `view.focus()` is left.
        self.commands.register("debug.collapseRepl", |workbench, _, window, cx| {
            window.focus(&workbench.debug_console.input_focus, cx);
            Outcome::done()
        });
        self.commands.register("repl.action.acceptInput", |workbench, _, window, cx| {
            let expression = std::mem::take(&mut workbench.debug_console.input).value;
            if expression.trim().is_empty() {
                return Outcome::done();
            }
            workbench.debug_console.history.add(&expression);
            // Upstream stores in `saveState`; the port stores at once, as the app can exit without a shutdown phase.
            let history = json!(workbench.debug_console.history.elements()).to_string();
            workbench.workspace_storage.lock().unwrap().set(HISTORY_STORAGE_KEY, history);
            workbench.evaluate_in_repl(expression, window, cx);
            Outcome::done()
        });
    }

    /// repl.ts `navigateHistory`, through `history.showPrevious` and `history.showNext`.
    pub(super) fn walk_repl_history(&mut self, back: bool, cx: &mut Context<Self>) {
        let console = &mut self.debug_console;
        let value = match back {
            true => console.history.previous().or_else(|| console.history.first()),
            false => console.history.next(),
        };
        let value = value.unwrap_or_default();
        console.input = InputBox::default();
        console.input.set_value(value);
        cx.notify();
    }

    /// `debugService.addReplExpression`: the input as an element, then the `repl` evaluation's result below it.
    pub(crate) fn evaluate_in_repl(&mut self, expression: String, window: &mut Window, cx: &mut Context<Self>) {
        let session_id = self.debug.focus.session.clone().unwrap_or_default();
        let index = self.debug.repl.len();
        self.debug.repl.push(ReplElement::Evaluation { session_id: session_id.clone(), input: expression.clone(), result: None });
        cx.notify();
        if self.debug.session(&session_id).is_none() {
            return;
        }
        let reply = self.dap_request(&session_id, "evaluate", json!({ "expression": expression, "frameId": self.debug.focus.frame, "context": "repl" }));
        cx.spawn_in(window, async move |this, cx| {
            let mut result = match reply.await {
                Ok(Ok(body)) => Variable::from_dap(&body),
                Ok(Err(error)) => Variable { value: error["message"].as_str().unwrap_or_default().to_owned(), error: true, ..Variable::default() },
                Err(_) => return,
            };
            // debugModel.ts `evaluateExpression` without `keepLazyVars`.
            if result.is_lazy() {
                super::debug_service::evaluate_lazy(&this, cx, &session_id, &mut result).await;
            }
            let _ = this.update_in(cx, |workbench, window, cx| {
                if let Some(ReplElement::Evaluation { result: slot, .. }) = workbench.debug.repl.get_mut(index) {
                    *slot = Some(result);
                }
                // repl.ts: evaluating may have side effects, so the variables and watches are fetched again.
                workbench.refresh_focus(window, cx);
            });
        })
        .detach();
    }

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

    /// The console's body under the tab strip: the elements, then the input (repl.css).
    pub(super) fn debug_console_body(&self, window: &Window, cx: &mut Context<Self>) -> Div {
        let font_size = 12.;
        let line_height = (font_size * 1.4_f32).round();
        let padding = if self.debug_console.find.open { FIND_PADDING } else { 0. };
        self.text_selection.begin(REPL_TEXTS);
        let mut rows = div().id("repl-tree").debug_selector(|| "repl-tree".into()).px(px(10.)).pt(px(4. + padding)).pb(px(4.)).flex().flex_col();
        let shown = self.shown_repl_session();
        let mut shown_elements = Vec::new();
        for (index, element) in self.debug.repl.iter().enumerate() {
            if Some(self.repl_owner(repl_element_session(element))) != shown || !self.repl_element_visible(element) {
                continue;
            }
            shown_elements.push(element);
            if self.repl_find_keeps(element) {
                // `flex_none`: once the rows overflow, a shrinking row would stop at its `min_h` and a wrapped output
                // would draw over the row below (issue #82).
                rows = rows.child(self.repl_element(index, element, line_height, cx).flex_none().debug_selector(move || format!("repl-element-{index}")));
            }
        }
        let list = self
            .text_selection_root(REPL_TEXTS, self.scrollable("repl-tree", None, rows, cx).size_full(), cx)
            .on_mouse_down(MouseButton::Left, cx.listener(|workbench, _, window, cx| window.focus(&workbench.debug_console.focus, cx)))
            // repl.ts `tree.onMouseClick`: the input takes the focus unless the click selected text or find is open.
            .on_mouse_up(MouseButton::Left, cx.listener(|workbench, _, window, cx| {
                if workbench.text_selection.is_collapsed() && !workbench.debug_console.find.open {
                    window.focus(&workbench.debug_console.input_focus, cx);
                }
            }));
        let tree = div().relative().flex_1().min_h_0().child(list).children(self.repl_find_widget(&shown_elements, window, cx));
        let focused = self.debug_console.input_focus.is_focused(window);
        let prompt_color = self.color("debugConsoleInputIcon.foreground");
        let input = div()
            .flex_none()
            .h(px(line_height + 8.))
            .flex()
            .items_center()
            .border_t_1()
            .border_color(self.color("panel.border"))
            .on_mouse_down(MouseButton::Left, cx.listener(|workbench, _, window, cx| window.focus(&workbench.debug_console.input_focus, cx)))
            .child(self.icon("chevron-right", 20., 16., prompt_color))
            .child(div().flex_1().h(px(line_height)).flex().child(self.input_text(InputId::DebugConsole, InputLook { password: false, placeholder: None, focused }, cx)));
        let console = div()
            .flex_1()
            .min_h_0()
            .flex()
            .flex_col()
            .track_focus(&self.debug_console.focus)
            .font_family("Menlo")
            .text_size(px(font_size))
            .line_height(px(line_height))
            .child(tree)
            .child(input);
        div()
            .flex_1()
            .min_h_0()
            .flex()
            .flex_col()
            .children((!self.view_filter_in_header(REPL_VIEW_ID)).then(|| self.debug_console_filter_box(window, cx)))
            .child(console)
    }

    /// debugANSIHandling.ts `handleANSIOutput` with repl.css's `code-*` rules; the theme's ANSI colors keep a
    /// contrast ratio of 4 against the panel, as its theming participant does.
    fn ansi_output(&self, value: &str) -> (String, Vec<(std::ops::Range<usize>, gpui::HighlightStyle)>) {
        let palette = crate::terminal::colors::TerminalColors::new(&self.theme).palette;
        let background = self.color("panel.background");
        let resolve = |color: AnsiColor| -> gpui::Hsla {
            match color {
                AnsiColor::Rgb(r, g, b) => gpui::Rgba { r: r as f32 / 255., g: g as f32 / 255., b: b as f32 / 255., a: 1. }.into(),
                AnsiColor::Theme(index) => crate::terminal::colors::ensure_contrast_ratio(background, palette[index], 4.).unwrap_or(palette[index]).into(),
            }
        };
        let mut text = String::new();
        let mut highlights = Vec::new();
        for (run, style) in crate::debug::ansi::parse(value) {
            let start = text.len();
            text.push_str(&run);
            let highlight = gpui::HighlightStyle {
                color: style.foreground.map(resolve),
                background_color: style.background.map(resolve),
                font_weight: style.bold.then_some(gpui::FontWeight::BOLD),
                font_style: style.italic.then_some(gpui::FontStyle::Italic),
                underline: style.underline.then(|| gpui::UnderlineStyle { thickness: px(1.), color: style.underline_color.map(resolve), wavy: false }),
                strikethrough: style.strike_through.then(|| gpui::StrikethroughStyle { thickness: px(1.), color: None }),
                fade_out: if style.hidden { Some(1.) } else { style.dim.then_some(0.6) },
            };
            if highlight != gpui::HighlightStyle::default() {
                highlights.push((start..text.len(), highlight));
            }
        }
        (text, highlights)
    }

    fn repl_element(&self, index: usize, element: &ReplElement, line_height: f32, cx: &mut Context<Self>) -> Div {
        let severity_color = |severity: Severity| match severity {
            Severity::Warning => self.color("debugConsole.warningForeground"),
            Severity::Error => self.color("debugConsole.errorForeground"),
            Severity::Info => self.color("debugConsole.infoForeground"),
            Severity::Ignore => self.foreground_or("foreground"),
        };
        match element {
            ReplElement::Output { value, severity, source, count, .. } => {
                let (text, highlights) = self.ansi_output(value.strip_suffix('\n').unwrap_or(value));
                let mut row = self.repl_menu_row(index, false, cx).flex().items_start().min_h(px(line_height));
                if *count > 1 {
                    row = row.child(div().flex_none().mr(px(6.)).px(px(4.)).rounded(px(8.)).bg(self.color("badge.background")).text_color(self.color("badge.foreground")).child(count.to_string()));
                }
                let text = SharedString::from(text);
                let styled = StyledText::new(text.clone()).with_highlights(highlights);
                let selection = self.selectable_text(REPL_TEXTS, styled.layout(), text, "\n");
                row = row.child(div().relative().flex_1().min_w_0().text_color(severity_color(*severity)).whitespace_normal().child(selection).child(styled));
                if let Some((path, line)) = source {
                    let name = path.rsplit('/').next().unwrap_or_default().to_owned();
                    let (path, line) = (std::path::PathBuf::from(path), *line as usize);
                    row = row.child(
                        div()
                            .id(("repl-source", index))
                            .flex_none()
                            .ml(px(8.))
                            .text_color(self.color("debugConsole.sourceForeground"))
                            .cursor_pointer()
                            .hover(|source| source.underline())
                            .child(format!("{name}:{line}"))
                            .on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
                                // replOutputElementRenderer's `e.stopPropagation()`: the input does not take the focus back.
                                cx.stop_propagation();
                                workbench.open_file(path.clone(), true, window, cx);
                                workbench.select_range(&path, crate::anything_quick_access::TextRange { start_line_number: line, start_column: 1, end_line_number: line, end_column: 1 }, cx);
                            })),
                    );
                }
                row
            }
            ReplElement::Variable { variable, severity, .. } => {
                let mut label = self.expression_label_in(variable, &self.repl_find_name_highlights(variable), None, Some(REPL_TEXTS));
                if variable.name.is_empty() {
                    label = label.text_color(severity_color(*severity));
                }
                self.repl_menu_row(index, false, cx).flex().min_h(px(line_height)).child(self.icon(if variable.has_children() { "chevron-right" } else { "blank" }, 16., 16., self.foreground_or("icon.foreground"))).child(label)
            }
            ReplElement::Evaluation { input, result, .. } => {
                let icon = self.foreground_or("icon.foreground");
                let styled = self.repl_input_label(input);
                let selection = self.selectable_text(REPL_TEXTS, styled.layout(), input.clone().into(), "\n");
                let input_row = self.repl_menu_row(index, false, cx).flex().items_center().min_h(px(line_height)).child(self.icon("arrow-small-right", 16., 16., icon)).child(div().relative().child(selection).child(styled));
                let mut rows = div().flex().flex_col().child(input_row);
                if let Some(result) = result {
                    let shown = Variable { name: String::new(), ..result.clone() };
                    rows = rows.child(self.repl_menu_row(index, true, cx).flex().items_center().min_h(px(line_height)).child(self.icon("chevron-left", 16., 16., icon)).child(self.expression_label_in(&shown, &[], None, Some(REPL_TEXTS))));
                }
                rows
            }
        }
    }

    /// A tree row whose context menu is `MenuId.DebugConsoleContext`, its commands given the element's index and whether
    /// the row is an evaluation's result, as `getActionsContext` gives them the element.
    fn repl_menu_row(&self, index: usize, result: bool, cx: &mut Context<Self>) -> Div {
        div().on_mouse_down(MouseButton::Right, cx.listener(move |workbench, event: &MouseDownEvent, window, cx| {
            let context = workbench.key_context(window);
            workbench.show_context_menu(crate::menus::MenuId::DebugConsoleContext, &context, Bounds::new(event.position, Default::default()), vec![json!(index), json!(result)], window, cx);
        }))
    }

    /// The row's `IReplElement.toString()`, and for an evaluation's result the expression it evaluated.
    fn repl_row_text(&self, index: usize, result: bool) -> Option<(String, Option<&str>)> {
        match self.debug.repl.get(index)? {
            ReplElement::Output { value, count, .. } => Some((repl_output_text(value, *count), None)),
            ReplElement::Variable { variable, .. } => Some((variable_text(variable), None)),
            ReplElement::Evaluation { input, result: Some(evaluated), .. } if result => Some((evaluated.value.clone(), Some(input))),
            ReplElement::Evaluation { input, .. } => Some((input.clone(), None)),
        }
    }

    /// repl.ts `getVisibleContent`: the shown elements' text, each trimmed at its end, one per line.
    fn repl_visible_content(&self) -> String {
        let mut content = String::new();
        let mut push = |text: &str| {
            content.push_str(text.trim_end());
            content.push('\n');
        };
        for element in self.shown_repl_elements() {
            if !self.repl_element_visible(element) || !self.repl_find_keeps(element) {
                continue;
            }
            match element {
                ReplElement::Output { value, count, .. } => push(&repl_output_text(value, *count)),
                ReplElement::Variable { variable, .. } => push(&variable_text(variable)),
                ReplElement::Evaluation { input, result, .. } => {
                    push(input);
                    if let Some(result) = result {
                        push(&result.value);
                    }
                }
            }
        }
        content
    }

    /// repl.ts `debug.replCopy`: the selected text, else the row's; an evaluation's result is evaluated again with
    /// the `clipboard` context when the adapter `supportsClipboardContext` (`tryEvaluateAndCopy`).
    fn copy_repl_row(&mut self, args: Vec<Value>, window: &mut Window, cx: &mut Context<Self>) {
        let selected = self.text_selection.to_text();
        if !selected.is_empty() {
            cx.write_to_clipboard(gpui::ClipboardItem::new_string(selected));
            return;
        }
        let (Some(index), result) = (args.first().and_then(Value::as_u64), args.get(1) == Some(&json!(true))) else { return };
        let Some((text, expression)) = self.repl_row_text(index as usize, result) else { return };
        let text = strip_ansi(&text);
        let expression = expression.map(str::to_owned);
        let session_id = self.debug.focus.session.clone();
        let supported = session_id.as_deref().and_then(|id| self.debug.session(id)).is_some_and(|session| session.capabilities["supportsClipboardContext"] == true);
        let (Some(expression), Some(session_id), Some(frame), true) = (expression, session_id, self.debug.focus.frame, supported) else {
            cx.write_to_clipboard(gpui::ClipboardItem::new_string(text));
            return;
        };
        let reply = self.dap_request(&session_id, "evaluate", json!({ "expression": expression, "frameId": frame, "context": "clipboard" }));
        cx.spawn_in(window, async move |_, cx| {
            let copied = match reply.await {
                Ok(Ok(body)) => body["result"].as_str().map_or(text, str::to_owned),
                _ => text,
            };
            cx.update(|_, cx| cx.write_to_clipboard(gpui::ClipboardItem::new_string(copied))).ok();
        })
        .detach();
    }
}

/// debugModel.ts `Variable.toString`: `name: value`, the value alone without a name.
fn variable_text(variable: &Variable) -> String {
    match variable.name.is_empty() {
        true => variable.value.clone(),
        false => format!("{}: {}", variable.name, variable.value),
    }
}

/// replModel.ts `SimpleReplElement.toString`: the value once per time it was output in a row.
fn repl_output_text(value: &str, count: u32) -> String {
    let mut text = value.to_owned();
    for _ in 1..count {
        if !text.ends_with('\n') {
            text.push('\n');
        }
        text.push_str(value);
    }
    text
}

pub(super) fn repl_element_session(element: &ReplElement) -> &str {
    match element {
        ReplElement::Output { session_id, .. } | ReplElement::Variable { session_id, .. } | ReplElement::Evaluation { session_id, .. } => session_id,
    }
}

/// `ReplFilter.filterQuery`: comma separated terms outside globs, `!` excludes, a leading `\\` escapes either.
fn parse_repl_filter(query: &str) -> Vec<(bool, String)> {
    let mut terms = Vec::new();
    for term in files::glob::split_glob_aware(query.trim(), ',') {
        let term = term.trim();
        if let Some(escaped) = term.strip_prefix('\\') {
            terms.push((false, escaped.to_owned()));
        } else if let Some(excluded) = term.strip_prefix('!') {
            terms.push((true, excluded.to_owned()));
        } else if !term.is_empty() {
            terms.push((false, term.to_owned()));
        }
    }
    terms
}

/// The text without its escape sequences, for views that draw no ANSI styles.
pub(super) fn strip_ansi(text: &str) -> String {
    let mut result = String::with_capacity(text.len());
    let mut chars = text.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\u{1b}' && chars.peek() == Some(&'[') {
            chars.next();
            for next in chars.by_ref() {
                if next.is_ascii_alphabetic() {
                    break;
                }
            }
            continue;
        }
        result.push(c);
    }
    result
}

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

    use gpui::TestAppContext;
    use serde_json::Value;

    use super::*;

    #[gpui::test]
    fn output_draws_its_sgr_styles_with_the_themes_ansi_colors(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 = crate::theme::load_theme(&[themes], "Dark Modern").unwrap();
        let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), crate::default_settings(), crate::host_sync::HostSync::new(std::sync::mpsc::channel().0), cx));
        let (text, highlights) = workbench.read_with(cx, |workbench, _| workbench.ansi_output("ok \u{1b}[1;31mfailed\u{1b}[0m done"));
        assert_eq!(text, "ok failed done");
        assert_eq!(highlights.len(), 1);
        let (range, style) = &highlights[0];
        assert_eq!(&text[range.clone()], "failed");
        assert_eq!(style.font_weight, Some(gpui::FontWeight::BOLD));
        let red = workbench.read_with(cx, |workbench, _| crate::terminal::colors::TerminalColors::new(&workbench.theme).palette[1]);
        let red = workbench.read_with(cx, |workbench, _| crate::terminal::colors::ensure_contrast_ratio(workbench.color("panel.background"), red, 4.).unwrap_or(red));
        assert_eq!(style.color, Some(red.into()));
    }

    fn workbench(cx: &mut TestAppContext) -> (gpui::Entity<Workbench>, &mut gpui::VisualTestContext) {
        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 = crate::theme::load_theme(&[themes], "Dark Modern").unwrap();
        cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), crate::default_settings(), crate::host_sync::HostSync::new(std::sync::mpsc::channel().0), cx))
    }

    fn output(session_id: &str, value: &str) -> ReplElement {
        ReplElement::Output { session_id: session_id.into(), value: value.into(), severity: Severity::Info, source: None, count: 1 }
    }

    fn session(id: &str, parent: Option<&str>, repl: &str) -> crate::debug::session::Session {
        let mut session = crate::debug::session::Session::new(id.into(), 1, json!({ "type": "node", "name": id }), json!({}), None, json!({ "repl": repl }));
        session.parent = parent.map(str::to_owned);
        session
    }

    #[gpui::test]
    fn the_filter_keeps_include_matches_drops_exclude_matches_and_always_shows_evaluations(cx: &mut TestAppContext) {
        let (workbench, cx) = workbench(cx);
        workbench.update(cx, |workbench, _| {
            let elements = [output("s", "server started"), output("s", "request failed"), output("s", "!literal bang"), ReplElement::Evaluation { session_id: "s".into(), input: "1+1".into(), result: None }];
            let shown = |workbench: &mut Workbench, query: &str| {
                workbench.debug_console.filter_query = query.into();
                elements.iter().map(|element| workbench.repl_element_visible(element)).collect::<Vec<_>>()
            };
            assert_eq!(shown(workbench, ""), [true, true, true, true]);
            assert_eq!(shown(workbench, "server"), [true, false, false, true]);
            assert_eq!(shown(workbench, "STARTED, failed"), [true, true, false, true]);
            assert_eq!(shown(workbench, "!failed"), [true, false, true, true]);
            assert_eq!(shown(workbench, "\\!literal"), [false, false, true, true]);
        });
    }

    /// repl.ts `FindReplAction`: `search` in the view title's navigation group (order 15), before Clear Console.
    #[gpui::test]
    fn the_title_shows_find_before_clear_console(cx: &mut TestAppContext) {
        let (workbench, cx) = workbench(cx);
        workbench.update_in(cx, |workbench, window, cx| workbench.open_debug_console(true, window, cx));
        cx.run_until_parked();
        let find = cx.debug_bounds("repl-title-find").expect("the title draws Find");
        let clear = cx.debug_bounds("repl-title-clear").expect("the title draws Clear Console");
        assert!(find.right() <= clear.left() && find.top() == clear.top(), "{find:?} before {clear:?}");
    }

    #[gpui::test]
    fn the_find_widget_filters_the_console_and_says_when_nothing_matches(cx: &mut TestAppContext) {
        let (workbench, cx) = workbench(cx);
        workbench.update_in(cx, |workbench, window, cx| {
            workbench.debug.repl = vec![output("s", "server started"), output("s", "request failed"), ReplElement::Evaluation { session_id: "s".into(), input: "failures".into(), result: None }];
            workbench.debug_console.selected_session = Some("s".into());
            workbench.open_debug_console(true, window, cx);
            drop(workbench.execute_command("repl.action.find", Vec::new(), window, cx));
            assert!(workbench.debug_console.find.focus.is_focused(window));
            workbench.edit_repl_find_input(|input| input.set_value("fail".into()), cx);
            let keeps = |workbench: &Workbench| workbench.debug.repl.iter().map(|element| workbench.repl_find_keeps(element)).collect::<Vec<_>>();
            assert_eq!(keeps(workbench), [true, true, true], "highlight mode keeps every element");
            workbench.toggle_repl_find(true, cx);
            assert_eq!(keeps(workbench), [false, true, true]);
            let variable = Variable { name: "failed".into(), value: "fail".into(), ..Default::default() };
            assert_eq!(workbench.repl_find_name_highlights(&variable), [0..4], "only the name's match, not the value's");
            let message = |workbench: &Workbench| workbench.repl_find_message(&workbench.debug.repl.iter().collect::<Vec<_>>());
            assert_eq!(message(workbench), None);
            workbench.edit_repl_find_input(|input| input.set_value("zzz".into()), cx);
            assert_eq!(message(workbench).as_deref(), Some("No results found."));
        });
        cx.run_until_parked();
        assert!(cx.debug_bounds("tree-find-input").is_some());
        workbench.update_in(cx, |workbench, window, cx| {
            workbench.close_repl_find(window, cx);
            assert_eq!(workbench.debug.repl.iter().filter(|element| workbench.repl_find_keeps(element)).count(), 3);
            assert!(workbench.debug_console.focus.is_focused(window));
            drop(workbench.execute_command("repl.action.find", Vec::new(), window, cx));
            assert_eq!(workbench.debug_console.find.input.value, "zzz", "a reopened widget starts with the last pattern");
        });
    }

    #[gpui::test]
    fn the_filter_text_and_history_persist_in_workspace_storage(cx: &mut TestAppContext) {
        let (workbench, cx) = workbench(cx);
        workbench.update_in(cx, |workbench, window, cx| workbench.edit_debug_console_filter(|input| input.set_value("server".into()), window, cx));
        cx.executor().advance_clock(std::time::Duration::from_millis(300));
        cx.run_until_parked();
        workbench.update(cx, |workbench, _| {
            assert_eq!(workbench.debug_console.filter_query, "server");
            let storage = workbench.workspace_storage.lock().unwrap();
            assert_eq!(storage.get(FILTER_VALUE_STORAGE_KEY), Some("server"));
            assert_eq!(storage.get(FILTER_HISTORY_STORAGE_KEY), Some(r#"["server"]"#));
        });
        workbench.update(cx, |workbench, _| {
            workbench.debug_console.filter_query.clear();
            workbench.restore_debug_console_state();
            assert_eq!(workbench.debug_console.filter.value, "server");
            assert_eq!(workbench.debug_console.filter_query, "server");
        });
    }

    #[gpui::test]
    fn the_input_history_is_stored_in_the_workspace_and_walked_after_a_restore(cx: &mut TestAppContext) {
        let (workbench, cx) = workbench(cx);
        workbench.update_in(cx, |workbench, window, cx| {
            for expression in ["a", "b", "a"] {
                workbench.debug_console.input.set_value(expression.into());
                drop(workbench.execute_command("repl.action.acceptInput", Vec::new(), window, cx));
            }
            assert_eq!(workbench.workspace_storage.lock().unwrap().get(HISTORY_STORAGE_KEY), Some(r#"["b","a"]"#));
            workbench.debug_console.history = HistoryNavigator::new(Vec::new(), 100);
            workbench.restore_debug_console_state();
            let mut walked = Vec::new();
            for back in [true, true, true, false, false] {
                workbench.walk_repl_history(back, cx);
                walked.push(workbench.debug_console.input.value.clone());
            }
            assert_eq!(walked, ["a", "b", "b", "a", ""]);
        });
    }

    #[gpui::test]
    fn the_console_shows_the_focused_sessions_elements_with_merged_children_and_the_picker_focuses_another(cx: &mut TestAppContext) {
        let (workbench, cx) = workbench(cx);
        workbench.update(cx, |workbench, _| {
            workbench.debug.sessions = vec![session("a", None, "separate"), session("a-child", Some("a"), "mergeWithParent"), session("b", None, "separate")];
            workbench.debug.repl = vec![output("a", "from a"), output("a-child", "from a's child"), output("b", "from b")];
            workbench.debug.focus.session = Some("a-child".into());
            let shown: Vec<_> = workbench.shown_repl_elements().into_iter().cloned().collect();
            assert_eq!(shown.len(), 2);
            assert!(matches!(&shown[1], ReplElement::Output { value, .. } if value == "from a's child"));
            let names: Vec<_> = workbench.repl_sessions().iter().map(|session| session.id.clone()).collect();
            assert_eq!(names, ["a", "b"]);
        });
        workbench.update_in(cx, |workbench, window, cx| workbench.select_repl("b", window, cx));
        workbench.update(cx, |workbench, _| {
            assert_eq!(workbench.debug.focus.session.as_deref(), Some("b"));
            assert!(matches!(workbench.shown_repl_elements()[..], [ReplElement::Output { value, .. }] if value == "from b"));
        });
    }

    #[gpui::test]
    fn an_ended_session_stays_in_the_picker_until_cleared_or_started_again(cx: &mut TestAppContext) {
        let (workbench, cx) = workbench(cx);
        let started = |id: &str, handle: u32| crate::debug::session::Session::new(id.into(), handle, json!({ "type": "node", "name": id.to_uppercase() }), json!({}), None, json!({}));
        let ids = |sessions: Vec<&crate::debug::session::Session>| sessions.iter().map(|session| session.id.clone()).collect::<Vec<_>>();
        workbench.update_in(cx, |workbench, window, cx| {
            workbench.debug.sessions = vec![started("a", 1), started("b", 2), started("c", 3)];
            workbench.debug.repl = vec![output("a", "from a"), output("b", "from b"), output("c", "from c")];
            workbench.debug.focus.session = Some("a".into());
            workbench.session_ended("a", window, cx);
            assert_eq!(ids(workbench.repl_sessions()), ["a", "b", "c"]);
            workbench.select_repl("a", window, cx);
            assert!(matches!(workbench.shown_repl_elements()[..], [ReplElement::Output { value, .. }] if value == "from a"));
            drop(workbench.execute_command("workbench.debug.panel.action.clearReplAction", Vec::new(), window, cx));
            assert_eq!(ids(workbench.repl_sessions()), ["b", "c"]);
            assert_eq!(workbench.debug.repl.len(), 2);
            workbench.session_ended("b", window, cx);
            workbench.debug.add_session(started("b", 4));
            assert_eq!(ids(workbench.repl_sessions()), ["c", "b"]);
            assert!(matches!(workbench.debug.repl[..], [ReplElement::Output { ref value, .. }] if value == "from c"));
        });
    }

    fn workbench_with_host(cx: &mut TestAppContext) -> (gpui::Entity<Workbench>, std::sync::mpsc::Receiver<crate::host_sync::HostMessage>, &mut gpui::VisualTestContext) {
        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 = crate::theme::load_theme(&[themes], "Dark Modern").unwrap();
        let (sender, receiver) = std::sync::mpsc::channel();
        let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), crate::default_settings(), crate::host_sync::HostSync::new(sender), cx));
        (workbench, receiver, cx)
    }

    fn running(capabilities: Value) -> crate::debug::session::Session {
        let mut session = crate::debug::session::Session::new("a".into(), 7, json!({ "type": "node", "name": "A", "request": "launch" }), json!({}), None, json!({}));
        session.capabilities = capabilities;
        session.initialized = true;
        session
    }

    /// The `$sendDAMessage` requests and `$startDASession` session DTOs sent so far.
    fn adapter_traffic(receiver: &std::sync::mpsc::Receiver<crate::host_sync::HostMessage>) -> (Vec<Value>, Vec<(Value, Value)>) {
        let (mut requests, mut starts) = (Vec::new(), Vec::new());
        for message in receiver.try_iter() {
            match message.method {
                "$sendDAMessage" => requests.push(message.args[1].clone()),
                "$startDASession" => starts.push((message.args[0].clone(), message.args[1].clone())),
                _ => {}
            }
        }
        (requests, starts)
    }

    #[gpui::test]
    fn an_adapter_restart_relaunches_the_same_session_and_keeps_its_console(cx: &mut TestAppContext) {
        let (workbench, receiver, cx) = workbench_with_host(cx);
        workbench.update_in(cx, |workbench, window, cx| {
            workbench.debug.sessions = vec![running(json!({}))];
            workbench.debug.repl = vec![output("a", "before the restart")];
            workbench.debug.focus.session = Some("a".into());
            drop(workbench.restart_session("a".into(), Some(json!({ "port": 9229 })), window, cx));
        });
        cx.run_until_parked();
        cx.executor().advance_clock(std::time::Duration::from_secs(2));
        cx.run_until_parked();
        cx.executor().advance_clock(std::time::Duration::from_millis(300));
        cx.run_until_parked();
        let (requests, starts) = adapter_traffic(&receiver);
        assert_eq!(requests[0]["command"], "disconnect");
        assert_eq!(requests[0]["arguments"], json!({ "restart": true, "terminateDebuggee": false }));
        let [(handle, dto)] = &starts[..] else { panic!("one relaunch, got {starts:?}") };
        assert_ne!(handle, &json!(7));
        assert_eq!(dto["id"], "a");
        assert_eq!(dto["configuration"]["__restart"], json!({ "port": 9229 }));
        workbench.update(cx, |workbench, _| {
            assert_eq!(workbench.debug.sessions.iter().map(|session| session.id.as_str()).collect::<Vec<_>>(), ["a"]);
            assert!(matches!(workbench.debug.repl[..], [ReplElement::Output { ref value, .. }] if value == "before the restart"));
        });
    }

    #[gpui::test]
    fn the_restart_command_clears_the_console_and_sends_restart_when_the_adapter_supports_it(cx: &mut TestAppContext) {
        let (workbench, receiver, cx) = workbench_with_host(cx);
        workbench.update_in(cx, |workbench, window, cx| {
            workbench.debug.sessions = vec![running(json!({ "supportsRestartRequest": true }))];
            workbench.debug.repl = vec![output("a", "before the restart")];
            workbench.debug.focus.session = Some("a".into());
            drop(workbench.execute_command("workbench.action.debug.restart", Vec::new(), window, cx));
        });
        cx.run_until_parked();
        let (requests, starts) = adapter_traffic(&receiver);
        assert_eq!(requests.iter().map(|request| request["command"].clone()).collect::<Vec<_>>(), [json!("restart")]);
        assert_eq!(requests[0]["arguments"]["arguments"]["name"], "A");
        assert!(starts.is_empty());
        workbench.update(cx, |workbench, _| assert!(workbench.debug.repl.is_empty()));
    }

    /// repl.css `user-select: text`: a drag across the rows selects their text and Copy copies it; a click without a
    /// drag gives the input the focus (repl.ts `tree.onMouseClick`).
    #[gpui::test]
    fn a_drag_selects_the_consoles_text_and_copy_copies_it(cx: &mut TestAppContext) {
        let (workbench, cx) = workbench(cx);
        workbench.update_in(cx, |workbench, window, cx| {
            workbench.debug.repl = vec![output("s", "first line\n"), ReplElement::Evaluation { session_id: "s".into(), input: "1 + 1".into(), result: Some(Variable { value: "2".into(), ..Default::default() }) }];
            workbench.debug_console.selected_session = Some("s".into());
            workbench.open_debug_console(true, window, cx);
        });
        cx.run_until_parked();
        let first = cx.debug_bounds("repl-element-0").expect("drawn");
        let evaluation = cx.debug_bounds("repl-element-1").expect("drawn");
        let none = gpui::Modifiers::none();
        cx.simulate_mouse_down(first.origin + gpui::point(px(1.), px(8.)), gpui::MouseButton::Left, none);
        cx.simulate_mouse_move(evaluation.bottom_right() - gpui::point(px(1.), px(4.)), gpui::MouseButton::Left, none);
        cx.simulate_mouse_up(evaluation.bottom_right() - gpui::point(px(1.), px(4.)), gpui::MouseButton::Left, none);
        workbench.update_in(cx, |workbench, window, _| {
            assert_eq!(workbench.text_selection.to_text(), "first line\n1 + 1\n2");
            assert!(workbench.debug_console.focus.is_focused(window), "a selection keeps the focus off the input");
        });
        // The test workbench loads no keybindings: Cmd+C runs this command.
        workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("editor.action.clipboardCopyAction", Vec::new(), window, cx)));
        assert_eq!(cx.read_from_clipboard().and_then(|item| item.text()).as_deref(), Some("first line\n1 + 1\n2"));
        cx.simulate_click(first.origin + gpui::point(px(30.), px(8.)), none);
        workbench.update_in(cx, |workbench, window, _| {
            assert_eq!(workbench.text_selection.to_text(), "");
            assert!(workbench.debug_console.input_focus.is_focused(window));
        });
    }

    /// repl.ts's `MenuId.DebugConsoleContext` actions: Copy copies the row without its escape sequences when nothing
    /// is selected, Copy All the shown rows (`getVisibleContent`).
    #[gpui::test]
    fn the_context_menu_copies_the_row_or_every_shown_row(cx: &mut TestAppContext) {
        let (workbench, cx) = workbench(cx);
        workbench.update_in(cx, |workbench, window, cx| {
            let repeated = ReplElement::Output { session_id: "s".into(), value: "again".into(), severity: Severity::Info, source: None, count: 2 };
            workbench.debug.repl = vec![output("s", "\u{1b}[31mred\u{1b}[0m  \n"), output("other", "hidden"), repeated];
            workbench.debug_console.selected_session = Some("s".into());
            workbench.open_debug_console(true, window, cx);
        });
        cx.run_until_parked();
        let first = cx.debug_bounds("repl-element-0").expect("drawn");
        cx.simulate_mouse_down(first.center(), gpui::MouseButton::Right, gpui::Modifiers::none());
        let (titles, args) = workbench.read_with(cx, |workbench, _| {
            let menu = workbench.context_menu.as_ref().expect("a context menu shows");
            let title = |action: &crate::menus::MenuAction| match action {
                crate::menus::MenuAction::Command { title, enabled: true, .. } => title.clone(),
                crate::menus::MenuAction::Command { title, .. } => format!("({title})"),
                _ => "---".into(),
            };
            (menu.levels[0].actions.iter().map(title).collect::<Vec<_>>(), menu.args.clone())
        });
        assert_eq!(titles, ["Copy", "Copy All", "(Paste)", "---", "Collapse All", "Clear Console", "Debug Console: Focus Find"]);
        workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("debug.replCopy", args, window, cx)));
        assert_eq!(cx.read_from_clipboard().and_then(|item| item.text()).as_deref(), Some("red  \n"));
        workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.debug.action.copyAll", Vec::new(), window, cx)));
        assert_eq!(cx.read_from_clipboard().and_then(|item| item.text()).as_deref(), Some("\u{1b}[31mred\u{1b}[0m\nagain\nagain\n"));
    }

    /// repl.ts `tryEvaluateAndCopy`: Copy on an evaluation's result evaluates its expression again with the
    /// `clipboard` context when the adapter supports it.
    #[gpui::test]
    fn copy_on_a_result_evaluates_it_for_the_clipboard(cx: &mut TestAppContext) {
        let (workbench, receiver, cx) = workbench_with_host(cx);
        workbench.update_in(cx, |workbench, window, cx| {
            workbench.debug.sessions = vec![running(json!({ "supportsClipboardContext": true }))];
            workbench.debug.focus = super::super::debug_service::DebugFocus { session: Some("a".into()), thread: Some(1), frame: Some(3) };
            workbench.debug.repl = vec![ReplElement::Evaluation { session_id: "a".into(), input: "user".into(), result: Some(Variable { value: "{…}".into(), ..Default::default() }) }];
            drop(workbench.execute_command("debug.replCopy", vec![json!(0), json!(true)], window, cx));
        });
        cx.run_until_parked();
        let (requests, _) = adapter_traffic(&receiver);
        let evaluate = requests.iter().find(|request| request["command"] == "evaluate").expect("an evaluate request");
        assert_eq!(evaluate["arguments"], json!({ "expression": "user", "frameId": 3, "context": "clipboard" }));
    }

    /// repl.css `.word-wrap .monaco-tl-contents`: a long output wraps, and the row below starts under its last line,
    /// also once the rows overflow the panel (a flex item shrinks to its `min-height` there).
    #[gpui::test]
    fn a_wrapped_output_pushes_the_next_row_down(cx: &mut TestAppContext) {
        let (workbench, cx) = workbench(cx);
        cx.simulate_resize(gpui::size(px(1024.), px(768.)));
        let long = "Another exception was thrown: Assertion failed: file:///Volumes/Dados/Dev/flutter_bin/flutter/packages/flutter/lib/src/widgets/framework.dart:5940:12\n";
        workbench.update_in(cx, |workbench, window, cx| {
            workbench.debug.repl = [long, "next\n"].repeat(20).into_iter().map(|value| output("s", value)).collect();
            workbench.debug_console.selected_session = Some("s".into());
            workbench.open_debug_console(true, window, cx);
        });
        cx.run_until_parked();
        let long = cx.debug_bounds("repl-element-0").expect("drawn");
        let next = cx.debug_bounds("repl-element-1").expect("drawn");
        assert!(long.size.height >= px(17.) * 2., "the long output wraps: {long:?}");
        assert!(next.top() >= long.bottom(), "{next:?} under {long:?}");
    }
}