Skip to content

Visual Studio Code, rebuilt in Rust

Rust
127 KB
Raw Blame
//! The debug service of the workbench: debugService.ts (start, stop, focus, breakpoints sent to sessions),
//! debugSession.ts and rawDebugSession.ts (the protocol with one adapter), debugConfigurationManager.ts (launch
//! configurations, configuration providers) and mainThreadDebugService.ts (the extension host's side). Every debug
//! adapter runs in the extension host (`ExtHostDebugService`), as on desktop: inline, executable and server adapters
//! alike reach this file as `$acceptDAMessage`.

use std::collections::{HashMap, HashSet};
use std::path::PathBuf;

use exthost::session::ForwardedRequest;
use futures::channel::oneshot;
use gpui::{AsyncWindowContext, Context, WeakEntity, Window};
use serde_json::{Map, Value, json};

use super::Workbench;
use super::debug_task_runner::{DebugTasks, run_debug_tasks, run_task, run_task_and_check_errors};
use crate::commands::{Outcome, error_value};
use crate::debug::configuration::{self, Debugger, Launch};
use crate::debug::session::{self, ReplElement, Session, Severity, StackFrame, State, Variable};
use crate::debug::{BreakpointData, BreakpointsChange, DataBreakpoint, DebugModel};
use crate::main_thread_quick_open::Owner;
use crate::quick_input::{Entry, Event, Item, Kind, QuickInput};

type Reply = oneshot::Receiver<Result<Value, Value>>;

/// The DAP `disconnect` request's `terminateDebuggee` and `suspendDebuggee`.
#[derive(Clone, Copy, PartialEq)]
enum Debuggee {
    Terminate,
    Keep,
    Suspend,
}

/// debugStorage.ts `DEBUG_CHOSEN_ENVIRONMENTS_KEY`, and debugConfigurationManager.ts's selected launch.
const CHOSEN_ENVIRONMENTS_KEY: &str = "debug.chosenenvironment";
const SELECTED_CONFIG_KEY: &str = "debug.selectedconfigname";
const SELECTED_ROOT_KEY: &str = "debug.selectedroot";
const SELECTED_TYPE_KEY: &str = "debug.selectedtype";
/// `debug_pick`'s answer for an item's button: this prefix, then the item's handle.
pub(super) const BUTTON_ANSWER: &str = "button:";

/// A `$registerDebugConfigurationProvider` registration.
#[derive(Clone, Debug)]
pub struct ConfigurationProvider {
    pub handle: i64,
    pub debug_type: String,
    /// `DebugConfigurationProviderTriggerKind`: 1 initial, 2 dynamic.
    pub trigger_kind: i64,
    pub has_provide: bool,
    pub has_resolve: bool,
    pub has_resolve2: bool,
}

/// Whether a focus change opens the frame, and with `focusStackFrame`'s `preserveFocus` or without it.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Reveal {
    No,
    PreservingFocus,
    TakingFocus,
}

/// The focus of debugViewModel.ts: a session, a thread of it and a frame of that thread.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct DebugFocus {
    pub session: Option<String>,
    pub thread: Option<i64>,
    pub frame: Option<i64>,
}

#[derive(Default)]
pub struct DebugService {
    pub model: DebugModel,
    pub debuggers: Vec<Debugger>,
    /// The types whose adapters the extension host creates (`$registerDebugTypes`).
    pub adapter_types: Vec<String>,
    pub providers: Vec<ConfigurationProvider>,
    pub sessions: Vec<Session>,
    /// Ended sessions debugModel.ts keeps (`State.Inactive`) until a session of the same configuration starts.
    pub inactive_sessions: Vec<Session>,
    next_handle: u32,
    pub focus: DebugFocus,
    /// The scopes of the focused frame, then each expanded row's children by `(session, variablesReference)`.
    pub scopes: Vec<Variable>,
    pub children: HashMap<(String, i64), Vec<Variable>>,
    pub visualizers: super::debug_visualizers::DebugVisualizers,
    pub inline_breakpoints: super::inline_breakpoints::InlineBreakpoints,
    /// Watch expression results by expression id.
    pub watch_values: HashMap<String, Variable>,
    /// The `vscode-debug-memory` resources opened, which `debug_memory_session_changed` reports to the extension host.
    pub memory_resources: Vec<Value>,
    pub repl: Vec<ReplElement>,
    /// Sessions the extension host caches (`$sessionCached`): their DTO is the id alone.
    known_sessions: HashSet<String>,
    /// `debugService.initializing`: a start is resolving its configuration.
    pub initializing: bool,
    /// `viewModel.firstSessionStart`.
    pub first_session_started: bool,
    /// debugViewModel.ts `multiSessionDebug`: set once a start leaves more than one toolbar session, cleared when none is left.
    pub multi_session_view: bool,
    /// `chosenEnvironments`: the debugger picked for a file without a launch configuration.
    chosen_environments: Map<String, Value>,
    /// debugAdapterManager.ts `earlyActivatedExtensions`: the extensions active before the first debugger activation.
    early_activated: Option<HashSet<String>>,
    /// debugAdapterManager.ts `usedDebugTypes`: the types of the sessions started.
    used_debug_types: HashSet<String>,
    /// The launch configuration the Run and Debug view's dropdown selects: its folder and name.
    pub selected: Option<(Option<PathBuf>, String)>,
    /// debugConfigurationManager.ts `selectedType` of a dynamic selection: its provider's type.
    pub selected_type: Option<String>,
    /// breakpointsView.ts `hintContainer`: the unverified breakpoints message the Breakpoints header shows.
    pub breakpoints_hint: Option<String>,
    /// breakpointsView.ts `hintDelayer`, pending.
    pub breakpoints_hint_delay: Option<gpui::Task<()>>,
    /// debugTaskRunner.ts `globalCancellation`: each task run a start waits for.
    pub(super) task_cancels: Vec<oneshot::Sender<()>>,
}

impl DebugService {
    /// debugAdapterManager.ts `initExtensionActivationsIfNeeded`, run before the first debugger activation.
    pub(super) fn init_extension_activations(&mut self) {
        if self.early_activated.is_none() {
            self.early_activated = Some(self.debuggers.iter().map(|debugger| debugger.extension_id.clone()).filter(|id| crate::perf::activation(id).is_some()).collect());
        }
    }

    pub fn session(&self, id: &str) -> Option<&Session> {
        self.sessions.iter().find(|session| session.id == id)
    }

    /// `getSessions(true)` in start order.
    pub fn sessions_including_inactive(&self) -> Vec<&Session> {
        let mut sessions: Vec<&Session> = self.sessions.iter().chain(&self.inactive_sessions).collect();
        sessions.sort_by_key(|session| session.handle);
        sessions
    }

    /// debugModel.ts `addSession`: drops the inactive sessions `shouldDisposeSession` names, with their console output.
    pub(super) fn add_session(&mut self, session: Session) {
        let disposed: Vec<String> = self.inactive_sessions.iter().filter(|inactive| self.should_dispose_session(inactive, &session)).map(|inactive| inactive.id.clone()).collect();
        self.inactive_sessions.retain(|inactive| !disposed.contains(&inactive.id));
        self.repl.retain(|element| !disposed.iter().any(|id| id == super::debug_console::repl_element_session(element)));
        if let Some(debug_type) = session.configuration["type"].as_str() {
            self.used_debug_types.insert(debug_type.to_owned());
        }
        self.sessions.push(session);
    }

    fn should_dispose_session(&self, inactive: &Session, new: &Session) -> bool {
        let name = &new.configuration["name"];
        if &inactive.configuration["name"] == name {
            return true;
        }
        if new.parent.is_some() {
            return false;
        }
        let mut root = inactive;
        while let Some(parent) = root.parent.as_deref().and_then(|id| self.sessions_including_inactive().into_iter().find(|session| session.id == id)) {
            root = parent;
        }
        self.inactive_sessions.iter().any(|session| session.id == root.id) && &root.configuration["name"] == name
    }

    pub fn session_mut(&mut self, id: &str) -> Option<&mut Session> {
        self.sessions.iter_mut().find(|session| session.id == id)
    }

    fn session_by_handle(&self, handle: u32) -> Option<&Session> {
        self.sessions.iter().find(|session| session.handle == handle)
    }

    pub fn focused_session(&self) -> Option<&Session> {
        self.focus.session.as_deref().and_then(|id| self.session(id))
    }

    pub fn focused_frame(&self) -> Option<&StackFrame> {
        let session = self.focused_session()?;
        let thread = session.thread(self.focus.thread?)?;
        thread.frames.iter().find(|frame| Some(frame.id) == self.focus.frame)
    }

    /// debugService.ts `state`: the focused session's, else initializing while a start resolves.
    pub fn state(&self) -> State {
        if let Some(session) = self.focused_session() {
            return session.state(self.focus.thread);
        }
        if self.initializing || self.sessions.iter().any(|session| session.state(None) == State::Initializing) {
            return State::Initializing;
        }
        State::Inactive
    }

    /// `getSessionDto`: the id alone once the host cached the session.
    fn session_dto(&self, session: &Session) -> Value {
        match self.known_sessions.contains(&session.id) {
            true => json!(session.id),
            false => session.dto(),
        }
    }

    pub fn debugger(&self, debug_type: &str) -> Option<&Debugger> {
        self.debuggers.iter().find(|debugger| debugger.debug_type == debug_type)
    }

    /// debugViewModel.ts `getStackFrameThreadAndSessionToFocus`: the first stopped thread's top frame with a source.
    pub(super) fn focus_target(&self, session_id: Option<&str>, thread_id: Option<i64>) -> DebugFocus {
        let session = session_id.and_then(|id| self.session(id)).or_else(|| self.sessions.iter().find(|session| session.state(None) == State::Stopped)).or(self.sessions.first());
        let Some(session) = session else { return DebugFocus::default() };
        let thread = thread_id.and_then(|id| session.thread(id)).or_else(|| session.threads.iter().find(|thread| thread.stopped)).or(session.threads.first());
        let Some(thread) = thread else { return DebugFocus { session: Some(session.id.clone()), ..Default::default() } };
        let frame = thread.frames.iter().find(|frame| frame.path().is_some() && !frame.deemphasized()).or(thread.frames.first());
        DebugFocus { session: Some(session.id.clone()), thread: Some(thread.id), frame: frame.map(|frame| frame.id) }
    }
}

/// The message of an error the host or an adapter answered.
fn error_message(error: &Value) -> String {
    error["message"].as_str().map(str::to_owned).unwrap_or_else(|| error.to_string())
}

pub(super) async fn answer(reply: Reply) -> Result<Value, String> {
    match reply.await {
        Ok(Ok(value)) => Ok(value),
        Ok(Err(error)) => Err(error_message(&error)),
        Err(_) => Err("Canceled".into()),
    }
}

/// debugModel.ts `evaluateLazy`: a lazy variable's `variables` request answers with the one variable it stands for;
/// any other answer leaves it as it was.
pub(super) async fn evaluate_lazy(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, session_id: &str, variable: &mut Variable) {
    let Ok(reply) = on_workbench(this, cx, |workbench, _, _| workbench.dap_request(session_id, "variables", json!({ "variablesReference": variable.variables_reference }))) else { return };
    let body = answer(reply).await.unwrap_or_default();
    if let Some([resolved]) = body["variables"].as_array().map(Vec::as_slice) {
        variable.adopt_lazy(resolved);
    }
}

/// An async step on the workbench; a closed window ends the flow.
pub(super) fn on_workbench<R>(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, step: impl FnOnce(&mut Workbench, &mut Window, &mut Context<Workbench>) -> R) -> Result<R, String> {
    this.update_in(cx, step).map_err(|_| "Canceled".to_owned())
}

impl Workbench {
    /// MainThreadDebugService's methods.
    pub(crate) fn handle_debug_request(&mut self, request: ForwardedRequest, window: &mut Window, cx: &mut Context<Self>) -> Outcome {
        let args = request.args;
        let arg = |index: usize| args.get(index).cloned().unwrap_or(Value::Null);
        match request.method.as_str() {
            "$registerDebugTypes" => {
                self.debug.adapter_types = arg(0).as_array().into_iter().flatten().filter_map(|value| value.as_str().map(str::to_owned)).collect();
                self.debug.debuggers = configuration::debuggers(&self.extensions);
            }
            "$sessionCached" => _ = self.debug.known_sessions.insert(arg(0).as_str().unwrap_or_default().to_owned()),
            "$acceptDAMessage" => self.accept_adapter_message(arg(0).as_u64().unwrap_or_default() as u32, &session::from_adapter_paths(&arg(1)), window, cx),
            "$acceptDAError" => {
                let handle = arg(0).as_u64().unwrap_or_default() as u32;
                let message = arg(2).as_str().unwrap_or_default().to_owned();
                self.adapter_exited(handle, Some(message), window, cx);
            }
            "$acceptDAExit" => self.adapter_exited(arg(0).as_u64().unwrap_or_default() as u32, None, window, cx),
            "$registerDebugConfigurationProvider" => self.debug.providers.push(ConfigurationProvider {
                debug_type: arg(0).as_str().unwrap_or_default().to_owned(),
                trigger_kind: arg(1).as_i64().unwrap_or_default(),
                has_provide: arg(2) == true,
                has_resolve: arg(3) == true,
                has_resolve2: arg(4) == true,
                handle: arg(5).as_i64().unwrap_or_default(),
            }),
            "$unregisterDebugConfigurationProvider" => self.debug.providers.retain(|provider| Some(provider.handle) != arg(0).as_i64()),
            "$registerDebugAdapterDescriptorFactory" | "$unregisterDebugAdapterDescriptorFactory" => {}
            "$startDebugging" => {
                let folder = crate::debug::configuration_folder(&arg(0));
                let mut options = arg(2);
                // mainThreadDebugService.ts: the host's options carry the parent's id, the session wants the parent.
                if options.is_null() {
                    options = json!({});
                }
                return Outcome::Pending(self.start_debugging(folder, arg(1), options, DebugTasks::PreLaunch, window, cx));
            }
            "$stopDebugging" => return Outcome::Pending(self.stop_session(arg(0).as_str().map(str::to_owned), false, false, window, cx)),
            "$setDebugSessionName" => {
                let id = arg(0).as_str().unwrap_or_default().to_owned();
                let name = arg(1).as_str().unwrap_or_default().to_owned();
                if let Some(session) = self.debug.session_mut(&id) {
                    session.name = name.clone();
                    let dto = session.dto();
                    self.host.send("ExtHostDebugService", "$acceptDebugSessionNameChanged", vec![dto, json!(name)]);
                    cx.notify();
                }
            }
            "$customDebugAdapterRequest" => {
                let id = arg(0).as_str().unwrap_or_default().to_owned();
                if self.debug.session(&id).is_none() {
                    return Outcome::error("debug session not found");
                }
                return Outcome::Pending(self.dap_request(&id, arg(1).as_str().unwrap_or_default(), arg(2)));
            }
            "$getDebugProtocolBreakpoint" => {
                let (session, id) = (arg(0).as_str().unwrap_or_default().to_owned(), arg(1).as_str().unwrap_or_default().to_owned());
                let model = &self.debug.model;
                let bases = model.breakpoints.iter().map(|breakpoint| &breakpoint.base).chain(model.function_breakpoints.iter().map(|breakpoint| &breakpoint.base));
                let found = bases.chain(model.data_breakpoints.iter().map(|breakpoint| &breakpoint.base)).find(|base| base.id == id).and_then(|base| base.debug_protocol_breakpoint(&session));
                return Outcome::Ready(Ok(found.unwrap_or(Value::Null)));
            }
            "$appendDebugConsole" => {
                let session_id = self.debug.focus.session.clone().unwrap_or_default();
                self.append_to_repl(&session_id, arg(0).as_str().unwrap_or_default(), Severity::Info, None, cx);
            }
            "$registerBreakpoints" => self.register_host_breakpoints(arg(0).as_array().map_or(&[], Vec::as_slice), cx),
            "$unregisterBreakpoints" => {
                let ids = |index: usize| -> Vec<String> { arg(index).as_array().into_iter().flatten().filter_map(|id| id.as_str().map(str::to_owned)).collect() };
                let mut change = self.debug.model.remove_breakpoints(&ids(0));
                for id in ids(1) {
                    change.removed.extend(self.debug.model.remove_function_breakpoints(Some(&id)).removed);
                }
                for id in ids(2) {
                    change.removed.extend(self.debug.model.remove_data_breakpoints(Some(&id)).removed);
                }
                self.breakpoints_changed(change, true, cx);
            }
            "$registerDebugVisualizer" | "$unregisterDebugVisualizer" | "$registerDebugVisualizerTree" | "$unregisterDebugVisualizerTree" => self.handle_visualizer_request(&request.method, &args),
            _ => {}
        }
        Outcome::done()
    }

