Skip to content

Visual Studio Code, rebuilt in Rust

Rust
73.1 KB
Raw Blame
//! testResultsTree.ts `OutputPeekTree` and testResultsViewContent.ts: the Test Results view's tree of runs, tasks,
//! tests and their error messages, beside the opened row's message or output.

use std::cmp::Reverse;
use std::collections::HashMap;
use std::path::PathBuf;

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

use super::Workbench;
use super::hover::{HoverContent, HoverOptions};
use super::markdown_view::MarkdownStyle;
use super::testing_item_menu::result_state_context;
use super::testing_message_colorizer;
use super::testing_view::state_icon;
use crate::commands::Outcome;
use crate::diff_editor::{DIFF_EDITOR_SCHEME, DiffInput, Side};
use crate::editor::{OpenEditor, PeekOwner, TEST_RESULTS_GROUP, TextDocument};
use crate::markdown::MarkdownString;
use crate::menus::{MenuAction, MenuId, menu_actions, menu_group_actions};
use crate::testing::{GROUP_DEBUG, GROUP_RUN, ResultState, TEST_DATA_SCHEME, TestResult, parent_id};

/// marshallingIds.ts `MarshalledId.TestItemContext` and `TestMessageMenuArgs`.
const TEST_ITEM_CONTEXT_MID: u64 = 16;
const TEST_MESSAGE_MENU_ARGS_MID: u64 = 18;
const ROW_HEIGHT: f32 = 22.;

/// A tree element: `TestResultElement`, `OlderResultsElement`, `TaskElement`, `TestCaseElement` or
/// `TestMessageElement`, by result id, task index, test id and message index.
#[derive(Clone, Debug, PartialEq)]
pub enum ResultsElement {
    Result { result: String },
    Older { count: usize },
    Task { result: String, task: usize },
    Coverage { result: String, task: usize },
    Test { result: String, task: usize, test: String },
    Message { result: String, task: usize, test: String, message: usize },
}

impl ResultsElement {
    fn id(&self) -> String {
        match self {
            ResultsElement::Result { result } => result.clone(),
            ResultsElement::Older { count } => format!("older-{count}"),
            ResultsElement::Task { result, task } => format!("{result}/{task}"),
            ResultsElement::Coverage { result, task } => format!("coverage-{result}/{task}"),
            ResultsElement::Test { result, test, .. } => format!("{result}/{test}"),
            ResultsElement::Message { result, task, test, message } => format!("{result}/{task}/{test}/message/{message}"),
        }
    }

    /// `ITreeElement.type`, the `peekItemType` context key.
    fn kind(&self) -> &'static str {
        match self {
            ResultsElement::Result { .. } => "result",
            ResultsElement::Older { .. } => "older",
            ResultsElement::Task { .. } => "task",
            ResultsElement::Coverage { .. } => "coverage",
            ResultsElement::Test { .. } => "test",
            ResultsElement::Message { .. } => "message",
        }
    }
}

/// testResultsSubject.ts `InspectSubject`: what the content beside the tree shows.
#[derive(Clone, Debug, PartialEq)]
pub enum InspectSubject {
    Task { result: String, task: usize },
    Message { result: String, task: usize, test: String, message: usize },
    Output { result: String, task: usize, test: String },
}

/// A drawn row. A compressed row draws `element` with its only child `subject`, a task or an error message, as
/// `TestRunElementRenderer.renderCompressedElements` does; the tree's events see the child.
#[derive(Clone, Debug, PartialEq)]
pub struct ResultsRow {
    pub element: ResultsElement,
    pub subject: Option<ResultsElement>,
    pub depth: usize,
    pub collapsible: bool,
    pub collapsed: bool,
}

impl ResultsRow {
    /// The element the tree selects and opens.
    fn target(&self) -> &ResultsElement {
        self.subject.as_ref().unwrap_or(&self.element)
    }
}

/// An `ICompressedTreeElement` of `getRootChildren`.
struct Node {
    element: ResultsElement,
    incompressible: bool,
    collapsed: bool,
    children: Vec<Node>,
}

/// A built-in action of `TreeActionsProvider.provideActionBar`, or a menu item when `icon` is None.
pub struct ResultsAction {
    icon: Option<&'static str>,
    title: String,
    command: String,
    args: Vec<Value>,
}

impl ResultsAction {
    fn new(icon: &'static str, title: &str, command: &str, args: Vec<Value>) -> Self {
        ResultsAction { icon: Some(icon), title: title.to_owned(), command: command.to_owned(), args }
    }
}

/// The tests of a result in the order they were added: each chain's parents before its children.
fn tests_in_order(result: &TestResult) -> Vec<&String> {
    let mut ordered = Vec::new();
    let mut stack: Vec<&String> = result.roots.iter().rev().collect();
    while let Some(id) = stack.pop() {
        ordered.push(id);
        stack.extend(result.items[id].children.iter().rev());
    }
    ordered
}

/// `renderTestMessageAsText` of an `ITestMessage.Serialized`: its string, or its markdown's source.
pub(super) fn message_text(message: &Value) -> &str {
    message["message"].as_str().or(message["message"]["value"].as_str()).unwrap_or_default()
}

fn is_error_message(message: &Value) -> bool {
    message["type"] == 0
}

/// testTypes.ts `ITestMessage.isDiffable`: an error message with both an expected and an actual value.
fn is_diffable(message: &Value) -> bool {
    is_error_message(message) && message["expected"].is_string() && message["actual"].is_string()
}

/// PlainTextMessagePeek `update`: a string message that is no `TestMessageType.Output` and not `ITestMessage.isDiffable`.
fn is_plain_text_message(message: &Value) -> bool {
    message["message"].is_string() && message["type"] != 1 && !is_diffable(message)
}

/// callStackWidget.ts `CallStackFrame` of a message's `ITestMessageStackFrame`: its source by scheme and path,
/// its 1-based line and column, each 1 when the frame has no position.
#[derive(Clone, Debug, PartialEq)]
pub struct CallStackFrame {
    pub label: String,
    pub source: Option<(String, PathBuf)>,
    pub line: usize,
    pub column: usize,
}

/// A header of the call stack widget: the message's frame (`CustomRenderer`), a frame with a source and its code
/// editor (`FrameCodeRenderer`) or one without (`MissingCodeRenderer`), `icon` None for a file's icon.
#[derive(Debug)]
pub(super) struct CallStackRow {
    pub icon: Option<&'static str>,
    pub label: String,
    pub suffix: Option<String>,
    pub description: Option<String>,
    pub editor: Option<u32>,
}

/// callStackWidget.ts `CONTEXT_LINES` around a frame's line, and `CALL_STACK_WIDGET_HEADER_HEIGHT`.
const CONTEXT_LINES: usize = 2;
const CALL_STACK_HEADER_HEIGHT: f32 = 24.;

/// testingUri.ts `TestUriParts` of a message's models.
const MESSAGE_PART: &str = "TestFailureMessage";
const EXPECTED_PART: &str = "ExpectedOutput";
const ACTUAL_PART: &str = "ActualOutput";

const DIFF_LENS_ZONE_HEIGHT: f32 = 20.;

/// testingUri.ts `buildTestUri` of a result message's `part`, with its authority and query in the path as models keep them.
fn message_path(result: &str, task: usize, test: &str, message: usize, part: &str) -> PathBuf {
    PathBuf::from(format!("//results/{result}/message/{task}/{message}/{part}?{test}"))
}

/// `getResultChildren`: a node per task with its tests that ran or have messages, worst state first, each with
/// its error messages.
fn result_children(result: &TestResult) -> Vec<Node> {
    let order = tests_in_order(result);
    let mut tasks = Vec::new();
    for task in 0..result.tasks.len() {
        let mut tests: Vec<&String> = order.iter().copied().filter(|id| {
            let state = &result.items[*id].tasks[task];
            state.state.to_value() >= ResultState::Running.to_value() || !state.messages.is_empty()
        }).collect();
        tests.sort_by_key(|id| Reverse(result.items[*id].tasks[task].state.priority()));
        let mut children = Vec::new();
        if result.tasks[task].coverage.is_some() {
            let element = ResultsElement::Coverage { result: result.id.clone(), task };
            children.push(Node { element, incompressible: true, collapsed: false, children: Vec::new() });
        }
        for test in tests {
            let messages = &result.items[test].tasks[task].messages;
            let mut message_nodes = Vec::new();
            for (message, value) in messages.iter().enumerate() {
                if is_error_message(value) {
                    let element = ResultsElement::Message { result: result.id.clone(), task, test: test.clone(), message };
                    message_nodes.push(Node { element, incompressible: false, collapsed: false, children: Vec::new() });
                }
            }
            let element = ResultsElement::Test { result: result.id.clone(), task, test: test.clone() };
            children.push(Node { element, incompressible: true, collapsed: false, children: message_nodes });
        }
        tasks.push(Node { element: ResultsElement::Task { result: result.id.clone(), task }, incompressible: false, collapsed: false, children });
    }
    tasks
}