    /// `$registerBreakpoints`: source breakpoints by resource, function and data breakpoints.
    fn register_host_breakpoints(&mut self, dtos: &[Value], cx: &mut Context<Self>) {
        let mut change = BreakpointsChange::default();
        let text = |value: &Value, key: &str| value[key].as_str().map(str::to_owned);
        for dto in dtos {
            match dto["type"].as_str() {
                Some("sourceMulti") => {
                    let data = dto["lines"]
                        .as_array()
                        .into_iter()
                        .flatten()
                        .map(|line| BreakpointData {
                            id: text(line, "id"),
                            line: line["line"].as_u64().unwrap_or_default() as u32 + 1,
                            column: line["character"].as_u64().filter(|character| *character > 0).map(|character| character as u32 + 1),
                            enabled: line["enabled"] != false,
                            condition: text(line, "condition"),
                            hit_condition: text(line, "hitCondition"),
                            log_message: text(line, "logMessage"),
                            mode: text(line, "mode"),
                            mode_label: None,
                            triggered_by: None,
                        })
                        .collect();
                    change.added.extend(self.debug.model.add_breakpoints(&dto["uri"], data).added);
                }
                Some("function") => {
                    let options = json!({ "enabled": dto["enabled"], "condition": dto["condition"], "hitCondition": dto["hitCondition"], "logMessage": dto["logMessage"], "mode": dto["mode"] });
                    change.added.extend(self.debug.model.add_function_breakpoint(dto["functionName"].as_str().unwrap_or_default(), &options, text(dto, "id")).added);
                }
                Some("data") => {
                    let options = json!({ "enabled": dto["enabled"], "condition": dto["condition"], "hitCondition": dto["hitCondition"], "logMessage": dto["logMessage"] });
                    let breakpoint = DataBreakpoint {
                        base: crate::debug::base_breakpoint(text(dto, "id").unwrap_or_else(crate::debug::generate_uuid), &options),
                        description: text(dto, "label").unwrap_or_default(),
                        data_id: text(dto, "dataId").unwrap_or_default(),
                        can_persist: dto["canPersist"] == true,
                        access_type: text(dto, "accessType").unwrap_or_else(|| "write".into()),
                        access_types: None,
                    };
                    change.added.extend(self.debug.model.add_data_breakpoint(breakpoint).added);
                }
                _ => {}
            }
        }
        // The host already knows these breakpoints; it ignores the delta of ids it has.
        self.breakpoints_changed(change, true, cx);
    }

    /// The model changed: storage, the extension host (unless only sessions changed) and the sessions.
    pub(crate) fn breakpoints_changed(&mut self, change: BreakpointsChange, send_to_sessions: bool, cx: &mut Context<Self>) {
        self.store_debug_model();
        if !change.session_only && !change.is_empty() {
            let mut delta = Map::new();
            if !change.added.is_empty() {
                delta.insert("added".into(), json!(self.debug.model.dtos(&change.added)));
            }
            if !change.removed.is_empty() {
                delta.insert("removed".into(), json!(change.removed));
            }
            if !change.changed.is_empty() {
                delta.insert("changed".into(), json!(self.debug.model.dtos(&change.changed)));
            }
            self.host.send("ExtHostDebugService", "$acceptBreakpointsDelta", vec![Value::Object(delta)]);
        }
        if send_to_sessions && !change.session_only {
            let ids: Vec<String> = self.debug.sessions.iter().map(|session| session.id.clone()).collect();
            for id in ids {
                self.send_all_breakpoints(&id, cx);
            }
        }
        self.update_breakpoints_hint(cx);
        cx.notify();
    }

    /// debugStorage.ts `storeBreakpoints` and `storeWatchExpressions`.
    pub(crate) fn store_debug_model(&mut self) {
        let mut storage = self.workspace_storage.lock().unwrap();
        for (key, value) in self.debug.model.storage_entries() {
            match value {
                Some(value) => storage.set(key, value),
                None => storage.delete(key),
            }
        }
    }

    /// DebugStorage's load with the workspace state; the host hears of the stored breakpoints
    /// (mainThreadDebugService.ts `sendBreakpointsAndListen`).
    pub(crate) fn restore_debug_state(&mut self) {
        let storage = self.workspace_storage.lock().unwrap();
        self.debug.model = DebugModel::from_storage(|key| storage.get(key).map(str::to_owned));
        self.debug.chosen_environments = storage.get(CHOSEN_ENVIRONMENTS_KEY).and_then(|raw| serde_json::from_str(raw).ok()).unwrap_or_default();
        let name = storage.get(SELECTED_CONFIG_KEY).map(str::to_owned);
        let root = storage.get(SELECTED_ROOT_KEY).and_then(crate::editor_history::file_path);
        self.debug.selected_type = storage.get(SELECTED_TYPE_KEY).map(str::to_owned);
        drop(storage);
        self.debug.selected = name.map(|name| (root, name));
        let ids = self.debug.model.all_ids();
        if !ids.is_empty() {
            self.host.send("ExtHostDebugService", "$acceptBreakpointsDelta", vec![json!({ "added": self.debug.model.dtos(&ids) })]);
        }
        self.update_debug_status();
    }

    pub(crate) fn store_selected_configuration(&mut self) {
        let mut storage = self.workspace_storage.lock().unwrap();
        match &self.debug.selected {
            Some((root, name)) => {
                storage.set(SELECTED_CONFIG_KEY, name.clone());
                match root {
                    Some(root) => storage.set(SELECTED_ROOT_KEY, crate::editor_history::file_uri_string(root)),
                    None => storage.delete(SELECTED_ROOT_KEY),
                }
            }
            None => {
                storage.delete(SELECTED_CONFIG_KEY);
                storage.delete(SELECTED_ROOT_KEY);
            }
        }
        match &self.debug.selected_type {
            Some(debug_type) => storage.set(SELECTED_TYPE_KEY, debug_type.clone()),
            None => storage.delete(SELECTED_TYPE_KEY),
        }
        drop(storage);
        self.update_debug_status();
    }

    /// The launch.json of a workspace folder (`Launch.getConfig`: the folder's value of the `launch` setting).
    pub(crate) fn folder_launch(&self, folder: &std::path::Path) -> Launch {
        let settings = self.settings.lock().unwrap();
        let overrides = config::configuration::Overrides { resource: Some(folder), override_identifier: None };
        let inspected = settings.configuration.inspect("launch", &overrides);
        Launch::from_section(inspected.workspace_folder.value.or(inspected.workspace.value).as_ref())
    }

    pub(crate) fn workspace_folders(&self) -> Vec<PathBuf> {
        self.workspace().map(|workspace| workspace.folders.iter().map(|folder| folder.path.clone()).collect()).unwrap_or_default()
    }

    /// rawDebugSession.ts `send`: a request to the session's adapter; the answer is its body or the adapter's error.
    pub(crate) fn dap_request(&mut self, session_id: &str, command: &str, arguments: Value) -> Reply {
        let (sender, receiver) = oneshot::channel();
        let Some(session) = self.debug.session_mut(session_id).filter(|session| !session.exited) else {
            let _ = sender.send(Err(json!({ "message": format!("No debugger available, can not send '{command}'") })));
            return receiver;
        };
        let message = session.request(command, arguments, sender);
        let handle = session.handle;
        self.host.send("ExtHostDebugService", "$sendDAMessage", vec![json!(handle), session::to_adapter_paths(&message)]);
        receiver
    }

    fn send_response(&mut self, session_id: &str, request: &Value, result: Result<Value, String>) {
        let Some(session) = self.debug.session_mut(session_id) else { return };
        let mut response = json!({ "type": "response", "seq": 0, "command": request["command"], "request_seq": request["seq"], "success": result.is_ok() });
        match result {
            Ok(body) if !body.is_null() => response["body"] = body,
            Ok(_) => {}
            Err(message) => response["message"] = json!(message),
        }
        let handle = session.handle;
        let response = session.number(response);
        self.host.send("ExtHostDebugService", "$sendDAMessage", vec![json!(handle), response]);
    }

    /// One message of an adapter: a response, an event, or a reverse request.
    fn accept_adapter_message(&mut self, handle: u32, message: &Value, window: &mut Window, cx: &mut Context<Self>) {
        let Some(session_id) = self.debug.session_by_handle(handle).map(|session| session.id.clone()) else { return };
        match message["type"].as_str() {
            Some("response") => {
                if let Some(session) = self.debug.session_mut(&session_id) {
                    session.accept_response(message);
                }
            }
            Some("event") => self.accept_adapter_event(&session_id, message, window, cx),
            Some("request") => self.accept_reverse_request(&session_id, message, window, cx),
            _ => {}
        }
    }

    /// rawDebugSession.ts `dispatchRequest`: `runInTerminal` goes to the host, `startDebugging` starts a child.
    fn accept_reverse_request(&mut self, session_id: &str, request: &Value, window: &mut Window, cx: &mut Context<Self>) {
        let arguments = request["arguments"].clone();
        let answer_with = |reply: Reply, session_id: String, request: Value, body: fn(Value) -> Result<Value, String>, window: &mut Window, cx: &mut Context<Self>| {
            cx.spawn_in(window, async move |this, cx| {
                let result = answer(reply).await.and_then(body);
                let _ = on_workbench(&this, cx, |workbench, _, _| workbench.send_response(&session_id, &request, result));
            })
            .detach();
        };
        match request["command"].as_str() {
            Some("runInTerminal") => {
                let reply = self.host.call("ExtHostDebugService", "$runInTerminal", vec![arguments, json!(session_id)]);
                answer_with(reply, session_id.to_owned(), request.clone(), |pid| Ok(if pid.is_number() { json!({ "shellProcessId": pid }) } else { json!({}) }), window, cx);
            }
            Some("startDebugging") => {
                let Some(session) = self.debug.session(session_id) else { return };
                let mut configuration = arguments["configuration"].clone();
                configuration["request"] = arguments["request"].clone();
                configuration["type"] = json!(session.session_type());
                if configuration["name"].as_str().is_none() {
                    configuration["name"] = json!(session.name);
                }
                let folder = session.folder_uri.as_ref().and_then(crate::debug::configuration_folder);
                let reply = self.start_debugging(folder, configuration, json!({ "parentSessionID": session_id }), DebugTasks::PreLaunch, window, cx);
                answer_with(reply, session_id.to_owned(), request.clone(), |started| if started == true { Ok(Value::Null) } else { Err("Failed to start debugging".into()) }, window, cx);
            }
            Some("launchVSCode") => {
                let opened = super::host::open_extension_development_host_window(&launch_vs_code_args(&arguments), cx);
                self.send_response(session_id, request, opened.map(|()| json!({})).map_err(|error| format!("{error:#}")));
            }
            _ => self.send_response(session_id, request, Err(format!("Unknown request '{}'", request["command"].as_str().unwrap_or_default()))),
        }
    }

    /// rawDebugSession.ts's event switch with debugSession.ts's listeners.
    fn accept_adapter_event(&mut self, session_id: &str, event: &Value, window: &mut Window, cx: &mut Context<Self>) {
        let body = &event["body"];
        match event["event"].as_str().unwrap_or_default() {
            // An `initialized` event in the same batch as the initialize response waits for the launch request, which
            // upstream sends in the response's continuation, before any other message.
            "initialized" => match self.debug.session_mut(session_id) {
                Some(session) if !session.initialized => session.initialized_event_pending = true,
                _ => self.session_initialized(session_id.to_owned(), window, cx),
            },
            "stopped" => self.session_stopped(session_id.to_owned(), body.clone(), window, cx),
            "continued" => {
                let thread = if body["allThreadsContinued"] == false { body["threadId"].as_i64() } else { None };
                self.threads_continued(session_id, thread, cx);
            }
            "thread" => match body["reason"].as_str() {
                Some("exited") => {
                    if let Some(session) = self.debug.session_mut(session_id) {
                        session.threads.retain(|thread| Some(thread.id) != body["threadId"].as_i64());
                    }
                    cx.notify();
                }
                _ => self.fetch_threads(session_id.to_owned(), window, cx),
            },
            "output" => self.accept_output_event(session_id, body, cx),
            "breakpoint" => self.accept_breakpoint_event(session_id, body, cx),
            "terminated" => {
                if !body["restart"].is_null() && body["restart"] != false {
                    drop(self.restart_session(session_id.to_owned(), Some(body["restart"].clone()), window, cx));
                } else {
                    // debugSession.ts `onDidTerminateDebugee`: the session disconnects itself, whoever manages its lifecycle.
                    drop(self.raw_disconnect(session_id.to_owned(), false, Debuggee::Keep, window, cx));
                }
            }
            "loadedSource" => {
                if let Some(session) = self.debug.session_mut(session_id) {
                    session.accept_loaded_source(body);
                }
                cx.notify();
            }
            "capabilities" => {
                if let (Some(session), Some(capabilities)) = (self.debug.session_mut(session_id), body["capabilities"].as_object()) {
                    for (key, value) in capabilities {
                        session.capabilities[key] = value.clone();
                    }
                }
                cx.notify();
            }
            "invalidated" => self.refresh_focus(window, cx),
            "memory" => self.debug_memory_session_changed(session_id, body["memoryReference"].as_str()),
            "exited" | "progressStart" | "progressUpdate" | "progressEnd" | "process" | "module" => {}
            _ => {
                let Some(session) = self.debug.session(session_id) else { return };
                let dto = self.debug.session_dto(session);
                self.host.send("ExtHostDebugService", "$acceptDebugSessionCustomEvent", vec![dto, event.clone()]);
            }
        }
    }

    /// debugSession.ts `onDidInitialize`: breakpoints, then `configurationDone`, then the threads.
    fn session_initialized(&mut self, session_id: String, window: &mut Window, cx: &mut Context<Self>) {
        let sent = self.send_all_breakpoints(&session_id, cx);
        cx.spawn_in(window, async move |this, cx| {
            for reply in sent {
                let _ = reply.await;
            }
            let supports = on_workbench(&this, cx, |workbench, _, _| workbench.debug.session(&session_id).is_some_and(|session| session.capabilities["supportsConfigurationDoneRequest"] == true));
            if supports == Ok(true) {
                let reply = on_workbench(&this, cx, |workbench, _, _| workbench.dap_request(&session_id, "configurationDone", Value::Null));
                if let Ok(reply) = reply
                    && let Err(error) = answer(reply).await
                {
                    let _ = on_workbench(&this, cx, |workbench, _, cx| workbench.append_to_repl(&session_id, &error, Severity::Error, None, cx));
                }
            }
            let _ = on_workbench(&this, cx, |workbench, _, cx| workbench.debug.session_mut(&session_id).map(|session| session.configuration_done = true).map(|_| cx.notify()));
            let _ = on_workbench(&this, cx, |workbench, window, cx| workbench.fetch_threads(session_id.clone(), window, cx));
        })
        .detach();
    }

    /// debugService.ts `sendAllBreakpoints` for one session: sources per file, then functions, data and exceptions.
    pub(crate) fn send_all_breakpoints(&mut self, session_id: &str, cx: &mut Context<Self>) -> Vec<Reply> {
        let Some(session) = self.debug.session(session_id) else { return Vec::new() };
        if session.no_debug() || !session.initialized {
            return Vec::new();
        }
        let capabilities = session.capabilities.clone();
        let activated = self.debug.model.breakpoints_activated;
        let mut uris: Vec<String> = Vec::new();
        for breakpoint in &self.debug.model.breakpoints {
            if !uris.contains(&breakpoint.uri_string()) {
                uris.push(breakpoint.uri_string());
            }
        }
        let mut replies = Vec::new();
        for uri in uris {
            replies.push(self.send_breakpoints(session_id, &uri, false, cx));
        }
        if capabilities["supportsFunctionBreakpoints"] == true {
            let breakpoints: Vec<Value> = self.debug.model.function_breakpoints.iter().filter(|breakpoint| breakpoint.base.enabled && activated).map(|breakpoint| breakpoint.to_dap()).collect();
            let ids: Vec<String> = self.debug.model.function_breakpoints.iter().filter(|breakpoint| breakpoint.base.enabled && activated).map(|breakpoint| breakpoint.base.id.clone()).collect();
            replies.push(self.send_breakpoint_request(session_id, "setFunctionBreakpoints", json!({ "breakpoints": breakpoints }), ids, cx));
        }
        if capabilities["supportsDataBreakpoints"] == true {
            let enabled: Vec<&DataBreakpoint> = self.debug.model.data_breakpoints.iter().filter(|breakpoint| breakpoint.base.enabled && activated).collect();
            let breakpoints: Vec<Value> = enabled.iter().map(|breakpoint| json!({ "dataId": breakpoint.data_id, "accessType": breakpoint.access_type, "condition": breakpoint.base.condition, "hitCondition": breakpoint.base.hit_condition })).collect();
            let ids = enabled.iter().map(|breakpoint| breakpoint.base.id.clone()).collect();
            replies.push(self.send_breakpoint_request(session_id, "setDataBreakpoints", json!({ "breakpoints": breakpoints }), ids, cx));
        }
        if let Some(reply) = self.send_instruction_breakpoints(session_id, cx) {
            replies.push(reply);
        }
        // debugSession.ts `sendExceptionBreakpoints`: only once the adapter has filters.
        let session_filters: Vec<&crate::debug::ExceptionBreakpoint> = self.debug.model.exception_breakpoints_for(Some(session_id)).collect();
        if !session_filters.is_empty() {
            let enabled: Vec<&&crate::debug::ExceptionBreakpoint> = session_filters.iter().filter(|breakpoint| breakpoint.base.enabled && activated).collect();
            let filters: Vec<&str> = enabled.iter().filter(|breakpoint| breakpoint.base.condition.is_none()).map(|breakpoint| breakpoint.filter.as_str()).collect();
            let mut arguments = json!({ "filters": filters });
            if capabilities["supportsExceptionFilterOptions"] == true {
                let options: Vec<Value> = enabled.iter().map(|breakpoint| json!({ "filterId": breakpoint.filter, "condition": breakpoint.base.condition })).map(|mut option| {
                    crate::debug::strip_nulls(&mut option);
                    option
                }).collect();
                arguments = json!({ "filters": [], "filterOptions": options });
            }
            let ids = enabled.iter().map(|breakpoint| breakpoint.base.id.clone()).collect();
            replies.push(self.send_breakpoint_request(session_id, "setExceptionBreakpoints", arguments, ids, cx));
        }
        replies
    }

    /// debugService.ts `sendInstructionBreakpoints` to one session: none unless the adapter supports them.
    pub(crate) fn send_instruction_breakpoints(&mut self, session_id: &str, cx: &mut Context<Self>) -> Option<Reply> {
        let session = self.debug.session(session_id)?;
        if session.capabilities["supportsInstructionBreakpoints"] != true || session.no_debug() || !session.initialized {
            return None;
        }
        let activated = self.debug.model.breakpoints_activated;
        let enabled: Vec<&crate::debug::InstructionBreakpoint> = self.debug.model.instruction_breakpoints.iter().filter(|breakpoint| breakpoint.base.enabled && activated).collect();
        let breakpoints: Vec<Value> = enabled.iter().map(|breakpoint| breakpoint.to_dap()).collect();
        let ids = enabled.iter().map(|breakpoint| breakpoint.base.id.clone()).collect();
        Some(self.send_breakpoint_request(session_id, "setInstructionBreakpoints", json!({ "breakpoints": breakpoints }), ids, cx))
    }

    /// debugService.ts `addInstructionBreakpoint` and `removeInstructionBreakpoints` after the model: every
    /// session gets the instruction breakpoints again.
    pub(crate) fn instruction_breakpoints_changed(&mut self, change: BreakpointsChange, cx: &mut Context<Self>) {
        self.breakpoints_changed(change, false, cx);
        let ids: Vec<String> = self.debug.sessions.iter().map(|session| session.id.clone()).collect();
        for id in ids {
            self.send_instruction_breakpoints(&id, cx);
        }
    }

    /// debugSession.ts `sendBreakpoints`: the file's enabled breakpoints; the answer verifies them by position.
    pub(crate) fn send_breakpoints(&mut self, session_id: &str, uri: &str, source_modified: bool, cx: &mut Context<Self>) -> Reply {
        let activated = self.debug.model.breakpoints_activated;
        let breakpoints: Vec<&crate::debug::Breakpoint> = self
            .debug
            .model
            .breakpoints_in(uri)
            .filter(|breakpoint| breakpoint.base.enabled && activated)
            .filter(|breakpoint| breakpoint.triggered_by.is_none() || breakpoint.sessions_did_trigger.iter().any(|id| id == session_id))
            .collect();
        let Some(first) = self.debug.model.breakpoints_in(uri).next() else {
            let source = source_of_uri(&crate::debug::uri_from_string(uri));
            return self.send_breakpoint_request(session_id, "setBreakpoints", json!({ "source": source, "lines": [], "breakpoints": [], "sourceModified": source_modified }), Vec::new(), cx);
        };
        let mut source = source_of_uri(&first.uri);
        if let Some(adapter_data) = breakpoints.iter().map(|breakpoint| breakpoint.adapter_data()).find(|data| !data.is_null()) {
            source["adapterData"] = adapter_data.clone();
        }
        let lines: Vec<u32> = breakpoints.iter().map(|breakpoint| breakpoint.session_agnostic_line().0).collect();
        let dap: Vec<Value> = breakpoints.iter().map(|breakpoint| breakpoint.to_dap()).collect();
        let ids = breakpoints.iter().map(|breakpoint| breakpoint.id().to_owned()).collect();
        self.send_breakpoint_request(session_id, "setBreakpoints", json!({ "source": source, "lines": lines, "breakpoints": dap, "sourceModified": source_modified }), ids, cx)
    }

    /// Sends one of the `set*Breakpoints` requests; the answer's breakpoints match `ids` by position.
    fn send_breakpoint_request(&mut self, session_id: &str, command: &str, arguments: Value, ids: Vec<String>, cx: &mut Context<Self>) -> Reply {
        let reply = self.dap_request(session_id, command, arguments);
        let (sender, receiver) = oneshot::channel();
        let session_id = session_id.to_owned();
        cx.spawn(async move |this, cx| {
            let result = reply.await.unwrap_or(Err(Value::Null));
            if let Ok(body) = &result {
                let answered: Vec<(String, Value)> = ids.into_iter().zip(body["breakpoints"].as_array().cloned().unwrap_or_default()).collect();
                let _ = this.update(cx, |workbench, cx| {
                    let capabilities = workbench.debug.session(&session_id).map(|session| session.capabilities.clone()).unwrap_or_default();
                    for (id, breakpoint) in answered {
                        set_one_session_data(&mut workbench.debug.model, &session_id, &capabilities, &id, &breakpoint);
                    }
                    workbench.update_breakpoints_hint(cx);
                    cx.notify();
                });
            }
            let _ = sender.send(result);
        })
        .detach();
        receiver
    }

    /// debugSession.ts `onDidBreakpoint`: an adapter's breakpoint changed, by its adapter id.
    fn accept_breakpoint_event(&mut self, session_id: &str, body: &Value, cx: &mut Context<Self>) {
        let breakpoint = &body["breakpoint"];
        let Some(adapter_id) = breakpoint["id"].as_i64() else { return };
        let capabilities = self.debug.session(session_id).map(|session| session.capabilities.clone()).unwrap_or_default();
        let model = &mut self.debug.model;
        let bases = model.breakpoints.iter().map(|breakpoint| &breakpoint.base).chain(model.function_breakpoints.iter().map(|breakpoint| &breakpoint.base));
        let Some(id) = bases.chain(model.data_breakpoints.iter().map(|breakpoint| &breakpoint.base)).find(|base| base.id_from_adapter(session_id) == Some(adapter_id)).map(|base| base.id.clone()) else { return };
        match body["reason"].as_str() {
            Some("removed") => clear_one_session_data(model, session_id, &id),
            _ => set_one_session_data(model, session_id, &capabilities, &id, breakpoint),
        }
        self.update_breakpoints_hint(cx);
        cx.notify();
    }

    /// debugSession.ts `onDidOutput`: telemetry is dropped, `important` also shows a notification.
    fn accept_output_event(&mut self, session_id: &str, body: &Value, cx: &mut Context<Self>) {
        let category = body["category"].as_str();
        if category == Some("telemetry") {
            return;
        }
        if category == Some("important") {
            self.notify_warning(body["output"].as_str().unwrap_or_default().to_owned());
            return;
        }
        let severity = session::output_severity(category);
        let source = body["source"]["path"].as_str().map(|path| (path.to_owned(), body["line"].as_u64().unwrap_or(1) as u32));
        if body["variablesReference"].as_i64().is_some_and(|reference| reference > 0) {
            let mut variable = Variable::from_dap(body);
            variable.value = body["output"].as_str().unwrap_or_default().trim_end().to_owned();
            self.debug.repl.push(ReplElement::Variable { session_id: session_id.to_owned(), variable, severity });
            cx.notify();
            return;
        }
        self.append_to_repl(session_id, body["output"].as_str().unwrap_or_default(), severity, source, cx);
    }

    /// replModel.ts `appendToRepl`: text joins the last unfinished line; a repeated line counts up.
    pub(crate) fn append_to_repl(&mut self, session_id: &str, text: &str, severity: Severity, source: Option<(String, u32)>, cx: &mut Context<Self>) {
        crate::debug::session::append_output(&mut self.debug.repl, session_id, text, severity, source);
        cx.notify();
    }

    /// debugSession.ts `fetchThreads`.
    pub(crate) fn fetch_threads(&mut self, session_id: String, window: &mut Window, cx: &mut Context<Self>) {
        let reply = self.dap_request(&session_id, "threads", Value::Null);
        cx.spawn_in(window, async move |this, cx| {
            let Ok(body) = answer(reply).await else { return };
            let _ = on_workbench(&this, cx, |workbench, _, cx| {
                if let Some(session) = workbench.debug.session_mut(&session_id) {
                    session.set_threads(body["threads"].as_array().map_or(&[], Vec::as_slice));
                }
                cx.notify();
            });
        })
        .detach();
    }

    /// debugSession.ts `handleStop` and debugService.ts's focus: threads, the top frame, focus, then the rest.
    fn session_stopped(&mut self, session_id: String, body: Value, window: &mut Window, cx: &mut Context<Self>) {
        self.remove_run_to_cursor_breakpoint(cx);
        // Sent at once with `hitBreakpointIds`, as the dependent breakpoints may take a moment to set.
        if let Some(hit) = body["hitBreakpointIds"].as_array() {
            let hit: Vec<String> = self.debug.model.breakpoints.iter().filter(|breakpoint| breakpoint.base.id_from_adapter(&session_id).is_some_and(|id| hit.contains(&json!(id)))).map(|breakpoint| breakpoint.id().to_owned()).collect();
            self.enable_dependent_breakpoints(&session_id, &hit, cx);
        }
        let threads = self.dap_request(&session_id, "threads", Value::Null);
        cx.spawn_in(window, async move |this, cx| {
            let threads = answer(threads).await.unwrap_or_default();
            let thread_id = body["threadId"].as_i64();
            let ids = on_workbench(&this, cx, |workbench, _, _| {
                let session = workbench.debug.session_mut(&session_id)?;
                session.set_threads(threads["threads"].as_array().map_or(&[], Vec::as_slice));
                session.stop_threads(&body);
                Some(session.threads.iter().filter(|thread| thread.stopped).map(|thread| thread.id).collect::<Vec<i64>>())
            });
            let Ok(Some(ids)) = ids else { return };
            // The stopped thread first, as handleStop fetches its call stack before the others'.
            let mut ordered: Vec<i64> = thread_id.into_iter().filter(|id| ids.contains(id)).collect();
            ordered.extend(ids.iter().filter(|id| Some(**id) != thread_id));
            for (index, id) in ordered.into_iter().enumerate() {
                let reply = on_workbench(&this, cx, |workbench, _, _| workbench.dap_request(&session_id, "stackTrace", json!({ "threadId": id, "startFrame": 0, "levels": 20 })));
                let Ok(reply) = reply else { return };
                let frames = answer(reply).await.unwrap_or_default();
                let focus_now = index == 0;
                let _ = on_workbench(&this, cx, |workbench, window, cx| {
                    workbench.accept_stack_trace(&session_id, id, &frames);
                    if focus_now && Some(id) == thread_id && body["hitBreakpointIds"].is_null() && body["reason"] == "breakpoint" {
                        let hit = workbench.breakpoints_at_top_frame(&session_id, id);
                        workbench.enable_dependent_breakpoints(&session_id, &hit, cx);
                    }
                    if focus_now {
                        workbench.focus_after_stop(&session_id, id, &body["reason"], window, cx);
                    }
                    cx.notify();
                });
            }
        })
        .detach();
    }