/// `getRootChildren`: the tasks of the newest result with tasks, then "n older results" holding the others.
fn root_nodes(results: &[TestResult]) -> Vec<Node> {
    let mut children = Vec::new();
    let mut older = Vec::new();
    for result in results {
        if children.is_empty() && !result.tasks.is_empty() {
            children = result_children(result);
        } else {
            older.push(Node { element: ResultsElement::Result { result: result.id.clone() }, incompressible: true, collapsed: true, children: result_children(result) });
        }
    }
    if children.is_empty() {
        return older;
    }
    if !older.is_empty() {
        children.push(Node { element: ResultsElement::Older { count: older.len() }, incompressible: true, collapsed: true, children: older });
    }
    children
}

/// The visible rows below `node`, compressing a node with its only compressible child.
fn push_rows(node: &Node, depth: usize, toggled: &std::collections::HashSet<String>, rows: &mut Vec<ResultsRow>) {
    let mut last = node;
    let mut chain = vec![&node.element];
    while let [child] = last.children.as_slice()
        && !child.incompressible
    {
        chain.push(&child.element);
        last = child;
    }
    let (element, subject) = match chain.as_slice() {
        [.., parent, child @ (ResultsElement::Task { .. } | ResultsElement::Message { .. })] => (*parent, Some((*child).clone())),
        [.., only] => (*only, None),
        [] => unreachable!("the chain starts with the node"),
    };
    let collapsible = !last.children.is_empty();
    let collapsed = collapsible && node.collapsed != toggled.contains(&element.id());
    rows.push(ResultsRow { element: element.clone(), subject, depth, collapsible, collapsed });
    if collapsible && !collapsed {
        for child in &last.children {
            push_rows(child, depth + 1, toggled, rows);
        }
    }
}

impl Workbench {
    pub(super) fn register_testing_results_commands(&mut self) {
        // `requestReveal` of the actions' Show Result Output: a task's output, or a test's in that task.
        self.commands.register("_testing.results.showOutput", |workbench, args, _, cx| {
            let (Some(result), Some(task)) = (args.first().and_then(Value::as_str), args.get(1).and_then(Value::as_u64)) else { return Outcome::done() };
            let (result, task) = (result.to_owned(), task as usize);
            workbench.show_results_subject(match args.get(2).and_then(Value::as_str) {
                Some(test) => InspectSubject::Output { result, task, test: test.to_owned() },
                None => InspectSubject::Task { result, task },
            });
            cx.notify();
            Outcome::done()
        });
        // `Go to Error`: the message's location, keeping focus in the results.
        self.commands.register("_testing.results.goToError", |workbench, args, window, cx| {
            let Some(location) = args.first() else { return Outcome::done() };
            let Some(path) = location["uri"]["path"].as_str().map(std::path::PathBuf::from) else { return Outcome::done() };
            let range = &location["range"];
            let at = |key: &str| range[key].as_u64().unwrap_or(1) as usize;
            workbench.open_file(path.clone(), true, window, cx);
            let range = crate::anything_quick_access::TextRange { start_line_number: at("startLineNumber"), start_column: at("startColumn"), end_line_number: at("endLineNumber"), end_column: at("endColumn") };
            workbench.select_range(&path, range, cx);
            Outcome::done()
        });
        // callStackWidget.ts `callStackWidget.goToFile`: the frame's file at its position.
        self.commands.register("callStackWidget.goToFile", |workbench, args, window, cx| {
            let Some(path) = args.first().and_then(|location| location["uri"]["path"].as_str()).map(std::path::PathBuf::from) else { return Outcome::done() };
            let range = &args[0]["range"];
            let at = |key: &str| range[key].as_u64().unwrap_or(1) as usize;
            workbench.open_file(path.clone(), true, window, cx);
            let range = crate::anything_quick_access::TextRange { start_line_number: at("startLineNumber"), start_column: at("startColumn"), end_line_number: at("endLineNumber"), end_column: at("endColumn") };
            workbench.select_range(&path, range, cx);
            Outcome::done()
        });
        // testResultsViewContent.ts `runInLast` of a message's test: its current item in the group.
        for (id, group) in [("testing.callStack.run", GROUP_RUN), ("testing.callStack.debug", GROUP_DEBUG)] {
            self.commands.register(id, move |workbench, args, window, cx| {
                let Some(test) = args.first().and_then(Value::as_str).filter(|test| workbench.testing.collection.items.contains_key(*test)) else { return Outcome::done() };
                workbench.run_or_notify(&[test.to_owned()], group, window, cx);
                Outcome::done()
            });
        }
        self.commands.register("vscode.revealTest", |workbench, args, window, cx| {
            if let Some(id) = args.first().and_then(Value::as_str) {
                workbench.reveal_test(id, window, cx);
            }
            Outcome::done()
        });
        // testExplorerActions.ts `RunOrDebugLastRun`: the run's request again, or its tests in the other group.
        for (id, group) in [("testing.reRunLastRun", GROUP_RUN), ("testing.debugLastRun", GROUP_DEBUG)] {
            self.commands.register(id, move |workbench, args, window, cx| {
                let run = args.first().and_then(Value::as_str);
                let Some(last) = workbench.testing.results.iter().find(|result| run.is_none_or(|run| result.id == run)) else { return Outcome::done() };
                let request = last.request.clone();
                if request["group"].as_u64().unwrap_or(GROUP_RUN) & group != 0 {
                    workbench.run_resolved_tests(request, window, cx);
                    cx.notify();
                    return Outcome::done();
                }
                let ids: Vec<String> = request["targets"].as_array().into_iter().flatten().flat_map(|target| target["testIds"].as_array().into_iter().flatten()).filter_map(|id| id.as_str().map(str::to_owned)).collect();
                workbench.run_or_notify(&ids, group, window, cx);
                Outcome::done()
            });
        }
        // `RunOrDebugFailedTests`: the tests whose latest own state across the results is failed or errored.
        for (id, group) in [("testing.reRunFailedFromLastRun", GROUP_RUN), ("testing.debugFailedFromLastRun", GROUP_DEBUG)] {
            self.commands.register(id, move |workbench, _, window, cx| {
                let mut failed = Vec::new();
                for result in workbench.testing.results.iter().rev() {
                    for (test, item) in &result.items {
                        failed.retain(|id| id != test);
                        if matches!(item.own_state, ResultState::Failed | ResultState::Errored) {
                            failed.push(test.clone());
                        }
                    }
                }
                failed.sort();
                workbench.run_or_notify(&failed, group, window, cx);
                Outcome::done()
            });
        }
    }

    /// The rows the tree shows, `testing_view.results_toggled` holding the rows flipped from their default.
    pub(super) fn results_rows(&self) -> Vec<ResultsRow> {
        let mut rows = Vec::new();
        for node in root_nodes(&self.testing.results) {
            push_rows(&node, 0, &self.testing_view.results_toggled, &mut rows);
        }
        rows
    }

    /// `CoverageElement.isOpen`.
    fn is_coverage_open(&self, element: &ResultsElement) -> bool {
        let ResultsElement::Coverage { result, task } = element else { return false };
        let task_id = &self.result_by_id(result).expect("rows come from the results").tasks[*task].id;
        self.testing.coverage.selected.as_ref().is_some_and(|(selected_result, selected_task)| selected_result == result && selected_task == task_id)
    }

    /// `onDidOpen` of a `CoverageElement`: closes the open coverage, else opens the task's with focus.
    pub(super) fn open_coverage_element(&mut self, element: &ResultsElement, cx: &mut Context<Self>) {
        let ResultsElement::Coverage { result, task } = element else { return };
        match self.is_coverage_open(element) {
            true => self.testing.coverage.selected = None,
            false => self.open_coverage(result, *task, true, cx),
        }
    }

    fn result_by_id(&self, id: &str) -> Option<&TestResult> {
        self.testing.results.iter().find(|result| result.id == id)
    }