    /// debugSession.ts `getBreakpointsAtPosition` for the thread's top frame.
    fn breakpoints_at_top_frame(&self, session_id: &str, thread_id: i64) -> Vec<String> {
        let Some(frame) = self.debug.session(session_id).and_then(|session| session.thread(thread_id)).and_then(|thread| thread.frames.first()) else { return Vec::new() };
        let Some(path) = frame.path() else { return Vec::new() };
        let frame_uri = crate::editor::uri_string("file", std::path::Path::new(path));
        let in_file = self.debug.model.breakpoints.iter().filter(|breakpoint| breakpoint.uri["scheme"] == "file" && breakpoint.uri_string() == frame_uri);
        let at_frame = in_file.filter(|breakpoint| (frame.line..=frame.end_line).contains(&breakpoint.line_number()) && breakpoint.column().is_none_or(|column| (frame.column..=frame.end_column).contains(&column)));
        at_frame.map(|breakpoint| breakpoint.id().to_owned()).collect()
    }

    /// debugSession.ts `enableDependentBreakpoints`: the enabled breakpoints a hit one triggers now trigger in this
    /// session and their files are sent again; resuming waits for the sends (`_waitToResume`).
    fn enable_dependent_breakpoints(&mut self, session_id: &str, hit: &[String], cx: &mut Context<Self>) {
        let mut uris = Vec::new();
        for breakpoint in &mut self.debug.model.breakpoints {
            if breakpoint.base.enabled && breakpoint.triggered_by.as_ref().is_some_and(|id| hit.contains(id)) {
                if !breakpoint.sessions_did_trigger.iter().any(|id| id == session_id) {
                    breakpoint.sessions_did_trigger.push(session_id.to_owned());
                }
                uris.push(breakpoint.uri_string());
            }
        }
        uris.sort_unstable();
        uris.dedup();
        let sends: Vec<Reply> = uris.iter().map(|uri| self.send_breakpoints(session_id, uri, false, cx)).collect();
        let wait = cx.background_executor().spawn(async move {
            futures::future::join_all(sends).await;
        });
        if let Some(session) = self.debug.session_mut(session_id) {
            session.wait_to_resume = Some(futures::FutureExt::shared(wait));
        }
    }

    /// callStackView.ts "Load More Stack Frames": the next 20 frames after those fetched.
    pub(crate) fn fetch_more_frames(&mut self, session_id: &str, thread_id: i64, cx: &mut Context<Self>) {
        let Some(start) = self.debug.session(session_id).and_then(|session| session.thread(thread_id)).map(|thread| thread.frames.len()) else { return };
        let reply = self.dap_request(session_id, "stackTrace", json!({ "threadId": thread_id, "startFrame": start, "levels": 20 }));
        let session_id = session_id.to_owned();
        cx.spawn(async move |this, cx| {
            let Ok(body) = answer(reply).await else { return };
            let _ = this.update(cx, |workbench, cx| {
                let Some(thread) = workbench.debug.session_mut(&session_id).and_then(|session| session.thread_mut(thread_id)) else { return };
                let fetched = std::mem::take(&mut thread.frames);
                workbench.accept_stack_trace(&session_id, thread_id, &body);
                let Some(thread) = workbench.debug.session_mut(&session_id).and_then(|session| session.thread_mut(thread_id)) else { return };
                let more = std::mem::replace(&mut thread.frames, fetched);
                thread.frames.extend(more);
                thread.total_frames = body["totalFrames"].as_u64().filter(|total| *total as usize > thread.frames.len());
                cx.notify();
            });
        })
        .detach();
    }

    fn accept_stack_trace(&mut self, session_id: &str, thread_id: i64, body: &Value) {
        let Some(thread) = self.debug.session_mut(session_id).and_then(|session| session.thread_mut(thread_id)) else { return };
        thread.frames = body["stackFrames"]
            .as_array()
            .into_iter()
            .flatten()
            .map(|frame| {
                let (line, column) = (frame["line"].as_u64().unwrap_or(1) as u32, frame["column"].as_u64().unwrap_or(1) as u32);
                (frame, line, column)
            })
            .map(|(frame, line, column)| StackFrame {
                id: frame["id"].as_i64().unwrap_or_default(),
                name: frame["name"].as_str().unwrap_or_default().to_owned(),
                source: frame["source"].clone(),
                line,
                column,
                end_line: frame["endLine"].as_u64().map_or(line, |end| end as u32),
                end_column: frame["endColumn"].as_u64().map_or(column, |end| end as u32),
                presentation_hint: frame["presentationHint"].as_str().map(str::to_owned),
                can_restart: frame["canRestart"] == true,
                instruction_pointer_reference: frame["instructionPointerReference"].as_str().map(str::to_owned),
            })
            .collect();
        thread.total_frames = body["totalFrames"].as_u64().filter(|total| *total as usize > thread.frames.len());
    }

    /// The focus after a stop: the focused session or none focused takes the stopped thread
    /// (debugService.ts `onDidStop` with `focusStackFrame`), and `debug.openDebug: openOnDebugBreak` shows the view on a breakpoint.
    fn focus_after_stop(&mut self, session_id: &str, thread_id: i64, reason: &Value, window: &mut Window, cx: &mut Context<Self>) {
        let focused = self.debug.focus.session.as_deref();
        let focused_is_running = self.debug.focused_session().is_none_or(|session| session.state(self.debug.focus.thread) != State::Stopped);
        if focused.is_none() || focused == Some(session_id) || focused_is_running {
            let target = self.debug.focus_target(Some(session_id), Some(thread_id));
            // debugSession.ts: `preserveFocus` is `!debug.focusEditorOnBreak`.
            let reveal = if self.setting("debug.focusEditorOnBreak") == json!(false) { Reveal::PreservingFocus } else { Reveal::TakingFocus };
            self.set_debug_focus(target, reveal, window, cx);
        }
        let suppressed = self.debug.session(session_id).is_some_and(|session| session.options["suppressDebugView"] == true);
        if reason == "breakpoint" && self.setting("debug.openDebug") == "openOnDebugBreak" && !suppressed {
            self.show_debug_view(cx);
        }
        if self.setting("debug.focusWindowOnBreak") != false {
            window.activate_window();
        }
    }

    fn threads_continued(&mut self, session_id: &str, thread_id: Option<i64>, cx: &mut Context<Self>) {
        let Some(session) = self.debug.session_mut(session_id) else { return };
        session.continue_threads(thread_id);
        self.debug_memory_session_changed(session_id, None);
        if self.debug.focus.session.as_deref() == Some(session_id) && thread_id.is_none_or(|id| Some(id) == self.debug.focus.thread) {
            self.debug.focus.frame = None;
            self.close_exception_widget(cx);
            self.debug.scopes.clear();
            self.debug.children.clear();
            self.send_stack_frame_focus();
            self.update_debug_inline_values(cx);
        }
        cx.notify();
    }

    /// debugService.ts `focusStackFrame`: the view model's focus, the frame's file opened at its line, the
    /// variables and watches of the frame, and `$acceptStackFrameFocus` for the host.
    pub(crate) fn set_debug_focus(&mut self, focus: DebugFocus, reveal: Reveal, window: &mut Window, cx: &mut Context<Self>) {
        let session_changed = focus.session != self.debug.focus.session;
        self.debug.focus = focus;
        if session_changed {
            self.debug_console.selected_session = None;
            let dto = self.debug.focused_session().map(|session| self.debug.session_dto(session));
            self.host.send("ExtHostDebugService", "$acceptDebugSessionActiveChanged", vec![dto.unwrap_or(Value::Null)]);
            self.update_breakpoints_hint(cx);
        }
        self.send_stack_frame_focus();
        self.debug.scopes.clear();
        self.debug.children.clear();
        self.debug_view.expand_first_scope = self.debug_view.variables_view_created || self.is_view_visible(super::debug_view::VARIABLES_VIEW);
        self.debug_view.call_stack_selects_focus = self.debug_view.call_stack_view_created || self.is_view_visible(super::debug_view::CALL_STACK_VIEW);
        self.disassembly_focus_changed(cx);
        if reveal != Reveal::No && let Some(frame) = self.debug.focused_frame().cloned() {
            self.reveal_stack_frame(&frame, reveal == Reveal::PreservingFocus, window, cx);
        }
        self.toggle_exception_widget(cx);
        self.update_debug_inline_values(cx);
        self.refresh_focus(window, cx);
    }

    fn send_stack_frame_focus(&self) {
        let focus = &self.debug.focus;
        let value = match (&focus.session, focus.thread, focus.frame) {
            (Some(session), Some(thread), Some(frame)) => json!({ "kind": "stackFrame", "threadId": thread, "frameId": frame, "sessionId": session }),
            (Some(session), Some(thread), None) => json!({ "kind": "thread", "threadId": thread, "sessionId": session }),
            _ => Value::Null,
        };
        self.host.send("ExtHostDebugService", "$acceptStackFrameFocus", vec![value]);
    }

    /// `StackFrame.openInEditor`: the file at the frame's line, revealed in the center if outside the view; the
    /// Disassembly view instead when it is active, or after an instruction breakpoint or instruction step.
    fn reveal_stack_frame(&mut self, frame: &StackFrame, preserve_focus: bool, window: &mut Window, cx: &mut Context<Self>) {
        if frame.instruction_pointer_reference.is_some() {
            let thread = self.debug.focused_session().zip(self.debug.focus.thread).and_then(|(session, id)| session.thread(id));
            let reason = thread.map(|thread| thread.stopped_details["reason"].clone()).unwrap_or_default();
            let stepped_instruction = reason == "step" && thread.is_some_and(|thread| thread.last_stepping_granularity == Some("instruction"));
            if self.disassembly_view_active() || (!preserve_focus && (reason == "instruction breakpoint" || stepped_instruction)) {
                self.open_disassembly_view(window, cx);
                return;
            }
        }
        let Some(path) = frame.path() else { return };
        let path = PathBuf::from(path);
        if !path.is_file() {
            return;
        }
        let editor_focused = self.editor_focus.is_focused(window);
        let previous_focus = window.focused(cx);
        self.open_file(path.clone(), true, window, cx);
        let line = frame.line.max(1) as usize;
        let column = frame.column.max(1) as usize;
        let range = crate::anything_quick_access::TextRange { start_line_number: line, start_column: column, end_line_number: line, end_column: column };
        // debugSource.ts `openInEditor`: `TextEditorSelectionRevealType.CenterIfOutsideViewport`.
        self.select_range_revealed(&path, range, crate::editor::VerticalReveal::CenterIfOutsideViewport, cx);
        // preserveFocus unless the editor had it: the stop must not take the focus from a view.
        match previous_focus {
            Some(previous) if !editor_focused => window.focus(&previous, cx),
            None => window.blur(cx),
            Some(_) => {}
        }
    }

    /// The focused frame's scopes and the watch expressions, evaluated again (variablesView.ts and
    /// watchExpressionsView.ts on focus change).
    pub(crate) fn refresh_focus(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let (Some(session_id), Some(frame_id)) = (self.debug.focus.session.clone(), self.debug.focus.frame) else {
            self.debug.watch_values.clear();
            cx.notify();
            return;
        };
        let scopes = self.dap_request(&session_id, "scopes", json!({ "frameId": frame_id }));
        let watches: Vec<(String, Reply)> = self
            .debug
            .model
            .watch_expressions
            .clone()
            .into_iter()
            .map(|expression| (expression.id, self.dap_request(&session_id, "evaluate", json!({ "expression": expression.name, "frameId": frame_id, "context": "watch" }))))
            .collect();
        cx.spawn_in(window, async move |this, cx| {
            let scopes = answer(scopes).await.unwrap_or_default();
            let scopes: Vec<Variable> = scopes["scopes"].as_array().into_iter().flatten().map(Variable::from_dap).collect();
            // variablesView.ts expands the first scope that is not expensive.
            let first = scopes.iter().find(|scope| !scope.expensive).map(|scope| (format!("scope/{}", scope.name), scope.variables_reference));
            let _ = on_workbench(&this, cx, |workbench, window, cx| {
                workbench.debug.scopes = scopes;
                if let Some((key, reference)) = first
                    && workbench.row_expanded(&key, workbench.debug_view.expand_first_scope)
                {
                    workbench.fetch_children(&session_id, reference, window, cx);
                }
                cx.notify();
            });
            for (id, reply) in watches {
                let mut value = evaluation_result(String::new(), answer(reply).await);
                // debugModel.ts `evaluateExpression` without `keepLazyVars`.
                if value.is_lazy() {
                    evaluate_lazy(&this, cx, &session_id, &mut value).await;
                }
                let _ = on_workbench(&this, cx, |workbench, _, cx| {
                    let name = workbench.debug.model.watch_expressions.iter().find(|expression| expression.id == id).map(|expression| expression.name.clone()).unwrap_or_default();
                    workbench.debug.watch_values.insert(id, Variable { name, ..value });
                    cx.notify();
                });
            }
        })
        .detach();
    }

    /// `Variable.getChildren`: the `variables` request of a row, cached until the focus moves.
    pub(crate) fn fetch_children(&mut self, session_id: &str, reference: i64, window: &mut Window, cx: &mut Context<Self>) {
        let key = (session_id.to_owned(), reference);
        if self.debug.children.contains_key(&key) {
            return;
        }
        self.debug.children.insert(key, Vec::new());
        self.request_children(session_id, reference, window, cx);
    }

    /// debugViewModel.ts `updateViews`: the shown rows and watch values fetched again, each keeping its rows until the reply.
    pub(crate) fn update_debug_views(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let shown: Vec<(String, i64)> = self.debug.children.keys().cloned().collect();
        for (session_id, reference) in shown {
            self.request_children(&session_id, reference, window, cx);
        }
        self.refresh_focus(window, cx);
    }

    fn request_children(&mut self, session_id: &str, reference: i64, window: &mut Window, cx: &mut Context<Self>) {
        let key = (session_id.to_owned(), reference);
        let reply = self.dap_request(session_id, "variables", json!({ "variablesReference": reference }));
        let auto_expand_lazy = self.auto_expand_lazy_variables();
        let session_id = session_id.to_owned();
        cx.spawn_in(window, async move |this, cx| {
            let body = answer(reply).await.unwrap_or_default();
            let mut variables: Vec<Variable> = body["variables"].as_array().into_iter().flatten().map(Variable::from_dap).collect();
            if auto_expand_lazy {
                for variable in variables.iter_mut().filter(|variable| variable.is_lazy()) {
                    evaluate_lazy(&this, cx, &session_id, variable).await;
                }
            }
            let _ = on_workbench(&this, cx, |workbench, window, cx| {
                workbench.debug.children.insert(key, variables);
                workbench.visualize_children(&session_id, reference, window, cx);
                cx.notify();
            });
        })
        .detach();
    }

    /// debugSession.ts `autoExpandLazyVariables`.
    fn auto_expand_lazy_variables(&self) -> bool {
        match self.setting("debug.autoExpandLazyVariables").as_str() {
            Some("on") => true,
            Some("auto") => self.is_screen_reader_optimized(),
            _ => false,
        }
    }

    /// The lazy button of the row `key` (baseDebugView.ts `lazyButton`): the row takes the value it stands for, and
    /// one with children expands (`onDidEvaluateLazyExpression`) in the tree of its key: `hover/` for the debug hover.
    pub(crate) fn evaluate_lazy_row(&mut self, session_id: &str, parent_reference: i64, name: &str, key: &str, window: &mut Window, cx: &mut Context<Self>) {
        let children_key = (session_id.to_owned(), parent_reference);
        let Some(mut variable) = self.debug.children.get(&children_key).and_then(|children| children.iter().find(|child| child.name == name)).cloned() else { return };
        let (session_id, key) = (session_id.to_owned(), key.to_owned());
        cx.spawn_in(window, async move |this, cx| {
            evaluate_lazy(&this, cx, &session_id, &mut variable).await;
            let _ = on_workbench(&this, cx, |workbench, window, cx| {
                let Some(row) = workbench.debug.children.get_mut(&children_key).and_then(|children| children.iter_mut().find(|child| child.name == variable.name)) else { return };
                *row = variable.clone();
                if variable.has_children() {
                    match key.starts_with("hover/") {
                        true => workbench.debug_hover.expanded.insert(key),
                        false => workbench.debug_view.expanded.insert(key),
                    };
                    workbench.fetch_children(&session_id, variable.variables_reference, window, cx);
                }
                cx.notify();
            });
        })
        .detach();
    }

    /// debugService.ts `startDebugging` as the host and the start commands call it: a launch configuration by
    /// name (or a compound), or a configuration object.
    pub(crate) fn start_debugging(&mut self, folder: Option<PathBuf>, name_or_config: Value, options: Value, tasks: DebugTasks, window: &mut Window, cx: &mut Context<Self>) -> Reply {
        let (sender, receiver) = oneshot::channel();
        self.debug.initializing = true;
        cx.notify();
        cx.spawn_in(window, async move |this, cx| {
            let result = start_debugging_flow(&this, cx, folder, name_or_config, options, tasks).await;
            let result = on_workbench(&this, cx, |workbench, _, cx| {
                workbench.debug.initializing = false;
                cx.notify();
                match result {
                    Ok(started) => Ok(json!(started)),
                    Err(message) => {
                        workbench.notify_error(message.clone());
                        Err(error_value(&message))
                    }
                }
            });
            let _ = sender.send(result.unwrap_or_else(|message| Err(error_value(&message))));
        })
        .detach();
        receiver
    }

    /// debugService.ts `stopSession`: terminate one session, or all.
    pub(crate) fn stop_session(&mut self, session_id: Option<String>, disconnect: bool, suspend: bool, window: &mut Window, cx: &mut Context<Self>) -> Reply {
        let ids: Vec<String> = match session_id {
            Some(id) => vec![id],
            None => self.debug.sessions.iter().map(|session| session.id.clone()).collect(),
        };
        if ids.is_empty() {
            self.cancel_debug_tasks();
        }
        let (sender, receiver) = oneshot::channel();
        let stops: Vec<Reply> = ids.into_iter().map(|id| if disconnect { self.disconnect_session(id, false, if suspend { Debuggee::Suspend } else { Debuggee::Keep }, window, cx) } else { self.terminate_session(id, false, window, cx) }).collect();
        cx.background_executor()
            .spawn(async move {
                for stop in stops {
                    let _ = stop.await;
                }
                let _ = sender.send(Ok(Value::Null));
            })
            .detach();
        receiver
    }

    /// debugSession.ts `terminate`: the parent of a child managed by it, else `terminate` when supported for a
    /// launch, else `disconnect` that terminates the debuggee.
    fn terminate_session(&mut self, session_id: String, restart: bool, window: &mut Window, cx: &mut Context<Self>) -> Reply {
        let Some(session) = self.debug.session(&session_id) else { return ready(Value::Null) };
        if session.options["lifecycleManagedByParent"] == true && let Some(parent) = session.parent.clone() {
            return self.terminate_session(parent, restart, window, cx);
        }
        if session.exited {
            self.session_ended(&session_id, window, cx);
            return ready(Value::Null);
        }
        let terminate = session.capabilities["supportsTerminateRequest"] == true && session.configuration["request"] == "launch" && !session.terminated;
        if !terminate {
            return self.disconnect_session(session_id, restart, Debuggee::Terminate, window, cx);
        }
        if let Some(session) = self.debug.session_mut(&session_id) {
            session.terminated = true;
        }
        let reply = self.dap_request(&session_id, "terminate", json!({ "restart": restart }));
        let (sender, receiver) = oneshot::channel();
        cx.spawn_in(window, async move |this, cx| {
            // rawDebugSession.ts `terminate`: a failed terminate falls back to disconnect.
            if answer(reply).await.is_err() {
                let disconnect = on_workbench(&this, cx, |workbench, window, cx| workbench.disconnect_session(session_id, restart, Debuggee::Terminate, window, cx));
                if let Ok(disconnect) = disconnect {
                    let _ = disconnect.await;
                }
            }
            let _ = sender.send(Ok(Value::Null));
        })
        .detach();
        receiver
    }

    /// rawDebugSession.ts `disconnect` then `stopAdapter`: the adapter has 2 s to answer, then it is stopped.
    fn disconnect_session(&mut self, session_id: String, restart: bool, debuggee: Debuggee, window: &mut Window, cx: &mut Context<Self>) -> Reply {
        let Some(session) = self.debug.session(&session_id) else { return ready(Value::Null) };
        if session.options["lifecycleManagedByParent"] == true && let Some(parent) = session.parent.clone() {
            return self.disconnect_session(parent, restart, debuggee, window, cx);
        }
        self.raw_disconnect(session_id, restart, debuggee, window, cx)
    }

    /// rawDebugSession.ts `disconnect`, then the adapter stops and the session ends.
    fn raw_disconnect(&mut self, session_id: String, restart: bool, debuggee: Debuggee, window: &mut Window, cx: &mut Context<Self>) -> Reply {
        let Some(session) = self.debug.session_mut(&session_id) else { return ready(Value::Null) };
        session.terminated = true;
        let handle = session.handle;
        let mut arguments = json!({ "restart": restart, "terminateDebuggee": debuggee == Debuggee::Terminate });
        if debuggee == Debuggee::Suspend {
            arguments["suspendDebuggee"] = json!(true);
        }
        let reply = self.dap_request(&session_id, "disconnect", arguments);
        let (sender, receiver) = oneshot::channel();
        cx.spawn_in(window, async move |this, cx| {
            let timer = cx.background_executor().timer(std::time::Duration::from_secs(2));
            futures::future::select(Box::pin(reply), Box::pin(timer)).await;
            let _ = on_workbench(&this, cx, |workbench, window, cx| {
                // A session relaunched by a restart in the meantime has a new adapter handle and stays.
                if workbench.debug.session_by_handle(handle).is_none() {
                    return;
                }
                workbench.host.send("ExtHostDebugService", "$stopDASession", vec![json!(handle)]);
                workbench.session_ended(&session_id, window, cx);
            });
            let _ = sender.send(Ok(Value::Null));
        })
        .detach();
        receiver
    }

    /// debugService.ts `restartSession`: an adapter with `supportsRestartRequest` gets `restart`; otherwise the
    /// session ends and, 300 ms later, launches again with a new adapter, keeping its id and Debug Console.
    /// `restart_data` (a `terminated` event's `restart`) disconnects instead of terminating and runs no tasks.
    pub(super) fn restart_session(&mut self, session_id: String, restart_data: Option<Value>, window: &mut Window, cx: &mut Context<Self>) -> Reply {
        let (sender, receiver) = oneshot::channel();
        cx.spawn_in(window, async move |this, cx| {
            let result = match restart_flow(&this, cx, &session_id, restart_data).await {
                Ok(()) => Ok(Value::Null),
                Err(message) => {
                    let _ = on_workbench(&this, cx, |workbench, _, _| workbench.notify_error(message.clone()));
                    Err(error_value(&message))
                }
            };
            let _ = sender.send(result);
        })
        .detach();
        receiver
    }

    /// debugUtils.ts `getExtensionHostDebugSession`: the session or its nearest parent that debugs an extension host.
    pub(super) fn extension_host_debug_session(&self, session_id: &str) -> Option<&Session> {
        let mut session = self.debug.session(session_id)?;
        loop {
            let debug_type = session.configuration["type"].as_str()?;
            if debug_type.eq_ignore_ascii_case("extensionhost") || debug_type.eq_ignore_ascii_case("pwa-extensionhost") {
                return Some(session);
            }
            session = self.debug.session(session.parent.as_deref()?)?;
        }
    }

    /// debugSession.ts `restart`: the request goes to the parent of a child whose lifecycle it manages.
    fn restart_request(&mut self, session_id: &str) -> Reply {
        let Some(session) = self.debug.session(session_id) else { return ready(Value::Null) };
        if session.options["lifecycleManagedByParent"] == true && let Some(parent) = session.parent.clone() {
            return self.restart_request(&parent);
        }
        let arguments = session.configuration.clone();
        self.dap_request(session_id, "restart", json!({ "arguments": arguments }))
    }

    /// debugService.ts `onAttachSession`: the extension host a session launched is up with its inspector on `port`, so
    /// the session, active or ended, attaches to it on a new adapter (debugSession.ts `initialize` shuts the old one down).
    pub(crate) fn attach_session(&mut self, session_id: &str, port: u16, window: &mut Window, cx: &mut Context<Self>) {
        let session = match self.debug.sessions.iter().position(|session| session.id == session_id) {
            Some(index) => {
                drop(self.dap_request(session_id, "disconnect", json!({})));
                let session = self.debug.sessions.remove(index);
                self.host.send("ExtHostDebugService", "$stopDASession", vec![json!(session.handle)]);
                session
            }
            None => {
                let Some(index) = self.debug.inactive_sessions.iter().position(|session| session.id == session_id) else { return };
                self.debug.inactive_sessions.remove(index)
            }
        };
        let mut configuration = session.configuration;
        configuration["request"] = json!("attach");
        configuration["port"] = json!(port);
        self.debug.next_handle += 1;
        let mut attaching = Session::new(session.id, self.debug.next_handle, configuration, session.unresolved_configuration, session.folder_uri, session.options);
        attaching.name = session.name;
        attaching.parent = session.parent;
        self.debug.sessions.push(attaching);
        let session_id = session_id.to_owned();
        cx.spawn_in(window, async move |this, cx| {
            let Err((message, show_user)) = launch_or_attach(&this, cx, &session_id).await else { return };
            let _ = on_workbench(&this, cx, |workbench, window, cx| {
                drop(workbench.disconnect_session(session_id, false, Debuggee::Terminate, window, cx));
                if show_user {
                    workbench.notify_error(message);
                }
            });
        })
        .detach();
        cx.notify();
    }

    /// debugSession.ts `initialize` for a restart: a connection still open is shut down, then the ended session
    /// returns under its id with a new adapter handle.
    fn relaunch_session(&mut self, session_id: &str, window: &mut Window, cx: &mut Context<Self>) {
        if let Some(session) = self.debug.session(session_id) {
            self.host.send("ExtHostDebugService", "$stopDASession", vec![json!(session.handle)]);
            self.session_ended(session_id, window, cx);
        }
        let Some(index) = self.debug.inactive_sessions.iter().position(|session| session.id == session_id) else { return };
        let ended = self.debug.inactive_sessions.remove(index);
        self.debug.next_handle += 1;
        let mut session = Session::new(ended.id, self.debug.next_handle, ended.configuration, ended.unresolved_configuration, ended.folder_uri, ended.options);
        session.name = ended.name;
        session.parent = ended.parent;
        self.debug.sessions.push(session);
        cx.notify();
    }

    /// The adapter of a handle exited or failed (`onDidExitAdapter`).
    fn adapter_exited(&mut self, handle: u32, error: Option<String>, window: &mut Window, cx: &mut Context<Self>) {
        let Some(session) = self.debug.session_by_handle(handle) else { return };
        let (session_id, ending) = (session.id.clone(), session.terminated);
        // A connection that closes after a disconnect is the end the session asked for, not a crash.
        if let Some(error) = error.filter(|_| !ending) {
            self.notify_error(format!("Debug adapter process has terminated unexpectedly ({error})"));
        }
        self.session_ended(&session_id, window, cx);
    }