    /// `ITreeElement` `label`, `description` and `icon`.
    fn results_label(&self, element: &ResultsElement) -> (String, Option<String>, Option<ResultState>) {
        match element {
            ResultsElement::Result { result } => {
                let result = self.result_by_id(result).expect("rows come from the results");
                let state = match result.completed_at {
                    None => ResultState::Running,
                    Some(_) => result.items.values().fold(ResultState::Unset, |state, item| state.max(item.own_state)),
                };
                (result.name(), None, Some(state))
            }
            ResultsElement::Older { count: 1 } => ("1 older result".into(), None, None),
            ResultsElement::Older { count } => (format!("{count} older results"), None, None),
            ResultsElement::Task { result, task } => {
                let task = &self.result_by_id(result).expect("rows come from the results").tasks[*task];
                (task.name.clone(), None, task.running.then_some(ResultState::Running))
            }
            ResultsElement::Coverage { .. } if self.is_coverage_open(element) => ("Close Test Coverage".into(), None, None),
            ResultsElement::Coverage { .. } => ("View Test Coverage".into(), None, None),
            ResultsElement::Test { result, task, test } => {
                let result = self.result_by_id(result).expect("rows come from the results");
                let item = &result.items[test];
                let mut parents = Vec::new();
                let mut parent = parent_id(test);
                while let Some(id) = parent.filter(|id| parent_id(id).is_some()) {
                    let Some(parent_item) = result.items.get(id) else { break };
                    parents.push(parent_item.label().to_owned());
                    parent = parent_id(id);
                }
                let description = parent_id(test).map(|_| parents.join(" \u{2039} "));
                (item.label().to_owned(), description, Some(item.tasks[*task].state))
            }
            ResultsElement::Message { result, task, test, message } => {
                let result = self.result_by_id(result).expect("rows come from the results");
                // testTypes.ts `renderTestMessageAsText`: a markdown message by `renderAsPlaintext`.
                let message = &result.items[test].tasks[*task].messages[*message];
                let text = match message["message"].is_object() {
                    true => crate::markdown::plain_text(&crate::markdown::parse(&MarkdownString::from_value(&message["message"]))),
                    false => message_text(message).to_owned(),
                };
                let lines = text.trim_end().matches('\n').count();
                let description = match lines {
                    0 => None,
                    1 => Some("+ 1 more line".to_owned()),
                    lines => Some(format!("+ {lines} more lines")),
                };
                (text.split('\n').next().unwrap_or_default().to_owned(), description, None)
            }
        }
    }

    /// `doRenderInner`: a row compressed with an error message describes itself with the message.
    pub(super) fn results_row_label(&self, row: &ResultsRow) -> (String, Option<String>, Option<ResultState>) {
        let (label, description, state) = self.results_label(&row.element);
        let Some(subject @ ResultsElement::Message { .. }) = &row.subject else { return (label, description, state) };
        let message = self.results_label(subject).0;
        let description = match description {
            Some(own) => format!("{message} @ {own}"),
            None => message,
        };
        (label, Some(description), state)
    }

    /// `getTaskContext`.
    fn result_task_context(&self, result: &str, task: usize) -> Value {
        let task = &self.result_by_id(result).expect("rows come from the results").tasks[task];
        json!({ "testRunName": task.name, "controllerId": task.controller_id, "resultId": result, "taskId": task.id })
    }

    /// `InternalTestItem.serialize` of the result's test.
    fn result_test_arg(&self, result: &str, test: &str) -> Value {
        let item = &self.result_by_id(result).expect("rows come from the results").items[test];
        json!({ "expand": item.expand, "item": item.item })
    }

    /// The element's `context`, spread over the actions' arguments by `SpreadableActionRunner`.
    fn results_element_args(&self, element: &ResultsElement) -> Vec<Value> {
        match element {
            ResultsElement::Result { result } => vec![json!(result)],
            ResultsElement::Older { .. } | ResultsElement::Coverage { .. } => Vec::new(),
            ResultsElement::Task { result, task } => vec![self.result_task_context(result, *task)],
            ResultsElement::Test { result, task, test } => vec![json!({ "$mid": TEST_ITEM_CONTEXT_MID, "tests": [self.result_test_arg(result, test)] }), self.result_task_context(result, *task)],
            ResultsElement::Message { result, task, .. } => vec![self.message_args(element), self.result_task_context(result, *task)],
        }
    }

    /// testResultsSubject.ts `getMessageArgs`.
    fn message_args(&self, element: &ResultsElement) -> Value {
        let ResultsElement::Message { result, task, test, message } = element else { unreachable!("a message element") };
        let message = &self.result_by_id(result).expect("rows come from the results").items[test].tasks[*task].messages[*message];
        json!({ "$mid": TEST_MESSAGE_MENU_ARGS_MID, "test": self.result_test_arg(result, test), "message": message })
    }

    /// `TreeActionsProvider.provideActionBar`: the built-in actions, then the `inline` group of
    /// `MenuId.TestPeekElement` (`MenuId.TestMessageContext` on a message) as primary and the other groups after
    /// the built-in secondary ones.
    pub(super) fn results_actions(&self, element: &ResultsElement, window: &Window) -> (Vec<ResultsAction>, Vec<ResultsAction>, Vec<MenuAction>) {
        let mut primary = Vec::new();
        let mut secondary = Vec::new();
        let mut context = self.key_context(window);
        let mut menu = MenuId::TestPeekElement;
        match element {
            ResultsElement::Task { result: result_id, task } => {
                let result = self.result_by_id(result_id).expect("rows come from the results");
                primary.push(ResultsAction::new("terminal", "Show Result Output", "_testing.results.showOutput", vec![json!(result_id), json!(task)]));
                if result.tasks[*task].running {
                    primary.push(ResultsAction::new("debug-stop", "Cancel Test Run", "testing.cancelRun", vec![json!(result_id), json!(result.tasks[*task].id)]));
                } else {
                    let failed = result.items.values().any(|item| matches!(item.own_state, ResultState::Failed | ResultState::Errored));
                    primary.push(ResultsAction::new("debug-rerun", "Rerun Last Run", "testing.reRunLastRun", vec![json!(result_id)]));
                    if failed {
                        primary.push(ResultsAction::new("debug-rerun", "Rerun Failed Tests", "testing.reRunFailedFromLastRun", vec![json!(result_id)]));
                    }
                    primary.push(ResultsAction::new("debug-alt-small", "Debug Last Run", "testing.debugLastRun", vec![json!(result_id)]));
                    if failed {
                        primary.push(ResultsAction::new("debug-alt-small", "Debug Failed Tests", "testing.debugFailedFromLastRun", vec![json!(result_id)]));
                    }
                }
            }
            ResultsElement::Result { result: result_id } => {
                let result = self.result_by_id(result_id).expect("rows come from the results");
                if result.tasks.len() == 1 {
                    primary.push(ResultsAction::new("terminal", "Show Result Output", "_testing.results.showOutput", vec![json!(result_id), json!(0)]));
                }
                primary.push(ResultsAction::new("run", "Rerun Test", "testing.reRunLastRun", vec![json!(result_id)]));
                if result.items.values().any(|item| matches!(item.own_state, ResultState::Failed | ResultState::Errored)) {
                    primary.push(ResultsAction::new("debug-rerun", "Rerun Failed Tests", "testing.reRunFailedFromLastRun", vec![json!(result_id)]));
                }
            }
            ResultsElement::Test { result: result_id, task, test } | ResultsElement::Message { result: result_id, task, test, .. } => {
                let result = self.result_by_id(result_id).expect("rows come from the results");
                let item = &result.items[test];
                let capabilities = self.test_capabilities(test);
                context = self.test_item_context(test, window);
                context.insert("testResultOutdated".into(), json!(item.retired));
                context.insert("testResultState".into(), json!(result_state_context(item.own_state)));
                if !item.item["uri"].is_null() {
                    primary.push(ResultsAction::new("go-to-file", "Go to Test", "vscode.revealTest", vec![json!(test)]));
                }
                if item.tasks[*task].messages.iter().any(|message| !is_error_message(message)) {
                    primary.push(ResultsAction::new("terminal", "Show Result Output", "_testing.results.showOutput", vec![json!(result_id), json!(task), json!(test)]));
                }
                secondary.push(ResultsAction::new("list-tree", "Reveal in Test Explorer", "_revealTestInExplorer", vec![json!(test)]));
                if capabilities & GROUP_RUN != 0 {
                    primary.push(ResultsAction::new("run", "Run Test", "vscode.runTestsById", vec![json!(GROUP_RUN), json!(test)]));
                }
                if capabilities & GROUP_DEBUG != 0 {
                    primary.push(ResultsAction::new("debug-alt-small", "Debug Test", "vscode.runTestsById", vec![json!(GROUP_DEBUG), json!(test)]));
                }
            }
            ResultsElement::Older { .. } | ResultsElement::Coverage { .. } => {}
        }
        if let ResultsElement::Message { result, task, test, message } = element {
            menu = MenuId::TestMessageContext;
            let message = &self.result_by_id(result).expect("rows come from the results").items[test].tasks[*task].messages[*message];
            context.insert("testMessage".into(), message["contextValue"].clone());
            // testingOutputPeek.ts `TestResultsView` passes `showRevealLocationOnMessages: true`.
            if message["location"].is_object() {
                primary.push(ResultsAction::new("debug-stackframe", "Go to Error", "_testing.results.goToError", vec![message["location"].clone()]));
            }
        }
        context.insert("peek".into(), json!("editor.contrib.testingOutputPeek"));
        context.insert("peekItemType".into(), json!(element.kind()));
        let args = self.results_element_args(element);
        for action in menu_group_actions(&self.menus, menu, &context, |group| group == "inline") {
            if let MenuAction::Command { id, title, .. } = action {
                primary.push(ResultsAction { icon: None, title, command: id, args: args.clone() });
            }
        }
        let contributed = menu_group_actions(&self.menus, menu, &context, |group| group != "inline");
        (primary, secondary, contributed)
    }