    /// debugService.ts `onDidEndAdapter`: the session leaves the model, its requests fail, the focus moves on.
    pub(super) fn session_ended(&mut self, session_id: &str, window: &mut Window, cx: &mut Context<Self>) {
        let Some(index) = self.debug.sessions.iter().position(|session| session.id == session_id) else { return };
        // #3905: 'Run Without Debugging' ends the extension development host with its adapter.
        if let Some(extension_session) = self.extension_host_debug_session(session_id)
            && extension_session.initialized
            && extension_session.configuration["noDebug"] == true
        {
            super::host::run_in_extension_development_host(&extension_session.id, "workbench.action.closeWindow", cx);
        }
        let shown_repl = self.shown_repl_session();
        let mut session = self.debug.sessions.remove(index);
        self.debug_memory_session_changed(session_id, None);
        if self.debug.sessions.is_empty() {
            self.debug.multi_session_view = false;
        }
        session.exited = true;
        session.cancel_pending();
        let dto = self.debug.session_dto(&session);
        self.debug.known_sessions.remove(session_id);
        self.host.send("ExtHostDebugService", "$acceptDebugSessionTerminated", vec![dto]);
        let capabilities = session.capabilities.clone();
        self.debug.model.set_breakpoint_session_data(session_id, &capabilities, None);
        self.debug.model.set_exception_breakpoint_fallback_session(session_id);
        self.debug.model.remove_exception_breakpoints_for_session(session_id);
        self.update_breakpoints_hint(cx);
        self.remove_run_to_cursor_breakpoint(cx);
        let post_debug_task = session.configuration["postDebugTask"].clone();
        if !post_debug_task.is_null() {
            cx.spawn_in(window, async move |this, cx| {
                if let Err(message) = run_task(&this, cx, &post_debug_task).await {
                    let _ = on_workbench(&this, cx, |workbench, _, _| workbench.notify_error(message));
                }
            })
            .detach();
        }
        if self.debug.focus.session.as_deref() == Some(session_id) {
            self.debug.focus = self.debug.focus_target(None, None);
            self.close_exception_widget(cx);
            self.debug.scopes.clear();
            self.debug.children.clear();
            self.debug.watch_values.clear();
            let dto = self.debug.focused_session().map(|session| self.debug.session_dto(session));
            self.host.send("ExtHostDebugService", "$acceptDebugSessionActiveChanged", vec![dto.unwrap_or(Value::Null)]);
            self.send_stack_frame_focus();
            self.update_debug_inline_values(cx);
            // repl.ts `onDidFocusSession(undefined)` keeps the console's session in the tree.
            self.debug_console.selected_session = if self.debug.focus.session.is_some() { None } else { shown_repl };
        }
        self.debug.inactive_sessions.push(session);
        if self.debug.sessions.is_empty() {
            // Data breakpoints that cannot persist end with the last session.
            let transient: Vec<String> = self.debug.model.data_breakpoints.iter().filter(|breakpoint| !breakpoint.can_persist).map(|breakpoint| breakpoint.base.id.clone()).collect();
            for id in transient {
                self.debug.model.remove_data_breakpoints(Some(&id));
            }
            if self.setting("debug.openExplorerOnEnd") == true {
                self.side_bar_view = super::search_view::SideBarView::Explorer;
            }
        }
        self.store_debug_model();
        cx.notify();
    }

    /// `quickInputService.pick` for the start flow: answers the picked item's handle, `None` when dismissed.
    pub(super) fn debug_pick(&mut self, placeholder: &str, entries: Vec<Entry>, window: &mut Window, cx: &mut Context<Self>) -> oneshot::Receiver<Option<String>> {
        let (sender, receiver) = oneshot::channel();
        let mut input = QuickInput::new(0, Kind::QuickPick);
        input.placeholder = Some(placeholder.into());
        input.set_items(entries);
        let id = self.quick_inputs.add(input, Owner::Debug(Some(sender)));
        self.show_quick_input(id, window, cx);
        self.flush_quick_input_events(window, cx);
        receiver
    }

    /// The picker or input box of the start flow: Enter answers the item's handle (the selected handles joined by
    /// commas with `can_select_many`) or the typed value.
    pub fn debug_pick_event(&mut self, id: i64, event: Event, window: &mut Window, cx: &mut Context<Self>) {
        match event {
            Event::Accept(_) => {
                let Some(input) = self.quick_inputs.get(id) else { return };
                let answer = match input.kind {
                    Kind::QuickPick if input.can_select_many => Some(input.selected_handles().iter().map(i64::to_string).collect::<Vec<_>>().join(",")),
                    Kind::QuickPick => input.selected_handles().first().map(|handle| handle.to_string()),
                    Kind::InputBox => Some(input.input_box.value.clone()),
                    Kind::Widget => None,
                };
                let Some(answer) = answer else { return };
                if let Some(Owner::Debug(reply)) = self.quick_inputs.owner_mut(id)
                    && let Some(reply) = reply.take()
                {
                    let _ = reply.send(Some(answer));
                }
                self.hide_quick_input_by_id(id, window, cx);
            }
            Event::TriggerItemButton(handle, _, _) => {
                if let Some(Owner::Debug(reply)) = self.quick_inputs.owner_mut(id)
                    && let Some(reply) = reply.take()
                {
                    let _ = reply.send(Some(format!("{BUTTON_ANSWER}{handle}")));
                }
                self.hide_quick_input_by_id(id, window, cx);
            }
            Event::Hide => {
                if let Some(Owner::Debug(reply)) = self.quick_inputs.owner_mut(id)
                    && let Some(reply) = reply.take()
                {
                    let _ = reply.send(None);
                }
                self.quick_inputs.remove(id);
            }
            _ => {}
        }
    }

    /// Opens the Run and Debug view where its container is.
    pub(crate) fn show_debug_view(&mut self, cx: &mut Context<Self>) {
        self.show_view_container(super::debug_view::DEBUG_CONTAINER, cx);
    }
}

fn ready(value: Value) -> Reply {
    let (sender, receiver) = oneshot::channel();
    let _ = sender.send(Ok(value));
    receiver
}

/// rawDebugSession.ts `launchVsCode`: each argument's `prefix` and `path` joined, the environment as
/// `--extensionEnvironment`.
fn launch_vs_code_args(arguments: &Value) -> Vec<String> {
    let mut args = Vec::new();
    for arg in arguments["args"].as_array().into_iter().flatten() {
        let arg = format!("{}{}", arg["prefix"].as_str().unwrap_or_default(), arg["path"].as_str().unwrap_or_default());
        // js-debug turns a folder or file argument into `--folder-uri` or `--file-uri`; as paths they open the same.
        match arg.split_once('=') {
            Some(("--folder-uri" | "--file-uri", path)) => args.push(path.to_owned()),
            _ => args.push(arg),
        }
    }
    if arguments["env"].is_object() {
        args.push(format!("--extensionEnvironment={}", arguments["env"]));
    }
    args
}

/// The DAP `Source` of a breakpoint's resource: a file's path, else the URI string.
pub(super) fn source_of_uri(uri: &Value) -> Value {
    let path = match uri["scheme"].as_str() {
        Some("file") => json!(crate::uri::json_fs_path(uri)),
        _ => json!(crate::debug::uri_string(uri)),
    };
    let name = uri["path"].as_str().and_then(|path| path.rsplit('/').next()).unwrap_or_default();
    json!({ "name": name, "path": path })
}

fn set_one_session_data(model: &mut DebugModel, session_id: &str, capabilities: &Value, id: &str, breakpoint: &Value) {
    let data = crate::debug::SessionData::from_dap(breakpoint, capabilities);
    if let Some(found) = model.breakpoint_mut(id) {
        found.set_session_data(session_id, Some(data));
        return;
    }
    let model_bases = model.function_breakpoints.iter_mut().map(|breakpoint| &mut breakpoint.base).chain(model.data_breakpoints.iter_mut().map(|breakpoint| &mut breakpoint.base));
    let mut bases = model_bases.chain(model.exception_breakpoints.iter_mut().map(|breakpoint| &mut breakpoint.base)).chain(model.instruction_breakpoints.iter_mut().map(|breakpoint| &mut breakpoint.base));
    if let Some(base) = bases.find(|base| base.id == id) {
        base.set_session_data(session_id, Some(data));
    }
}

fn clear_one_session_data(model: &mut DebugModel, session_id: &str, id: &str) {
    if let Some(found) = model.breakpoint_mut(id) {
        found.set_session_data(session_id, None);
    }
}

/// A watch or REPL evaluation: the result row, or the error message drawn as one.
fn evaluation_result(name: String, result: Result<Value, String>) -> Variable {
    match result {
        Ok(body) => Variable { name, ..Variable::from_dap(&body) },
        Err(message) => Variable { name, value: message, error: true, ..Variable::default() },
    }
}

/// The start flow of debugService.ts `startDebugging` and `createSession`; `Err` rejects the start.
async fn start_debugging_flow(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, folder: Option<PathBuf>, name_or_config: Value, options: Value, tasks: DebugTasks) -> Result<bool, String> {
    let activation = on_workbench(this, cx, |workbench, _, _| workbench.host.activate_by_event("onDebug"))?;
    let _ = activation.await;
    // debugService.ts `startDebugging`: `saveBeforeStart` defaults to `!options.parentSession`; the host passes `suppressSaveBeforeStart`.
    if options["suppressSaveBeforeStart"].as_bool().map_or(options["parentSessionID"].is_null(), |suppress| !suppress) {
        save_all_before_debug_start(this, cx).await?;
    }
    let launch = match &folder {
        Some(folder) => Some(on_workbench(this, cx, |workbench, _, _| workbench.folder_launch(folder))?),
        None => None,
    };
    let config = match &name_or_config {
        Value::String(name) => {
            if let Some(compound) = launch.as_ref().and_then(|launch| launch.compound(name)).cloned() {
                return start_compound(this, cx, folder, launch.expect("a compound comes from a launch"), compound, options).await;
            }
            match launch.as_ref().and_then(|launch| launch.configuration(name)) {
                Some(config) => Some(config),
                None if launch.is_some() => return Err(format!("Configuration '{name}' is missing in 'launch.json'.")),
                None => return Err("'launch.json' does not exist for passed workspace folder.".into()),
            }
        }
        Value::Object(_) => Some(name_or_config.clone()),
        _ => None,
    };
    let launch_inputs = launch.map(|launch| launch.inputs).unwrap_or_default();
    create_session(this, cx, folder, config, options, launch_inputs, tasks).await
}

/// debugUtils.ts `saveAllBeforeDebugStart`: unless `debug.saveBeforeStart` (for the active editor's language) is
/// `none`, the dirty editors save, with `allEditorsInActiveGroup` an untitled active editor too; then the settings reload.
async fn save_all_before_debug_start(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext) -> Result<(), String> {
    let mode = on_workbench(this, cx, |workbench, _, _| {
        let language = workbench.editors.active().map(|editor| editor.document().language_id.clone());
        let overrides = config::configuration::Overrides { resource: None, override_identifier: language.as_deref() };
        workbench.settings.lock().unwrap().get_value(Some("debug.saveBeforeStart"), &overrides).unwrap_or(Value::Null)
    })?;
    if mode != "none" {
        let saves = on_workbench(this, cx, |workbench, _, cx| workbench.save_all_editors(false, cx))?;
        futures::future::join_all(saves).await;
        if mode == "allEditorsInActiveGroup" {
            let save = on_workbench(this, cx, |workbench, _, cx| {
                let index = workbench.editors.active_index().filter(|index| workbench.editors.editors[*index].document().scheme == "untitled")?;
                Some(workbench.save_editor(index, cx))
            })?;
            if let Some(save) = save {
                let _ = save.await;
            }
        }
    }
    on_workbench(this, cx, |workbench, _, cx| workbench.reload_changed_settings_files(cx))
}

/// A compound: each named configuration of the same launch.json, a success only when all start.
async fn start_compound(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, folder: Option<PathBuf>, launch: Launch, compound: Value, options: Value) -> Result<bool, String> {
    let Some(names) = compound["configurations"].as_array() else {
        return Err("Compound must have \"configurations\" attribute set in order to start multiple configurations.".into());
    };
    if !run_task_and_check_errors(this, cx, &compound["preLaunchTask"]).await? {
        return Ok(false);
    }
    let mut all = true;
    for name in names {
        let name = name.as_str().or(name["name"].as_str()).unwrap_or_default();
        if Some(name) == compound["name"].as_str() {
            all = false;
            continue;
        }
        let Some(config) = launch.configuration(name) else { return Err(format!("Could not find launch configuration '{name}' in the workspace.")) };
        all &= Box::pin(create_session(this, cx, folder.clone(), Some(config), options.clone(), launch.inputs.clone(), DebugTasks::PreLaunch)).await?;
    }
    Ok(all)
}

/// debugService.ts `createSession`: the type (guessed from the active editor without one), the providers'
/// resolution, variables, then a new session; its errors are shown and answer false.
async fn create_session(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, folder: Option<PathBuf>, config: Option<Value>, options: Value, inputs: Vec<Value>, tasks: DebugTasks) -> Result<bool, String> {
    let mut config = config.unwrap_or_else(|| json!({}));
    if options["noDebug"] == true {
        config["noDebug"] = json!(true);
    }
    let unresolved = config.clone();
    let mut debug_type = config["type"].as_str().map(str::to_owned);
    let mut folder = folder;
    if debug_type.is_none() {
        let Some((guessed, with_config)) = guess_debugger(this, cx).await? else { return Ok(false) };
        debug_type = Some(guessed);
        if let Some((dynamic_folder, dynamic_config)) = with_config {
            folder = dynamic_folder;
            config.as_object_mut().expect("a config object").extend(dynamic_config.as_object().cloned().unwrap_or_default());
        }
    }
    let folder_uri = folder.as_deref().map(exthost::scan::file_uri);
    let resolved = resolve_by_providers(this, cx, folder_uri.clone(), debug_type.clone().unwrap_or_default(), config).await?;
    let Some(resolved) = resolved.filter(|resolved| resolved["type"].is_string()) else { return Ok(false) };
    match finish_session(this, cx, folder, folder_uri, resolved, unresolved, options, inputs, tasks).await {
        Ok(started) => Ok(started),
        Err(message) => {
            on_workbench(this, cx, |workbench, _, cx| {
                workbench.notify_error(message);
                cx.notify();
            })?;
            Ok(false)
        }
    }
}