    /// `OutputPeekTree.onContextMenu`: the row's primary actions, a separator, then its secondary ones.
    fn show_results_menu(&mut self, element: &ResultsElement, position: gpui::Point<gpui::Pixels>, window: &mut Window, cx: &mut Context<Self>) {
        let actions = self.results_menu_actions(element, window);
        let context = self.key_context(window);
        self.show_context_menu_actions(actions, &context, gpui::Bounds::new(position, Default::default()), Vec::new(), window, cx);
    }

    pub(super) fn results_menu_actions(&mut self, element: &ResultsElement, window: &Window) -> Vec<MenuAction> {
        let (primary, secondary, contributed) = self.results_actions(element, window);
        let args = self.results_element_args(element);
        let mut actions: Vec<MenuAction> = primary.into_iter().map(|action| self.bound_action(&action.title, &action.command, action.args)).collect();
        let mut rest: Vec<MenuAction> = secondary.into_iter().map(|action| self.bound_action(&action.title, &action.command, action.args)).collect();
        if !rest.is_empty() && !contributed.is_empty() {
            rest.push(MenuAction::Separator);
        }
        for action in contributed {
            let action = self.forward_with_args(action, &args);
            rest.push(action);
        }
        if !rest.is_empty() {
            actions.push(MenuAction::Separator);
            actions.extend(rest);
        }
        actions
    }

    /// listService.ts keys of the focused results tree: `listFocus` and the focused row's `treeElement*` keys.
    pub(super) fn testing_results_list_context(&self, window: &Window, context: &mut HashMap<String, Value>) {
        if !self.testing_view.results_focus.is_focused(window) {
            return;
        }
        context.insert("listFocus".into(), json!(true));
        let rows = self.results_rows();
        let Some(index) = rows.iter().position(|row| self.testing_view.results_focused.as_ref() == Some(&row.target().id())) else { return };
        let depths: Vec<usize> = rows.iter().map(|row| row.depth).collect();
        context.insert("listHasSelectionOrFocus".into(), json!(true));
        context.insert("treeElementCanCollapse".into(), json!(rows[index].collapsible && !rows[index].collapsed));
        context.insert("treeElementCanExpand".into(), json!(rows[index].collapsed));
        context.insert("treeElementHasChild".into(), json!(depths.get(index + 1).is_some_and(|child| *child > depths[index])));
        context.insert("treeElementHasParent".into(), json!(crate::list_tree::parent(&depths, index).is_some()));
    }

    /// listCommands.ts on the results tree while it has the focus; false for a command of another list.
    pub(super) fn testing_results_list_command(&mut self, id: &str, window: &mut Window, cx: &mut Context<Self>) -> bool {
        if !self.testing_view.results_focus.is_focused(window) {
            return false;
        }
        let rows = self.results_rows();
        if rows.is_empty() {
            return true;
        }
        let focus = rows.iter().position(|row| self.testing_view.results_focused.as_ref() == Some(&row.target().id()));
        let depths: Vec<usize> = rows.iter().map(|row| row.depth).collect();
        let last = rows.len() - 1;
        let next = match id {
            "list.focusDown" | "list.focusAnyDown" => focus.map_or(0, |index| (index + 1).min(last)),
            "list.focusUp" | "list.focusAnyUp" => focus.map_or(last, |index| index.saturating_sub(1)),
            "list.focusFirst" | "list.focusAnyFirst" => 0,
            "list.focusLast" | "list.focusAnyLast" => last,
            "list.focusParent" => {
                let Some(parent) = focus.and_then(|index| crate::list_tree::parent(&depths, index)) else { return true };
                parent
            }
            // `expand` answers false for an expanded row, which then moves to its first child; `collapse` to the parent.
            "list.expand" | "list.collapse" | "list.toggleExpand" => {
                let Some(index) = focus else { return true };
                let row = &rows[index];
                let expand = id == "list.expand";
                match row.collapsible {
                    true if id == "list.toggleExpand" || row.collapsed == expand => {
                        self.toggle_results_row(&row.element);
                        cx.notify();
                        return true;
                    }
                    _ if expand && depths.get(index + 1).is_some_and(|child| *child > depths[index]) => index + 1,
                    _ if id != "list.collapse" => return true,
                    _ => {
                        let Some(parent) = crate::list_tree::parent(&depths, index) else { return true };
                        parent
                    }
                }
            }
            "list.select" | "list.selectAndPreserveFocus" => {
                let Some(index) = focus else { return true };
                let target = rows[index].target().clone();
                self.testing_view.results_selected = Some(target.id());
                self.open_results_element(&target);
                self.open_coverage_element(&target, cx);
                cx.notify();
                return true;
            }
            "list.clear" => {
                self.testing_view.results_selected = None;
                cx.notify();
                return true;
            }
            _ => return true,
        };
        self.testing_view.results_focused = Some(rows[next].target().id());
        cx.notify();
        true
    }

    fn toggle_results_row(&mut self, element: &ResultsElement) {
        let toggled = &mut self.testing_view.results_toggled;
        if !toggled.remove(&element.id()) {
            toggled.insert(element.id());
        }
    }

    /// `onDidOpen`: a message shows itself, a test its first message or else its output, the others nothing.
    fn open_results_element(&mut self, element: &ResultsElement) {
        let subject = match element {
            ResultsElement::Message { result, task, test, message } => InspectSubject::Message { result: result.clone(), task: *task, test: test.clone(), message: *message },
            ResultsElement::Test { result: result_id, test, .. } => {
                let result = self.result_by_id(result_id).expect("rows come from the results");
                let first = result.items[test].tasks.iter().enumerate().find_map(|(task, state)| (!state.messages.is_empty()).then_some(task));
                match first {
                    Some(task) => InspectSubject::Message { result: result_id.clone(), task, test: test.clone(), message: 0 },
                    None => InspectSubject::Output { result: result_id.clone(), task: 0, test: test.clone() },
                }
            }
            _ => return,
        };
        self.show_results_subject(subject);
    }

    /// testResultsViewContent.ts `reveal`: the subject's content and its call stack.
    pub(super) fn show_results_subject(&mut self, subject: InspectSubject) {
        self.testing_view.results_subject = Some(subject);
        self.text_selection.collapse_in(super::markdown_view::MARKDOWN_TEXTS);
        self.show_message_editor();
        self.show_call_stack();
    }

    /// `setCallStackFrames` with `MessageSubject.stack`: an error message's stack frames, each with a source in a
    /// read-only code editor of its file (`FrameCodeRenderer`) showing its line and `CONTEXT_LINES` around it.
    fn show_call_stack(&mut self) {
        let frames = self.subject_stack();
        let old = std::mem::replace(&mut self.testing_view.call_stack, frames);
        self.testing_view.call_stack_collapsed.clear();
        if old.is_empty() && self.testing_view.call_stack.is_empty() {
            return;
        }
        self.editors.ensure_detached_group(TEST_RESULTS_GROUP);
        self.with_group(TEST_RESULTS_GROUP, |workbench| {
            for index in 0..old.len() {
                workbench.drop_peek_editor(PeekOwner::CallStackFrame(index));
            }
            for (index, frame) in workbench.testing_view.call_stack.clone().into_iter().enumerate() {
                let Some((scheme, path)) = frame.source else { continue };
                if workbench.editors.model(&scheme, &path).is_none() {
                    // `createModelReference` of a file that cannot be read rejects: the frame has no editor.
                    let read = (scheme == "file").then(|| TextDocument::read(&path, &workbench.languages, &workbench.settings.lock().unwrap()));
                    let Some(Ok(document)) = read else { continue };
                    workbench.editors.open_model(document);
                }
                let editor = &mut workbench.editors.show_in_peek_editor(PeekOwner::CallStackFrame(index), &scheme, &path, || unreachable!("the model is open")).editor;
                let count = editor.document().lines.len();
                // `setupEditorAfterModel`: lines 1 to `line - CONTEXT_LINES - 1` (at least line 1) and from `line + CONTEXT_LINES + 1` hidden.
                let before = 0..frame.line.saturating_sub(CONTEXT_LINES + 1).max(1);
                editor.folding.set_hidden_areas(vec![before, (frame.line + CONTEXT_LINES).min(count)..count]);
            }
        });
    }

    /// callStackWidget.ts `setupEditorAfterModel`: each frame's editor marks its frame's column, 1 too. The marker's
    /// width is in columns of `char_width`, which the results group's viewport lacks until its editors draw.
    pub(super) fn sync_call_stack_frame_columns(&mut self, char_width: f32) {
        for (index, frame) in self.testing_view.call_stack.iter().enumerate() {
            let Some(peek) = self.editors.peek_editors.iter_mut().find(|peek| peek.owner == PeekOwner::CallStackFrame(index)) else { continue };
            let line = frame.line.saturating_sub(1);
            let Some(text) = peek.editor.document().lines.get(line).cloned() else { continue };
            let wanted = super::breakpoint_widget::stack_frame_column(&text, line, frame.column, char_width);
            let current: Vec<_> = peek.editor.injected_text.iter().filter(|injection| injection.owner == crate::editor::injected_text::InjectionOwner::StackFrameColumn).collect();
            if current != [&wanted] {
                peek.editor.set_injected_text(crate::editor::injected_text::InjectionOwner::StackFrameColumn, vec![wanted]);
            }
        }
    }

    /// testResultsSubject.ts `MessageSubject.stack`: the stack trace of an opened error message.
    fn subject_stack(&self) -> Vec<CallStackFrame> {
        let Some(InspectSubject::Message { result, task, test, message }) = &self.testing_view.results_subject else { return Vec::new() };
        let message = &self.result_by_id(result).expect("the subject is a result's").items[test].tasks[*task].messages[*message];
        if !is_error_message(message) {
            return Vec::new();
        }
        let mut frames = Vec::new();
        for frame in message["stackTrace"].as_array().into_iter().flatten() {
            let source = super::host_requests::uri_parts(&frame["uri"]).ok().map(|(scheme, path)| (scheme.to_owned(), path));
            let at = |key: &str| frame["position"][key].as_u64().map_or(1, |value| value as usize);
            frames.push(CallStackFrame { label: frame["label"].as_str().unwrap_or_default().to_owned(), source, line: at("lineNumber"), column: at("column") });
        }
        frames
    }

    /// The call stack frame whose code editor `editor` is.
    pub(super) fn call_stack_frame(&self, editor: &OpenEditor) -> Option<&CallStackFrame> {
        let peek = self.editors.peek_editors.iter().find(|peek| peek.editor.model_id == editor.model_id)?;
        let PeekOwner::CallStackFrame(index) = peek.owner else { return None };
        self.testing_view.call_stack.get(index)
    }

    /// The call stack widget's headers, none without a stack: the message's frame (`MessageStackFrame`: the testing
    /// view icon and the test's label), then each frame, by `ResourceLabel.setFile` with a source, else its name,
    /// the line as the label's `range` suffix and `Line {0} column {1}`.
    pub(super) fn results_call_stack_rows(&self) -> Vec<CallStackRow> {
        let Some(InspectSubject::Message { result, test, .. }) = &self.testing_view.results_subject else { return Vec::new() };
        let Some(item) = self.result_by_id(result).and_then(|result| result.items.get(test)).filter(|_| !self.testing_view.call_stack.is_empty()) else { return Vec::new() };
        let label = item.item["label"].as_str().unwrap_or_default().to_owned();
        let mut rows = vec![CallStackRow { icon: Some("beaker"), label, suffix: None, description: None, editor: None }];
        for (index, frame) in self.testing_view.call_stack.iter().enumerate() {
            rows.push(match &frame.source {
                Some((_, path)) => {
                    let label = path.file_name().map(|name| name.to_string_lossy().into_owned()).unwrap_or_default();
                    let folder = path.parent().map(|folder| crate::quick_input::path_label(folder, self.workspace())).filter(|folder| !folder.is_empty() && folder != ".");
                    let editor = self.editors.peek_editor(PeekOwner::CallStackFrame(index)).map(|editor| editor.model_id);
                    CallStackRow { icon: None, label, suffix: None, description: folder, editor }
                }
                None => CallStackRow { icon: Some("file-binary"), label: frame.label.clone(), suffix: Some(format!(":{}", frame.line)), description: Some(format!("Line {} column {}", frame.line, frame.column)), editor: None },
            });
        }
        rows
    }

    /// testResultsOutput.ts `DiffContentProvider` and `PlainTextMessagePeek` `update`: a diffable message opens its
    /// `expectedUri` and `actualUri` models in an embedded diff editor, a plain text one its `messageUri` model in a
    /// read-only code editor.
    fn show_message_editor(&mut self) {
        let Some(InspectSubject::Message { result, task, test, message }) = self.testing_view.results_subject.clone() else { return };
        let value = self.result_by_id(&result).expect("the subject is a result's").items[&test].tasks[task].messages[message].clone();
        let diffable = is_diffable(&value);
        if !diffable && !is_plain_text_message(&value) {
            return;
        }
        let path = |part| message_path(&result, task, &test, message, part);
        let document = |workbench: &Self, scheme, part, text: &str| TextDocument::from_text(scheme, &path(part), text, "utf8".into(), None, &workbench.languages, &workbench.settings.lock().unwrap());
        self.editors.ensure_detached_group(TEST_RESULTS_GROUP);
        self.with_group(TEST_RESULTS_GROUP, |workbench| {
            if workbench.editors.editors.first().is_some_and(|editor| editor.document().path == path(MESSAGE_PART)) {
                workbench.editors.activate(0);
                return;
            }
            let replaced = workbench.editors.editors.first().map(|editor| editor.model_id);
            if diffable {
                let (expected, actual) = (value["expected"].as_str().expect("diffable"), value["actual"].as_str().expect("diffable"));
                for (part, text) in [(EXPECTED_PART, expected), (ACTUAL_PART, actual)] {
                    if workbench.editors.model(TEST_DATA_SCHEME, &path(part)).is_none() {
                        workbench.editors.open_model(document(workbench, TEST_DATA_SCHEME, part, text));
                    }
                }
                let side = |part| Side { scheme: TEST_DATA_SCHEME.into(), path: path(part) };
                let input = DiffInput { embedded: true, ..DiffInput::new(side(EXPECTED_PART), side(ACTUAL_PART), None) };
                workbench.editors.open_diff(document(workbench, DIFF_EDITOR_SCHEME, MESSAGE_PART, ""), input, false);
                // DiffContentProvider `getOptions`: line numbers when either side is multiline.
                let line_numbers = (expected.contains('\n') || actual.contains('\n')).then_some("on");
                let id = workbench.editors.active_tab().expect("just opened").model_id;
                let input = workbench.editors.diffs.get_mut(&id).expect("just opened");
                for editor in [&mut input.original_editor, &mut input.modified_editor].into_iter().flatten() {
                    editor.line_numbers_override = line_numbers;
                    // testingDecorations.ts `TitleLensContentWidget`: a 20px zone above line 1 holds the side's title.
                    editor.add_view_zone(None, DIFF_LENS_ZONE_HEIGHT);
                }
            } else {
                let text = testing_message_colorizer::remove_ansi_escape_codes(message_text(&value));
                workbench.editors.open(document(workbench, TEST_DATA_SCHEME, MESSAGE_PART, &text), false);
                let editor = workbench.editors.active_mut().expect("just opened");
                editor.text_decorations = testing_message_colorizer::colorize_test_message(message_text(&value));
                // wordHighlighter.ts runs on an explicit cursor move or the text focus, which a model set here is not.
                editor.highlights.clear();
            }
            if let Some(replaced) = replaced {
                let index = workbench.editors.editors.iter().position(|editor| editor.model_id == replaced).expect("not closed yet");
                workbench.editors.close(index);
            }
            workbench.update_diff_editor();
        });
    }