/// debugAdapterManager.ts `guessDebugger`: the debuggers interested in the active editor's language, picked when
/// more than one; remembered per file in `chosenEnvironments`. A "More {0} options..." pick also answers the
/// dynamic configuration picked and its folder.
async fn guess_debugger(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext) -> Result<Option<(String, Option<(Option<PathBuf>, Value)>)>, String> {
    let (resource, language) = on_workbench(this, cx, |workbench, _, _| workbench.editors.active().map(|editor| (editor.document().uri_string(), editor.document().language_id.clone())).unzip())?;
    if let Some(resource) = &resource
        && let Some(chosen) = on_workbench(this, cx, |workbench, _, _| workbench.debug.chosen_environments.get(resource).cloned())?
        && let Some(debug_type) = chosen["type"].as_str()
    {
        let mut with_config = None;
        if let Some(label) = chosen["dynamicLabel"].as_str() {
            let configurations = super::debug_dynamic::dynamic_configurations(this, cx, debug_type).await?;
            with_config = configurations.into_iter().find(|(_, config)| config["name"].as_str() == Some(label)).map(|(launch, config)| (launch.folder(), config));
        }
        return Ok(Some((debug_type.to_owned(), with_config)));
    }
    let activation = on_workbench(this, cx, |workbench, _, _| {
        workbench.debug.init_extension_activations();
        (workbench.host.activate_by_event("onDebugInitialConfigurations"), workbench.host.activate_by_event("onDebug"))
    })?;
    let _ = activation.0.await;
    let _ = activation.1.await;
    let (candidates, contributed, by_language, language_label, dynamic) = on_workbench(this, cx, |workbench, window, _| {
        let dynamic = workbench.dynamic_providers();
        let context = workbench.key_context(window);
        let mut contributed = Vec::new();
        for action in crate::menus::menu_actions(&workbench.menus, crate::menus::MenuId::DebugCreateConfiguration, &context) {
            if let crate::menus::MenuAction::Command { id, title, .. } = action {
                contributed.push((id, title));
            }
        }
        let language_label = language.as_deref().map(|language| workbench.languages.name(language).to_owned());
        let holds = |when: Option<&str>| when.and_then(crate::contextkey::Expr::deserialize).is_none_or(|when| when.evaluate(&context));
        let enabled: Vec<&Debugger> = workbench.debug.debuggers.iter().filter(|debugger| holds(debugger.when()) && workbench.debug.adapter_types.contains(&debugger.debug_type)).collect();
        let interested: Vec<&Debugger> = enabled.iter().copied().filter(|debugger| language.as_deref().is_some_and(|language| debugger.interested_in_language(language))).collect();
        let mut candidates: Vec<&Debugger> = match interested.len() {
            1 => return (vec![(interested[0].debug_type.clone(), interested[0].label().to_owned(), false)], contributed, true, language_label, dynamic),
            0 => enabled.into_iter().filter(|debugger| debugger.has_initial_configuration() || workbench.debug.providers.iter().any(|provider| provider.debug_type == debugger.debug_type && provider.has_provide)).collect(),
            _ => interested,
        };
        candidates.retain(|debugger| !debugger.hidden_when().and_then(crate::contextkey::Expr::deserialize).is_some_and(|when| when.evaluate(&context)));
        candidates.sort_by(|first, second| first.label().cmp(second.label()));
        // Suggested: a debugger whose extension activated early, or whose type a session already used.
        let early_activated = workbench.debug.early_activated.as_ref().expect("set before the activation above");
        let candidates = candidates.into_iter().map(|debugger| {
            let suggested = early_activated.contains(&debugger.extension_id) || workbench.debug.used_debug_types.contains(&debugger.debug_type);
            (debugger.debug_type.clone(), debugger.label().to_owned(), suggested)
        });
        (candidates.collect(), contributed, false, language_label, dynamic)
    })?;
    if by_language {
        return remember_chosen_environment(this, cx, resource, candidates[0].0.clone(), None);
    }
    if candidates.is_empty()
        && let Some(label) = language_label
    {
        let label = if label.contains(' ') { format!("'{label}'") } else { label };
        let message = format!("You don't have an extension for debugging {label}. Should we find a {label} extension in the Marketplace?");
        if super::explorer_actions::confirm(this, cx, gpui::PromptLevel::Warning, message, None, &format!("Find {label} extension")).await {
            on_workbench(this, cx, |workbench, window, cx| drop(workbench.execute_command("debug.installAdditionalDebuggers", vec![json!(label)], window, cx)))?;
        }
        return Ok(None);
    }
    let (entries, picks) = select_debugger_picks(&candidates, &dynamic, &contributed, language_label.as_deref());
    let picked = on_workbench(this, cx, |workbench, window, cx| workbench.debug_pick("Select debugger", entries, window, cx))?;
    let Some(handle) = picked.await.ok().flatten().and_then(|handle| handle.parse::<usize>().ok()) else { return Ok(None) };
    let debug_type = match &picks[handle] {
        GuessPick::Debugger(debug_type) => debug_type.clone(),
        GuessPick::Dynamic(debug_type) => {
            let Some(picked) = super::debug_dynamic::pick_dynamic_configuration(this, cx, debug_type.clone()).await? else { return Ok(None) };
            return remember_chosen_environment(this, cx, resource, debug_type.clone(), Some(picked));
        }
        // debugAdapterManager.ts: a `MenuId.DebugCreateConfiguration` item runs its command and starts nothing.
        GuessPick::Command(command) => {
            on_workbench(this, cx, |workbench, window, cx| drop(workbench.execute_command(command, Vec::new(), window, cx)))?;
            return Ok(None);
        }
        GuessPick::Install => {
            let args = language_label.into_iter().map(Value::from).collect();
            on_workbench(this, cx, |workbench, window, cx| drop(workbench.execute_command("debug.installAdditionalDebuggers", args, window, cx)))?;
            return Ok(None);
        }
    };
    remember_chosen_environment(this, cx, resource, debug_type, None)
}

enum GuessPick {
    Debugger(String),
    /// A dynamic configuration provider's type.
    Dynamic(String),
    Install,
    Command(String),
}

/// debugAdapterManager.ts `guessDebugger`'s picks: the Suggested debuggers, the others, the dynamic providers'
/// "More {0} options...", Install, then the `MenuId.DebugCreateConfiguration` items; each item's handle is its index
/// in the returned picks.
fn select_debugger_picks(candidates: &[(String, String, bool)], dynamic: &[(String, String)], contributed: &[(String, String)], language_label: Option<&str>) -> (Vec<Entry>, Vec<GuessPick>) {
    let mut entries = Vec::new();
    let mut picks = Vec::new();
    let mut push = |entries: &mut Vec<Entry>, label: String, pick: GuessPick| {
        entries.push(Entry::Item(Item { handle: picks.len() as i64, label, ..Item::default() }));
        picks.push(pick);
    };
    let (suggested, other): (Vec<_>, Vec<_>) = candidates.iter().partition(|(_, _, suggested)| *suggested);
    if !suggested.is_empty() {
        entries.push(Entry::Separator(Some("Suggested".into())));
        for (debug_type, label, _) in suggested {
            push(&mut entries, label.clone(), GuessPick::Debugger(debug_type.clone()));
        }
    }
    if !other.is_empty() {
        if !entries.is_empty() {
            entries.push(Entry::Separator(None));
        }
        for (debug_type, label, _) in other {
            push(&mut entries, label.clone(), GuessPick::Debugger(debug_type.clone()));
        }
    }
    if !dynamic.is_empty() {
        if !entries.is_empty() {
            entries.push(Entry::Separator(None));
        }
        for (debug_type, label) in dynamic {
            push(&mut entries, format!("More {label} options..."), GuessPick::Dynamic(debug_type.clone()));
        }
    }
    entries.push(Entry::Separator(None));
    let install = match language_label {
        Some(label) => format!("Install an extension for {label}..."),
        None => "Install extension...".to_owned(),
    };
    push(&mut entries, install, GuessPick::Install);
    for (command, title) in contributed {
        push(&mut entries, title.clone(), GuessPick::Command(command.clone()));
    }
    (entries, picks)
}

/// debugService.ts `startDebugging`: the debugger guessed for a file is remembered for it (`chosenEnvironments`),
/// with the dynamic configuration's name as `dynamicLabel`.
fn remember_chosen_environment(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, resource: Option<String>, debug_type: String, with_config: Option<(Option<PathBuf>, Value)>) -> Result<Option<(String, Option<(Option<PathBuf>, Value)>)>, String> {
    if let Some(resource) = resource {
        let mut chosen = json!({ "type": debug_type });
        if let Some((_, config)) = &with_config {
            chosen["dynamicLabel"] = config["name"].clone();
        }
        on_workbench(this, cx, |workbench, _, _| {
            workbench.debug.chosen_environments.insert(resource, chosen);
            let stored = Value::Object(workbench.debug.chosen_environments.clone()).to_string();
            workbench.workspace_storage.lock().unwrap().set(CHOSEN_ENVIRONMENTS_KEY, stored);
        })?;
    }
    Ok(Some((debug_type, with_config)))
}

/// debugConfigurationManager.ts `resolveConfigurationByProviders`: the type's providers then `*`'s, again while
/// a provider changes the type.
async fn resolve_by_providers(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, folder_uri: Option<Value>, debug_type: String, config: Value) -> Result<Option<Value>, String> {
    let mut resolved_type = config["type"].as_str().map(str::to_owned).unwrap_or(debug_type.clone());
    let mut result = Some(config);
    let mut seen = HashSet::new();
    while let Some(config) = result.clone() {
        if !seen.insert(resolved_type.clone()) {
            break;
        }
        let mut current = Some(config);
        for kind in [resolved_type.clone(), "*".to_owned()] {
            if kind != "*" {
                let events = on_workbench(this, cx, |workbench, _, _| {
                    workbench.debug.init_extension_activations();
                    ["onDebugResolve".to_owned(), "onDebug".to_owned(), format!("onDebugResolve:{kind}")].map(|event| workbench.host.activate_by_event(&event))
                })?;
                for event in events {
                    let _ = event.await;
                }
            }
            let handles = on_workbench(this, cx, |workbench, _, _| workbench.debug.providers.iter().filter(|provider| provider.debug_type == kind && provider.has_resolve).map(|provider| provider.handle).collect::<Vec<i64>>())?;
            for handle in handles {
                let Some(config) = current.take() else { break };
                let reply = on_workbench(this, cx, |workbench, _, _| workbench.host.call("ExtHostDebugService", "$resolveDebugConfiguration", vec![json!(handle), json!(folder_uri), config]))?;
                current = Some(answer(reply).await?).filter(|config| config.is_object());
            }
        }
        result = current;
        resolved_type = result.as_ref().and_then(|config| config["type"].as_str()).map(str::to_owned).unwrap_or(debug_type.clone());
    }
    Ok(result)
}

/// debugService.ts `substituteVariables`: through the extension host for a type it has an adapter for; `None` when
/// an input prompt is dismissed.
async fn substitute_variables(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, folder_uri: &Option<Value>, config: Value, inputs: &[Value]) -> Result<Option<Value>, String> {
    let debug_type = config["type"].as_str().unwrap_or_default().to_owned();
    let (registered, debugger) = on_workbench(this, cx, |workbench, _, _| (workbench.debug.adapter_types.contains(&debug_type), workbench.debug.debugger(&debug_type).cloned()))?;
    if !registered {
        return Ok(Some(config));
    }
    let reply = on_workbench(this, cx, |workbench, _, _| workbench.host.call("ExtHostDebugService", "$substituteVariables", vec![json!(folder_uri), config]))?;
    let config = answer(reply).await?;
    let commands = debugger.as_ref().and_then(|debugger| debugger.contribution["variables"].as_object().cloned()).unwrap_or_default();
    super::configuration_resolver::resolve_with_interaction_replace(this, cx, config, "launch", Some(inputs), &commands).await
}

/// debugConfigurationManager.ts `resolveDebugConfigurationWithSubstitutedVariables`: the type's providers then
/// `*`'s; `None` when one cancels.
async fn resolve_with_substituted_variables(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, folder_uri: &Option<Value>, mut config: Value) -> Result<Option<Value>, String> {
    let debug_type = config["type"].as_str().unwrap_or_default().to_owned();
    let handles = on_workbench(this, cx, |workbench, _, _| {
        let of_type = workbench.debug.providers.iter().filter(|provider| provider.debug_type == debug_type && provider.has_resolve2);
        let any = workbench.debug.providers.iter().filter(|provider| provider.debug_type == "*" && provider.has_resolve2);
        of_type.chain(any).map(|provider| provider.handle).collect::<Vec<i64>>()
    })?;
    for handle in handles {
        let reply = on_workbench(this, cx, |workbench, _, _| workbench.host.call("ExtHostDebugService", "$resolveDebugConfigurationWithSubstitutedVariables", vec![json!(handle), json!(folder_uri), config.clone()]))?;
        let Some(resolved) = Some(answer(reply).await?).filter(Value::is_object) else { return Ok(None) };
        config = resolved;
    }
    Ok(Some(config))
}
/// The rest of `createSession` after the providers: variables, `resolveDebugConfigurationWithSubstitutedVariables`,
/// the debugger check, then `doCreateSession` and `launchOrAttachToSession`.
#[allow(clippy::too_many_arguments)]
async fn finish_session(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, folder: Option<PathBuf>, folder_uri: Option<Value>, config: Value, unresolved: Value, options: Value, inputs: Vec<Value>, tasks: DebugTasks) -> Result<bool, String> {
    let debug_type = config["type"].as_str().unwrap_or_default().to_owned();
    let registered = on_workbench(this, cx, |workbench, _, _| workbench.debug.adapter_types.contains(&debug_type))?;
    let Some(mut config) = substitute_variables(this, cx, &folder_uri, config, &inputs).await? else { return Ok(false) };
    if !run_debug_tasks(this, cx, tasks, &config).await? {
        return Ok(false);
    }
    let Some(resolved) = resolve_with_substituted_variables(this, cx, &folder_uri, config).await? else { return Ok(false) };
    config = resolved;
    let request = config["request"].as_str();
    if request != Some("launch") && request != Some("attach") {
        return Err(match request {
            Some(request) => format!("Attribute 'request' has an unsupported value '{request}' in the chosen debug configuration."),
            None => "Attribute 'request' is missing from the chosen debug configuration.".into(),
        });
    }
    if !registered {
        return Err(match config["type"].as_str() {
            Some(debug_type) if !debug_type.is_empty() => format!("Configured debug type '{debug_type}' is not supported."),
            _ => "Missing property 'type' for the chosen launch configuration.".into(),
        });
    }
    let session_id = on_workbench(this, cx, |workbench, _, cx| {
        let id = crate::debug::generate_uuid();
        workbench.debug.next_handle += 1;
        let session = Session::new(id.clone(), workbench.debug.next_handle, config.clone(), unresolved, folder_uri.clone(), options.clone());
        // disassemblyView.ts `onDidChangeState`: a debug run that starts clears the view.
        if workbench.debug.state() == State::Inactive {
            workbench.clear_disassembly();
        }
        workbench.debug.add_session(session);
        // debug.openDebug: the view opens on the first session start, not for Run Without Debugging.
        let open_debug = workbench.setting("debug.openDebug");
        if config["noDebug"] != true && options["suppressDebugView"] != true && (open_debug == "openOnSessionStart" || open_debug == "openOnFirstSessionStart" && !workbench.debug.first_session_started) {
            workbench.show_debug_view(cx);
        }
        cx.notify();
        id
    })?;
    let _ = folder;
    match launch_or_attach(this, cx, &session_id).await {
        Ok(()) => {
            on_workbench(this, cx, |workbench, window, cx| {
                let console = config["internalConsoleOptions"].as_str().map(str::to_owned).unwrap_or_else(|| workbench.setting("debug.internalConsoleOptions").as_str().unwrap_or_default().to_owned());
                if console == "openOnSessionStart" || console == "openOnFirstSessionStart" && !workbench.debug.first_session_started {
                    workbench.open_debug_console(false, window, cx);
                }
                workbench.debug.first_session_started = true;
                if workbench.toolbar_sessions().len() > 1 {
                    workbench.debug.multi_session_view = true;
                }
                workbench.update_debug_status();
                let Some(session) = workbench.debug.session(&session_id) else { return };
                let dto = workbench.debug.session_dto(session);
                workbench.host.send("ExtHostDebugService", "$acceptDebugSessionStarted", vec![dto]);
                if workbench.debug.focus.session.is_none() {
                    let focus = workbench.debug.focus_target(Some(&session_id), None);
                    workbench.set_debug_focus(focus, Reveal::No, window, cx);
                }
                cx.notify();
            })?;
            Ok(true)
        }
        Err(error) => {
            on_workbench(this, cx, |workbench, window, cx| {
                drop(workbench.disconnect_session(session_id.clone(), false, Debuggee::Terminate, window, cx));
                if error.1 {
                    workbench.notify_error(error.0);
                }
            })?;
            Ok(false)
        }
    }
}

async fn restart_flow(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, session_id: &str, restart_data: Option<Value>) -> Result<(), String> {
    // debugSession.ts `saveBeforeRestart`: `options.saveBeforeRestart ?? !options.parentSession`.
    let save_before_restart = on_workbench(this, cx, |workbench, _, _| {
        let session = workbench.debug.session(session_id)?;
        Some(session.options["suppressSaveBeforeStart"].as_bool().map_or(session.parent.is_none(), |suppress| !suppress))
    })?;
    if save_before_restart == Some(true) {
        save_all_before_debug_start(this, cx).await?;
    }
    on_workbench(this, cx, |workbench, _, _| {
        for breakpoint in &mut workbench.debug.model.breakpoints {
            breakpoint.sessions_did_trigger.retain(|id| id != session_id);
        }
    })?;
    let tasks = if restart_data.is_some() { DebugTasks::None } else { DebugTasks::Restart };
    // An extension host session reloads its development window instead.
    let extension_host = on_workbench(this, cx, |workbench, _, _| Some((workbench.extension_host_debug_session(session_id)?.id.clone(), workbench.debug.session(session_id)?.configuration.clone())))?;
    if let Some((extension_session_id, configuration)) = extension_host {
        if run_debug_tasks(this, cx, tasks, &configuration).await? {
            on_workbench(this, cx, |_, _, cx| super::host::run_in_extension_development_host(&extension_session_id, "workbench.action.reloadWindow", cx))?;
        }
        return Ok(());
    }
    let found = on_workbench(this, cx, |workbench, _, _| {
        let session = workbench.debug.session(session_id)?;
        Some((session.folder_uri.clone(), session.configuration.clone(), session.unresolved_configuration.clone(), session.capabilities["supportsRestartRequest"] == true))
    })?;
    let Some((folder_uri, configuration, unresolved_before, supports_restart)) = found else { return Ok(()) };
    let launch = match folder_uri.as_ref().and_then(crate::debug::configuration_folder) {
        Some(folder) => Some(on_workbench(this, cx, |workbench, _, _| workbench.folder_launch(&folder))?),
        None => None,
    };
    // launch.json changed since the start: its configuration is resolved again, else the one in memory stays.
    let mut resolved = Some(configuration.clone());
    let name = configuration["name"].as_str().unwrap_or_default();
    if let Some(launch) = &launch
        && let Some(mut unresolved) = launch.configuration(name).filter(|unresolved| *unresolved != unresolved_before)
    {
        if let Some(no_debug) = configuration.get("noDebug") {
            unresolved["noDebug"] = no_debug.clone();
        }
        let debug_type = unresolved["type"].as_str().unwrap_or_default().to_owned();
        resolved = match resolve_by_providers(this, cx, folder_uri.clone(), debug_type, unresolved.clone()).await? {
            Some(by_providers) => match substitute_variables(this, cx, &folder_uri, by_providers, &launch.inputs).await? {
                Some(substituted) => resolve_with_substituted_variables(this, cx, &folder_uri, substituted).await?,
                None => None,
            },
            None => None,
        };
        if let Some(resolved) = &resolved {
            on_workbench(this, cx, |workbench, _, _| {
                if let Some(session) = workbench.debug.session_mut(session_id) {
                    session.configuration = resolved.clone();
                    session.unresolved_configuration = unresolved;
                }
            })?;
        }
    }
    let configuration = on_workbench(this, cx, |workbench, _, _| {
        let session = workbench.debug.session_mut(session_id)?;
        match &restart_data {
            Some(restart_data) => session.configuration["__restart"] = restart_data.clone(),
            None => drop(session.configuration.as_object_mut().and_then(|configuration| configuration.remove("__restart"))),
        }
        Some(session.configuration.clone())
    })?;
    let Some(configuration) = configuration else { return Ok(()) };
    if supports_restart {
        if run_debug_tasks(this, cx, tasks, &configuration).await? {
            let reply = on_workbench(this, cx, |workbench, _, _| workbench.restart_request(session_id))?;
            answer(reply).await?;
        }
        return Ok(());
    }
    let should_focus = on_workbench(this, cx, |workbench, _, _| workbench.debug.focus.session.as_deref() == Some(session_id))?;
    // #55064: an automatic restart disconnects, a restart by the user terminates.
    let stop = on_workbench(this, cx, |workbench, window, cx| match restart_data {
        Some(_) => workbench.disconnect_session(session_id.to_owned(), true, Debuggee::Keep, window, cx),
        None => workbench.terminate_session(session_id.to_owned(), true, window, cx),
    })?;
    let _ = stop.await;
    cx.background_executor().timer(std::time::Duration::from_millis(300)).await;
    if !run_debug_tasks(this, cx, tasks, &configuration).await? || resolved.is_none() {
        return Ok(());
    }
    on_workbench(this, cx, |workbench, window, cx| workbench.relaunch_session(session_id, window, cx))?;
    if let Err((message, show_user)) = launch_or_attach(this, cx, session_id).await {
        return on_workbench(this, cx, |workbench, window, cx| {
            drop(workbench.disconnect_session(session_id.to_owned(), false, Debuggee::Terminate, window, cx));
            if show_user {
                workbench.notify_error(message);
            }
        });
    }
    on_workbench(this, cx, |workbench, window, cx| {
        workbench.update_debug_status();
        if let Some(session) = workbench.debug.session(session_id) {
            let dto = workbench.debug.session_dto(session);
            workbench.host.send("ExtHostDebugService", "$acceptDebugSessionStarted", vec![dto]);
        }
        if should_focus || workbench.debug.focus.session.is_none() {
            let focus = workbench.debug.focus_target(Some(session_id), None);
            workbench.set_debug_focus(focus, Reveal::No, window, cx);
        }
        cx.notify();
    })
}

/// debugSession.ts `initialize` and `launchOrAttach`; the error and whether to show it (`showUser`).
async fn launch_or_attach(this: &WeakEntity<Workbench>, cx: &mut AsyncWindowContext, session_id: &str) -> Result<(), (String, bool)> {
    let start = on_workbench(this, cx, |workbench, _, _| {
        let session = workbench.debug.session(session_id)?;
        let dto = session.dto();
        Some(workbench.host.call("ExtHostDebugService", "$startDASession", vec![json!(session.handle), dto]))
    });
    let Ok(Some(start)) = start else { return Err(("Canceled".into(), false)) };
    answer(start).await.map_err(|message| (message, true))?;
    let initialize = on_workbench(this, cx, |workbench, _, _| {
        let adapter_id = workbench.debug.session(session_id).map(|session| session.session_type().to_owned()).unwrap_or_default();
        workbench.dap_request(
            session_id,
            "initialize",
            json!({
                "clientID": "vscode", "clientName": crate::product::name_long(), "adapterID": adapter_id, "pathFormat": "path",
                "linesStartAt1": true, "columnsStartAt1": true, "supportsVariableType": true, "supportsVariablePaging": true,
                "supportsRunInTerminalRequest": true, "locale": "en", "supportsProgressReporting": true, "supportsInvalidatedEvent": true,
                "supportsMemoryReferences": true, "supportsArgsCanBeInterpretedByShell": true, "supportsMemoryEvent": true,
                "supportsStartDebuggingRequest": true, "supportsANSIStyling": true,
            }),
        )
    })
    .map_err(|message| (message, false))?;
    let capabilities = initialize.await.unwrap_or(Err(Value::Null));
    let capabilities = capabilities.map_err(|error| (error_message(&error), error["showUser"] != false))?;
    let launch = on_workbench(this, cx, |workbench, window, cx| {
        let session = workbench.debug.session_mut(session_id)?;
        session.capabilities = if capabilities.is_object() { capabilities.clone() } else { json!({}) };
        session.initialized = true;
        let filters = session.capabilities["exceptionBreakpointFilters"].as_array().cloned().unwrap_or_default();
        // debugSession.ts `launchOrAttach`: js-debug passes the id to an extension host it launches as `--debugId`.
        session.configuration["__sessionId"] = json!(session_id);
        let (request, configuration) = (session.configuration["request"].as_str().unwrap_or("launch").to_owned(), session.configuration.clone());
        workbench.debug.model.set_exception_breakpoints_for_session(session_id, &filters);
        workbench.store_debug_model();
        cx.notify();
        let launch = workbench.dap_request(session_id, &request, configuration);
        if workbench.debug.session_mut(session_id).is_some_and(|session| std::mem::take(&mut session.initialized_event_pending)) {
            workbench.session_initialized(session_id.to_owned(), window, cx);
        }
        Some(launch)
    });
    let Ok(Some(launch)) = launch else { return Err(("Canceled".into(), false)) };
    // debugSession.ts `shutdown` drops a connection without answering its requests: the launch an attach replaced
    // (`attach_session`) waits on, as upstream's does.
    let Ok(result) = launch.await else { return std::future::pending().await };
    match result {
        Ok(_) => Ok(()),
        Err(error) => Err((error_message(&error), error["showUser"] != false)),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn rows(entries: &[Entry]) -> Vec<String> {
        entries.iter().map(|entry| match entry {
            Entry::Item(item) => format!("{}:{}", item.handle, item.label),
            Entry::Separator(label) => format!("--{}--", label.as_deref().unwrap_or_default()),
            Entry::Header(_) => unreachable!(),
        }).collect()
    }

    /// debugAdapterManager.ts `guessDebugger`: the Suggested section, an unlabelled one for the others, one for the
    /// dynamic providers, then Install and the `DebugCreateConfiguration` items after a separator.
    #[test]
    fn the_select_debugger_picks_group_the_suggested_debuggers() {
        let candidates = [("node".to_owned(), "Node.js".to_owned(), true), ("chrome".to_owned(), "Web App (Chrome)".to_owned(), false)];
        let contributed = [("x.create".to_owned(), "Create X Configuration".to_owned())];
        let dynamic = [("node".to_owned(), "Node.js".to_owned())];
        let (entries, picks) = select_debugger_picks(&candidates, &dynamic, &contributed, Some("JavaScript"));
        assert_eq!(rows(&entries), ["--Suggested--", "0:Node.js", "----", "1:Web App (Chrome)", "----", "2:More Node.js options...", "----", "3:Install an extension for JavaScript...", "4:Create X Configuration"]);
        assert!(matches!(&picks[1], GuessPick::Debugger(debug_type) if debug_type == "chrome"));
        assert!(matches!(&picks[2], GuessPick::Dynamic(debug_type) if debug_type == "node"));
        assert!(matches!(picks[3], GuessPick::Install));
        assert!(matches!(&picks[4], GuessPick::Command(command) if command == "x.create"));

        let (entries, _) = select_debugger_picks(&candidates[1..], &[], &[], None);
        assert_eq!(rows(&entries), ["0:Web App (Chrome)", "----", "1:Install extension..."]);
    }

    /// debugAdapterManager.ts `guessDebugger`: no debugger for the file's language asks to find one, and the confirmed
    /// dialog searches the Extensions view (debugCommands.ts `debug.installAdditionalDebuggers`).
    #[gpui::test]
    fn a_file_without_a_debugger_offers_to_find_an_extension_for_its_language(cx: &mut gpui::TestAppContext) {
        let app_root = std::path::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, host) = std::sync::mpsc::channel();
        let (workbench, cx) = cx.add_window_view(|_, cx| {
            let mut workbench = Workbench::new(theme, app_root.clone(), None, crate::languages::Languages::new(&[]), crate::default_settings(), crate::host_sync::HostSync::new(sender), cx);
            workbench.skip_dialogs = true;
            workbench
        });
        let dir = std::env::temp_dir().join(format!("code-gpui-guess-debugger-{}", std::process::id()));
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("notes.txt"), "notes").unwrap();
        workbench.update_in(cx, |workbench, window, cx| workbench.open_file(dir.join("notes.txt"), true, window, cx));
        workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.debug.start", Vec::new(), window, cx)));
        for _ in 0..5 {
            cx.run_until_parked();
            for message in host.try_iter() {
                if let Some(reply) = message.reply {
                    let _ = reply.send(Ok(Value::Null));
                }
            }
        }
        assert_eq!(workbench.read_with(cx, |workbench, _| workbench.extensions_viewlet.search.value.clone()), "@category:debuggers 'Plain Text'");
        std::fs::remove_dir_all(dir).unwrap();
    }

    /// debugSession.ts `handleStop`: `openOnDebugBreak` opens the view only for a `breakpoint` stop, and not with `suppressDebugView`.
    #[gpui::test]
    fn only_a_breakpoint_stop_opens_the_run_and_debug_view(cx: &mut gpui::TestAppContext) {
        use super::super::search_view::SideBarView;
        let app_root = std::path::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, host) = 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));
        let mut view_after_stop = |reason: &str, options: Value| {
            workbench.update_in(cx, |workbench, _, _| {
                let mut session = crate::debug::session::Session::new("s".into(), 1, json!({ "name": "s", "type": "node", "request": "launch" }), json!({}), None, options);
                session.initialized = true;
                workbench.debug.sessions = vec![session];
                workbench.side_bar_view = SideBarView::Explorer;
            });
            let accept = |message: Value| exthost::session::ForwardedRequest { req: 1, proxy: "MainThreadDebugService", method: "$acceptDAMessage".into(), args: vec![json!(1), message] };
            let stopped = json!({ "type": "event", "seq": 0, "event": "stopped", "body": { "reason": reason, "threadId": 1 } });
            workbench.update_in(cx, |workbench, window, cx| drop(workbench.handle_debug_request(accept(stopped), window, cx)));
            for (command, body) in [("threads", json!({ "threads": [{ "id": 1, "name": "main" }] })), ("stackTrace", json!({ "stackFrames": [] }))] {
                cx.run_until_parked();
                let request = host.try_iter().filter(|message| message.method == "$sendDAMessage").map(|message| message.args[1].clone()).find(|request| request["command"] == command).unwrap();
                let response = json!({ "type": "response", "seq": 0, "request_seq": request["seq"], "success": true, "command": command, "body": body });
                workbench.update_in(cx, |workbench, window, cx| drop(workbench.handle_debug_request(accept(response), window, cx)));
            }
            cx.run_until_parked();
            workbench.read_with(cx, |workbench, _| workbench.side_bar_view)
        };
        assert_eq!(view_after_stop("debugger statement", json!({})), SideBarView::Explorer);
        assert_eq!(view_after_stop("breakpoint", json!({ "suppressDebugView": true })), SideBarView::Explorer);
        assert_eq!(view_after_stop("breakpoint", json!({})), SideBarView::Debug);
    }
}