    /// testingDecorations.ts `ExpectedLensContentWidget` and `ActualLensContentWidget`: the title above line 1 of an
    /// expected or actual output model, bottom-aligned in the zone `id` that `show_message_editor` added.
    pub(super) fn testing_diff_lens(&self, editor: &crate::editor::OpenEditor, id: u32, height: f32, content_left: f32) -> Option<Div> {
        let document = editor.document();
        let zone = editor.view_zone(id)?;
        let title = match document.path.to_string_lossy() {
            _ if document.scheme != TEST_DATA_SCHEME || zone.anchor.is_some() => return None,
            path if path.contains(&format!("/{EXPECTED_PART}?")) => "Expected",
            path if path.contains(&format!("/{ACTUAL_PART}?")) => "Actual",
            _ => return None,
        };
        let setting = self.suggest_setting(editor, "editor.codeLensFontSize").as_f64().unwrap_or(0.);
        let line_height = if setting < 5. { self.editors.viewport.line_height } else { self.code_lens_height() };
        let family = self.suggest_setting(editor, "editor.codeLensFontFamily");
        let family = family.as_str().filter(|family| !family.is_empty()).unwrap_or(super::peek_view::UI_FONT).to_owned();
        let label = div().absolute().bottom_0().left(px(content_left)).h(px(line_height)).whitespace_nowrap().font_family(family).text_size(px(self.code_lens_font_size())).line_height(px(line_height)).text_color(self.color("editorCodeLens.foreground")).child(title);
        Some(div().h(px(height)).relative().child(label))
    }

    /// TerminalMessagePeek `update`: what its terminal shows for a task, a test's output or an output message: the
    /// output, else once the run completed the notice that there is none.
    pub(super) fn terminal_output(&self) -> Option<String> {
        let (result_id, task, test) = match self.testing_view.results_subject.as_ref()? {
            InspectSubject::Task { result, task } => (result, *task, None),
            InspectSubject::Output { result, task, test } => (result, *task, Some(test)),
            InspectSubject::Message { result, task, test, message } => {
                let result = self.result_by_id(result)?;
                (result.items[test].tasks[*task].messages[*message]["type"] == 1).then_some(())?;
                (&result.id, *task, Some(test))
            }
        };
        let result = self.result_by_id(result_id)?;
        let (output, notice) = match test {
            None => (result.tasks.get(task)?.output.clone(), "The test run did not record any output."),
            Some(test) => {
                let messages = &result.items.get(test)?.tasks[task].messages;
                (messages.iter().filter(|message| message["type"] == 1).map(message_text).collect(), "The test case did not report any output.")
            }
        };
        if output.is_empty() && result.completed_at.is_some() {
            return Some(format!("\r\n{}", crate::terminal::format_message_for_terminal(notice)));
        }
        Some(output)
    }

    /// Writes `output` to the detached terminal: what it adds to the text written, else all of it after a reset
    /// (`makeTerminal` reuses the terminal with `\x1bc`), the cursor hidden (`attachTerminalToDom`).
    fn write_results_terminal(&mut self, output: String) -> u32 {
        let (id, written) = match self.testing_view.results_terminal.take() {
            Some((id, written)) => (id, Some(written)),
            None => (self.terminal_view.create_detached(80, 10, self.terminal_config()), None),
        };
        let colors = crate::terminal::colors::TerminalColors::new(&self.theme);
        let instance = self.terminal_view.instance_mut(id).expect("created above");
        match written.as_deref().and_then(|written| output.strip_prefix(written)) {
            Some(added) => {
                instance.process(added.as_bytes(), &colors);
            }
            None => {
                instance.process(format!("\x1bc\x1b[?25l{output}").as_bytes(), &colors);
            }
        }
        self.testing_view.results_terminal = Some((id, output));
        id
    }

    /// MarkdownTestMessagePeek `update`: the opened message's markdown, when it is neither a string nor diffable.
    pub(super) fn markdown_message(&self) -> Option<MarkdownString<'_>> {
        let Some(InspectSubject::Message { result, task, test, message }) = &self.testing_view.results_subject else { return None };
        let message = &self.result_by_id(result)?.items[test].tasks[*task].messages[*message];
        (message["message"].is_object() && !is_diffable(message)).then(|| MarkdownString::from_value(&message["message"]))
    }

    /// The tab of the opened message's code or diff editor, while it shows that message.
    fn message_editor(&self) -> Option<&crate::editor::OpenEditor> {
        let Some(InspectSubject::Message { result, task, test, message }) = &self.testing_view.results_subject else { return None };
        let in_group = self.editors.id == TEST_RESULTS_GROUP || self.editors.group(TEST_RESULTS_GROUP).is_some();
        let path = message_path(result, *task, test, *message, MESSAGE_PART);
        self.editors.group_tabs(TEST_RESULTS_GROUP).0.first().filter(|editor| in_group && editor.document().path == path)
    }

    /// The Test Results view: the opened subject's text and, by `testing.resultsView.layout`, the tree on its right
    /// or left. testResultsViewContent.ts adds both with `Sizing.Distribute` to a split view of size 0, which leaves
    /// them at their minimums, 200 and 100, so its proportional layout splits the width 2:1 down to those minimums.
    pub(super) fn test_results_body(&mut self, window: &mut Window, cx: &mut Context<Self>) -> Div {
        let content = self.results_content(window, cx).flex_grow(2.).min_w(px(200.)).debug_selector(|| "test-results-content".into());
        let tree = self.results_tree(window, cx).min_w(px(100.)).debug_selector(|| "test-results-tree".into());
        let body = div().flex_1().min_h_0().flex();
        match self.setting("testing.resultsView.layout").as_str() {
            Some("treeLeft") => body.child(tree).child(content),
            _ => body.child(content).child(tree),
        }
    }

    fn results_tree(&self, window: &Window, cx: &mut Context<Self>) -> gpui::Stateful<Div> {
        let focus = self.testing_view.results_focus.clone();
        let tree_focused = focus.is_focused(window);
        let rows = self.results_rows();
        let selected: Vec<usize> = rows.iter().enumerate().filter(|(_, row)| self.testing_view.results_selected.as_ref() == Some(&row.target().id())).map(|(index, _)| index).collect();
        let guides = self.tree_guides_in_group("test-results-tree".into(), rows.iter().map(|row| row.depth).collect(), &selected);
        let inset = self.pane_row_inset();
        let mut tree = div()
            .id("test-results-tree")
            .group("test-results-tree")
            .track_focus(&focus)
            .capture_any_mouse_down(move |_, window, cx| window.focus(&focus, cx))
            .text_color(self.color("editor.foreground"))
            .flex()
            .flex_col();
        for (index, row) in rows.into_iter().enumerate() {
            let row = self.results_row(row, selected.contains(&index), tree_focused, window, cx);
            tree = tree.child(div().relative().child(row).children(guides.row(index, inset)));
        }
        self.scrollable("test-results-tree", None, tree, cx).flex_1().border_l_1().border_color(self.color("panelSection.border"))
    }

    /// `TestRunElementRenderer.doRenderInner`: twistie, state icon, label with its description, and the primary
    /// actions while hovered (testing.css `.testing-stdtree-container`).
    fn results_row(&self, row: ResultsRow, selected: bool, tree_focused: bool, window: &Window, cx: &mut Context<Self>) -> gpui::Stateful<Div> {
        let (label, description, state) = self.results_row_label(&row);
        let twistie_color = self.foreground_or("icon.foreground");
        let id = row.target().id();
        let is_focus = self.testing_view.results_focused.as_ref() == Some(&id);
        let mut label_box = div().flex_1().min_w_0().flex().items_baseline().overflow_hidden().whitespace_nowrap().child(div().min_w_0().overflow_hidden().text_ellipsis().child(label));
        if let Some(description) = description.filter(|description| !description.is_empty()) {
            label_box = label_box.child(div().flex_1().min_w_0().overflow_hidden().text_ellipsis().ml(px(6.5)).text_size(px(11.7)).opacity(0.7).child(description));
        }
        let mut actions = div().flex().flex_none().mr(px(10.)).invisible().group_hover("results-row", |actions| actions.visible());
        let (primary, ..) = self.results_actions(&row.element, window);
        for action in primary {
            actions = actions.child(self.results_action_button(action, cx));
        }
        let (toggle, open, menu, right_clicked) = (row.element.clone(), row.target().clone(), row.element.clone(), id.clone());
        let collapsible = row.collapsible;
        let element = div()
            .id(gpui::SharedString::from(format!("results-row:{id}")))
            .group("results-row")
            .h(px(ROW_HEIGHT))
            .flex_none()
            .mx(px(self.pane_row_inset()))
            .rounded(px(4.))
            // abstractTree.ts `DefaultIndent` (8px) plus the twistie's translateX(3px) (tree.css).
            .pl(px(self.tree_indent() * row.depth as f32 + 11.))
            .flex()
            .items_center()
            .cursor_pointer();
        // tree.css `.monaco-tl-twistie`: 16px and `padding-right: 6px` less the 3px shift.
        let twistie = div().w(px(19.)).flex_none();
        self.list_row_selection(element, selected, is_focus, tree_focused)
            .child(match row.collapsible {
                true => twistie.child(self.icon(if row.collapsed { "chevron-right" } else { "chevron-down" }, 16., 16., twistie_color)),
                false => twistie,
            })
            .child(match (state, &row.element) {
                (Some(state), _) => {
                    let (icon, color) = state_icon(state);
                    self.icon(icon, 16., 16., self.foreground_or(color)).mr(px(3.25))
                }
                // testResultsTree.ts `CoverageElement.icon`: `widgetClose` while open, else `testingCoverageReport`.
                (None, element @ ResultsElement::Coverage { .. }) => {
                    let icon = if self.is_coverage_open(element) { "close" } else { "coverage" };
                    self.icon(icon, 16., 16., twistie_color).mr(px(3.25))
                }
                (None, _) => div().w(px(3.25)).flex_none(),
            })
            .child(label_box)
            .child(actions)
            .on_click(cx.listener(move |workbench, _: &ClickEvent, _, cx| {
                workbench.testing_view.results_selected = Some(open.id());
                workbench.testing_view.results_focused = Some(open.id());
                if collapsible {
                    workbench.toggle_results_row(&toggle);
                }
                workbench.open_results_element(&open);
                workbench.open_coverage_element(&open, cx);
                cx.notify();
            }))
            .on_mouse_down(MouseButton::Right, cx.listener(move |workbench, event: &MouseDownEvent, window, cx| {
                workbench.testing_view.results_focused = Some(right_clicked.clone());
                workbench.show_results_menu(&menu, event.position, window, cx);
            }))
    }

    fn results_action_button(&self, action: ResultsAction, cx: &mut Context<Self>) -> gpui::Stateful<Div> {
        let foreground = self.foreground_or("icon.foreground");
        let Some(icon) = action.icon else { return self.command_button(&action.command, action.title, action.args, foreground, cx) };
        let (command, args) = (action.command, action.args);
        self.icon(icon, 22., 16., foreground)
            .id(gpui::SharedString::from(format!("results-action-{command}-{}", Value::from(args.clone()))))
            .rounded(px(4.))
            .cursor_pointer()
            .hover(|icon| icon.bg(self.color("toolbar.hoverBackground")))
            .on_mouse_down(MouseButton::Left, super::scm_view::stop_action_mouse_down)
            .on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
                cx.stop_propagation();
                drop(workbench.execute_command(&command, args.clone(), window, cx));
            }))
            .child(self.hover_target(gpui::SharedString::from(format!("results-action-hover-{}", action.title)), HoverContent::Text(action.title), HoverOptions::action_item()))
    }

    /// The subject, with the call stack widget around it when it has a stack; its code editors draw in the results group.
    fn results_content(&mut self, window: &mut Window, cx: &mut Context<Self>) -> gpui::Stateful<Div> {
        if self.message_editor().is_none() && self.testing_view.call_stack.is_empty() {
            return self.results_subject_view(window, cx);
        }
        let body = |workbench: &mut Self, window: &mut Window, cx: &mut Context<Self>| {
            // A diff's side and the frames' code editors draw unfocused before the body, as editor_groups.rs `editor_group_body` does.
            workbench.draw_unfocused_code_editors(window, cx);
            let body = match workbench.testing_view.call_stack.is_empty() {
                true => workbench.results_subject_view(window, cx),
                false => workbench.call_stack_view(window, cx),
            };
            workbench.unfocused_code_editors_placed();
            // callStackWidget.ts hosts the message and the frames in list rows, so the pane's list row inset applies.
            div().flex_1().min_w_0().flex().px(px(workbench.pane_row_inset())).child(body)
        };
        let body = match self.editors.id == TEST_RESULTS_GROUP {
            true => body(self, window, cx),
            false => self.swapped_group_body(TEST_RESULTS_GROUP, body, window, cx),
        };
        div().id("test-results-content").flex_1().min_w_0().flex().child(body)
    }

    /// callStackWidget.ts `CallStackWidget` of the message's frame and its stack: each frame a list row of a 24px
    /// header over its content (callStackWidget.css `.multiCallStackFrame`), none while collapsed: the message at
    /// its content height (`IPeekOutputRenderer.layout` with `hasMultipleFrames`), a frame's code editor at its own.
    fn call_stack_view(&mut self, window: &mut Window, cx: &mut Context<Self>) -> gpui::Stateful<Div> {
        let char_width = self.results_call_stack_rows().iter().find_map(|row| row.editor).and_then(|id| self.editors.editor_by_id(id)).map(|editor| self.editor_metrics(editor, window).char_width);
        if let Some(char_width) = char_width {
            self.sync_call_stack_frame_columns(char_width);
        }
        let viewport = crate::editor::Viewport { top_whitespace: 0., ..self.editors.viewport };
        let content_height = |editor: &OpenEditor| editor.line_top(editor.view_line_count(), viewport);
        let mut list = div().id("test-results-call-stack").flex().flex_col();
        for (index, row) in self.results_call_stack_rows().into_iter().enumerate() {
            let collapsible = index == 0 || self.testing_view.call_stack[index - 1].source.is_some();
            let collapsed = self.testing_view.call_stack_collapsed.contains(&index);
            list = list.child(self.call_stack_header(index, &row, collapsible, collapsed, window, cx));
            if collapsed {
                continue;
            }
            if index == 0 {
                let height = self.message_editor().map(|editor| match self.editors.diffs.get(&editor.model_id) {
                    Some(diff) => [&diff.original_editor, &diff.modified_editor].into_iter().flatten().map(content_height).fold(0., f32::max),
                    None => content_height(editor),
                });
                let message = self.results_subject_view(window, cx);
                list = list.child(div().flex_none().flex().when_some(height, |message, height| message.h(px(height))).child(message));
            } else if let Some(editor) = row.editor.and_then(|id| self.editors.editor_by_id(id)) {
                let frame = div().flex_none().h(px(content_height(editor))).flex().debug_selector(move || format!("test-results-frame-{index}"));
                list = list.child(frame.child(self.embedded_code_editor(editor, window, cx)));
            }
        }
        self.scrollable("test-results-call-stack", None, list, cx).flex_1()
    }

    /// callStackWidget.ts `makeFrameElements` header: the collapse button (the title toggles too), the
    /// `ResourceLabel` and the frame's toolbar: `MenuId.TestCallStack` for the message's frame with the test's
    /// capabilities as `capabilityContextKeys`, `MenuId.DebugCallStackToolbar` for a frame's code.
    fn call_stack_header(&self, index: usize, row: &CallStackRow, collapsible: bool, collapsed: bool, window: &Window, cx: &mut Context<Self>) -> gpui::Stateful<Div> {
        let foreground = self.color("foreground");
        let icon_foreground = self.foreground_or("icon.foreground");
        let toggle = move |workbench: &mut Self, cx: &mut Context<Self>| {
            let collapsed = &mut workbench.testing_view.call_stack_collapsed;
            if !collapsed.remove(&index) {
                collapsed.insert(index);
            }
            cx.notify();
        };
        let chevron = if collapsed { "chevron-right" } else { "chevron-down" };
        let collapse = div().id(("call-stack-collapse", index)).w(px(16.)).flex_none().when(collapsible, |button| {
            button.cursor_pointer().child(self.icon(chevron, 16., 16., icon_foreground)).on_click(cx.listener(move |workbench, _: &ClickEvent, _, cx| toggle(workbench, cx)))
        });
        let frame = index.checked_sub(1).map(|frame| &self.testing_view.call_stack[frame]);
        let icon = match (row.icon, frame.and_then(|frame| frame.source.as_ref())) {
            (Some(icon), _) => Some(self.icon(icon, 16., 16., icon_foreground)),
            (None, Some((_, path))) => self.file_icons.as_ref().and_then(|icons| icons.file_icon(path, self.languages.language_of(path, ""), self.theme.kind, 13., CALL_STACK_HEADER_HEIGHT, foreground)),
            (None, None) => None,
        };
        let mut label = div().flex().items_baseline().whitespace_nowrap().child(row.label.clone()).children(row.suffix.clone());
        if let Some(description) = &row.description {
            label = label.child(super::icon_label::label_description().opacity(0.7).child(description.clone()));
        }
        let title = div()
            .id(("call-stack-title", index))
            .flex_1()
            .min_w_0()
            .overflow_hidden()
            .flex()
            .items_center()
            .children(icon.map(|icon| icon.mr(px(6.))))
            .child(label)
            .when(collapsible, |title| title.cursor_pointer().on_click(cx.listener(move |workbench, _: &ClickEvent, _, cx| toggle(workbench, cx))));
        let mut actions = div().flex_none().flex().items_center().gap(px(8.)).mr(px(12.));
        for (id, title, args) in self.call_stack_actions(frame, window) {
            actions = actions.child(self.command_button(&id, title, args, icon_foreground, cx));
        }
        div()
            .id(("call-stack-header", index))
            .h(px(CALL_STACK_HEADER_HEIGHT))
            .flex_none()
            .flex()
            .items_center()
            .px(px(5.))
            .border_t_1()
            .when(collapsed, |header| header.border_b_1())
            .border_color(self.color("multiDiffEditor.border"))
            .bg(self.color("multiDiffEditor.headerBackground"))
            .text_color(foreground)
            .text_size(px(13.))
            .child(collapse)
            .child(title)
            .child(actions)
    }

    /// The commands of a frame's toolbar, with the arguments its `context` gives them: the subject's test, or the
    /// frame's location.
    fn call_stack_actions(&self, frame: Option<&CallStackFrame>, window: &Window) -> Vec<(String, String, Vec<Value>)> {
        let (menu, context, args) = match frame {
            None => {
                let Some(InspectSubject::Message { test, .. }) = &self.testing_view.results_subject else { return Vec::new() };
                let capabilities = self.test_capabilities(test);
                let mut context = self.key_context(window);
                context.insert("testing.hasRunnableTests".into(), json!(capabilities & GROUP_RUN != 0));
                context.insert("testing.hasDebuggableTests".into(), json!(capabilities & GROUP_DEBUG != 0));
                (MenuId::TestCallStack, context, vec![json!(test)])
            }
            Some(CallStackFrame { source: Some((scheme, path)), line, column, .. }) => {
                let uri = json!({ "$mid": 1, "scheme": scheme, "path": path });
                let range = json!({ "startLineNumber": line, "startColumn": column, "endLineNumber": line, "endColumn": column });
                (MenuId::DebugCallStackToolbar, self.key_context(window), vec![json!({ "uri": uri, "range": range })])
            }
            Some(_) => return Vec::new(),
        };
        let mut actions = Vec::new();
        for action in menu_actions(&self.menus, menu, &context) {
            if let MenuAction::Command { id, title, .. } = action {
                actions.push((id, title, args.clone()));
            }
        }
        actions
    }

    /// The subject: a diffable message in its diff editor, a plain text one in its code editor, else a task's or a
    /// test's output as plain lines; a message with testResultsViewContent.ts `populateFloatingClick`'s button.
    fn results_subject_view(&mut self, window: &mut Window, cx: &mut Context<Self>) -> gpui::Stateful<Div> {
        if let Some(editor) = self.message_editor() {
            let body = div().flex_1().min_h_0().flex().flex_col();
            // A focused frame's code editor is the active one; the message then draws as an unfocused code editor.
            let body = match self.editors.active_diff() {
                Some(diff) => body.child(self.diff_editor_body(diff, diff.modified_editor.as_ref().unwrap_or(editor), window, cx)),
                None => body.child(self.embedded_code_editor(editor, window, cx)),
            };
            let floating = self.results_floating_button(window, cx);
            return div().id("test-results-output").flex_1().min_w_0().relative().flex().flex_col().child(body).children(floating);
        }
        if let Some(output) = self.terminal_output() {
            let id = self.write_results_terminal(output);
            let pane = self.terminal_pane(id, false, self.color("panel.border"), cx);
            // callStackWidget.ts hosts the terminal in a list row, so the pane's list row inset applies.
            return div().id("test-results-output").flex_1().min_w_0().relative().flex().px(px(self.pane_row_inset())).child(pane).children(self.results_floating_button(window, cx));
        }
        if let Some(markdown) = self.markdown_message() {
            let blocks = crate::markdown::parse(&markdown);
            // `line-height: normal` of the 13px system font.
            let style = MarkdownStyle { font_size: 13., line_height: 15., foreground: self.color("foreground"), action_handler: None, code_foreground: None, code_background: None, selectable: true };
            // testing.css `.preview-text`: 8px 12px 8px 20px of padding; paragraphs 1em apart, none at the ends.
            let text = self.selectable_markdown_blocks("test-results-markdown", &blocks, style, cx).gap(px(13.)).pt(px(8.)).pr(px(12.)).pb(px(8.)).pl(px(20.));
            let output = div().id("test-results-output").px(px(self.pane_row_inset())).child(text);
            return self.scrollable("test-results-output", None, output, cx).flex_1().children(self.results_floating_button(window, cx));
        }
        let content = div().id("test-results-output").p(px(8.)).font_family("Menlo").text_size(px(12.)).flex().flex_col();
        let text = self.testing_view.results_subject.as_ref().and_then(|subject| self.subject_text(subject));
        let lines = super::debug_console::strip_ansi(&text.unwrap_or_default()).lines().map(|line| div().whitespace_nowrap().child(line.to_owned())).collect::<Vec<_>>();
        self.scrollable("test-results-output", None, content.children(lines), cx).flex_1().children(self.results_floating_button(window, cx))
    }

    pub(super) fn subject_text(&self, subject: &InspectSubject) -> Option<String> {
        match subject {
            InspectSubject::Task { result, task } => self.result_by_id(result).and_then(|result| result.tasks.get(*task)).map(|task| task.output.clone()),
            InspectSubject::Output { result, task, test } => self.result_by_id(result).and_then(|result| result.items.get(test)).map(|item| {
                item.tasks[*task].messages.iter().filter(|message| !is_error_message(message)).map(message_text).collect::<String>()
            }),
            InspectSubject::Message { result, task, test, message } => self.result_by_id(result).map(|result| message_text(&result.items[test].tasks[*task].messages[*message]).to_owned()),
        }
    }

    /// floatingMenu.ts `FloatingClickMenu` of `MenuId.TestMessageContent`: its first item as a button at the
    /// message's bottom right (testing.css `.floating-click-widget`), run with `getMessageArgs`.
    pub(super) fn results_floating_action(&self, window: &Window) -> Option<(String, String, Value)> {
        let Some(InspectSubject::Message { result, task, test, message }) = &self.testing_view.results_subject else { return None };
        let element = ResultsElement::Message { result: result.clone(), task: *task, test: test.clone(), message: *message };
        let item = &self.result_by_id(result)?.items[test];
        let value = &item.tasks[*task].messages[*message];
        let mut context: HashMap<String, Value> = self.key_context(window);
        context.insert("testMessage".into(), json!(value["contextValue"].as_str().unwrap_or_default()));
        context.insert("testResultOutdated".into(), json!(item.retired));
        let first = menu_actions(&self.menus, MenuId::TestMessageContent, &context).into_iter().find_map(|action| match action {
            MenuAction::Command { id, title, .. } => Some((id, title)),
            _ => None,
        })?;
        Some((first.0, first.1, self.message_args(&element)))
    }

    fn results_floating_button(&self, window: &Window, cx: &mut Context<Self>) -> Option<gpui::Stateful<Div>> {
        let (command, title, arg) = self.results_floating_action(window)?;
        let background = self.theme.color("button.background").unwrap_or(self.color("editor.background"));
        let foreground = self.theme.color("button.foreground").unwrap_or(self.color("editor.foreground"));
        let mut button = div()
            .id("test-message-floating-click")
            .absolute()
            .right(px(20.))
            .bottom(px(10.))
            .px(px(11.))
            .py(px(6.))
            .rounded(px(2.))
            .cursor_pointer()
            .bg(background)
            .text_color(foreground)
            .text_size(px(13.))
            .child(title)
            .on_click(cx.listener(move |workbench, _: &ClickEvent, window, cx| {
                drop(workbench.execute_command(&command, vec![arg.clone()], window, cx));
            }));
        if let Some(border) = self.theme.color("contrastBorder") {
            button = button.border_1().border_color(border);
        }
        Some(button)
    }
}

#[cfg(test)]
mod tests;