dap_store.rs

   1use super::{
   2    breakpoint_store::BreakpointStore,
   3    dap_command::EvaluateCommand,
   4    locators,
   5    session::{self, Session, SessionStateEvent},
   6};
   7use crate::{
   8    InlayHint, InlayHintLabel, ProjectEnvironment, ResolveState,
   9    debugger::session::SessionQuirks,
  10    project_settings::{DapBinary, ProjectSettings},
  11    worktree_store::WorktreeStore,
  12};
  13use anyhow::{Context as _, Result, anyhow};
  14use async_trait::async_trait;
  15use collections::HashMap;
  16use dap::{
  17    Capabilities, DapRegistry, DebugRequest, EvaluateArgumentsContext, StackFrameId,
  18    adapters::{
  19        DapDelegate, DebugAdapterBinary, DebugAdapterName, DebugTaskDefinition, TcpArguments,
  20    },
  21    client::SessionId,
  22    inline_value::VariableLookupKind,
  23    messages::Message,
  24};
  25use fs::{Fs, RemoveOptions};
  26use futures::{
  27    StreamExt, TryStreamExt as _,
  28    channel::mpsc::{self, UnboundedSender},
  29    future::{Shared, join_all},
  30};
  31use gpui::{App, AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task};
  32use http_client::HttpClient;
  33use language::{Buffer, LanguageToolchainStore};
  34use node_runtime::NodeRuntime;
  35use settings::InlayHintKind;
  36
  37use remote::RemoteClient;
  38use rpc::{
  39    AnyProtoClient, TypedEnvelope,
  40    proto::{self},
  41};
  42use serde::{Deserialize, Serialize};
  43use settings::{Settings, SettingsLocation, WorktreeId};
  44use std::{
  45    borrow::Borrow,
  46    collections::BTreeMap,
  47    ffi::OsStr,
  48    net::Ipv4Addr,
  49    path::{Path, PathBuf},
  50    sync::{Arc, Once},
  51};
  52use task::{DebugScenario, SpawnInTerminal, TaskContext, TaskTemplate};
  53use util::{ResultExt as _, rel_path::RelPath};
  54use worktree::Worktree;
  55
  56#[derive(Debug)]
  57pub enum DapStoreEvent {
  58    DebugClientStarted(SessionId),
  59    DebugSessionInitialized(SessionId),
  60    DebugClientShutdown(SessionId),
  61    DebugClientEvent {
  62        session_id: SessionId,
  63        message: Message,
  64    },
  65    Notification(String),
  66    RemoteHasInitialized,
  67}
  68
  69enum DapStoreMode {
  70    Local(LocalDapStore),
  71    Remote(RemoteDapStore),
  72    Collab,
  73}
  74
  75pub struct LocalDapStore {
  76    fs: Arc<dyn Fs>,
  77    node_runtime: NodeRuntime,
  78    http_client: Arc<dyn HttpClient>,
  79    environment: Entity<ProjectEnvironment>,
  80    toolchain_store: Arc<dyn LanguageToolchainStore>,
  81    is_headless: bool,
  82}
  83
  84pub struct RemoteDapStore {
  85    remote_client: Entity<RemoteClient>,
  86    upstream_client: AnyProtoClient,
  87    upstream_project_id: u64,
  88    node_runtime: NodeRuntime,
  89    http_client: Arc<dyn HttpClient>,
  90}
  91
  92pub struct DapStore {
  93    mode: DapStoreMode,
  94    downstream_client: Option<(AnyProtoClient, u64)>,
  95    breakpoint_store: Entity<BreakpointStore>,
  96    worktree_store: Entity<WorktreeStore>,
  97    sessions: BTreeMap<SessionId, Entity<Session>>,
  98    next_session_id: u32,
  99    adapter_options: BTreeMap<DebugAdapterName, Arc<PersistedAdapterOptions>>,
 100}
 101
 102impl EventEmitter<DapStoreEvent> for DapStore {}
 103
 104#[derive(Clone, Serialize, Deserialize)]
 105pub struct PersistedExceptionBreakpoint {
 106    pub enabled: bool,
 107}
 108
 109/// Represents best-effort serialization of adapter state during last session (e.g. watches)
 110#[derive(Clone, Default, Serialize, Deserialize)]
 111pub struct PersistedAdapterOptions {
 112    /// Which exception breakpoints were enabled during the last session with this adapter?
 113    pub exception_breakpoints: BTreeMap<String, PersistedExceptionBreakpoint>,
 114}
 115
 116impl DapStore {
 117    pub fn init(client: &AnyProtoClient, cx: &mut App) {
 118        static ADD_LOCATORS: Once = Once::new();
 119        ADD_LOCATORS.call_once(|| {
 120            let registry = DapRegistry::global(cx);
 121            registry.add_locator(Arc::new(locators::cargo::CargoLocator {}));
 122            registry.add_locator(Arc::new(locators::go::GoLocator {}));
 123            registry.add_locator(Arc::new(locators::node::NodeLocator));
 124            registry.add_locator(Arc::new(locators::python::PythonLocator));
 125        });
 126        client.add_entity_request_handler(Self::handle_run_debug_locator);
 127        client.add_entity_request_handler(Self::handle_get_debug_adapter_binary);
 128        client.add_entity_message_handler(Self::handle_log_to_debug_console);
 129    }
 130
 131    #[expect(clippy::too_many_arguments)]
 132    pub fn new_local(
 133        http_client: Arc<dyn HttpClient>,
 134        node_runtime: NodeRuntime,
 135        fs: Arc<dyn Fs>,
 136        environment: Entity<ProjectEnvironment>,
 137        toolchain_store: Arc<dyn LanguageToolchainStore>,
 138        worktree_store: Entity<WorktreeStore>,
 139        breakpoint_store: Entity<BreakpointStore>,
 140        is_headless: bool,
 141        cx: &mut Context<Self>,
 142    ) -> Self {
 143        let mode = DapStoreMode::Local(LocalDapStore {
 144            fs: fs.clone(),
 145            environment,
 146            http_client,
 147            node_runtime,
 148            toolchain_store,
 149            is_headless,
 150        });
 151
 152        Self::new(mode, breakpoint_store, worktree_store, fs, cx)
 153    }
 154
 155    pub fn new_remote(
 156        project_id: u64,
 157        remote_client: Entity<RemoteClient>,
 158        breakpoint_store: Entity<BreakpointStore>,
 159        worktree_store: Entity<WorktreeStore>,
 160        node_runtime: NodeRuntime,
 161        http_client: Arc<dyn HttpClient>,
 162        fs: Arc<dyn Fs>,
 163        cx: &mut Context<Self>,
 164    ) -> Self {
 165        let mode = DapStoreMode::Remote(RemoteDapStore {
 166            upstream_client: remote_client.read(cx).proto_client(),
 167            remote_client,
 168            upstream_project_id: project_id,
 169            node_runtime,
 170            http_client,
 171        });
 172
 173        Self::new(mode, breakpoint_store, worktree_store, fs, cx)
 174    }
 175
 176    pub fn new_collab(
 177        _project_id: u64,
 178        _upstream_client: AnyProtoClient,
 179        breakpoint_store: Entity<BreakpointStore>,
 180        worktree_store: Entity<WorktreeStore>,
 181        fs: Arc<dyn Fs>,
 182        cx: &mut Context<Self>,
 183    ) -> Self {
 184        Self::new(
 185            DapStoreMode::Collab,
 186            breakpoint_store,
 187            worktree_store,
 188            fs,
 189            cx,
 190        )
 191    }
 192
 193    fn new(
 194        mode: DapStoreMode,
 195        breakpoint_store: Entity<BreakpointStore>,
 196        worktree_store: Entity<WorktreeStore>,
 197        fs: Arc<dyn Fs>,
 198        cx: &mut Context<Self>,
 199    ) -> Self {
 200        cx.background_spawn(async move {
 201            let dir = paths::debug_adapters_dir().join("js-debug-companion");
 202
 203            let mut children = fs.read_dir(&dir).await?.try_collect::<Vec<_>>().await?;
 204            children.sort_by_key(|child| semver::Version::parse(child.file_name()?.to_str()?).ok());
 205
 206            if let Some(child) = children.last()
 207                && let Some(name) = child.file_name()
 208                && let Some(name) = name.to_str()
 209                && semver::Version::parse(name).is_ok()
 210            {
 211                children.pop();
 212            }
 213
 214            for child in children {
 215                fs.remove_dir(
 216                    &child,
 217                    RemoveOptions {
 218                        recursive: true,
 219                        ignore_if_not_exists: true,
 220                    },
 221                )
 222                .await
 223                .ok();
 224            }
 225
 226            anyhow::Ok(())
 227        })
 228        .detach();
 229
 230        Self {
 231            mode,
 232            next_session_id: 0,
 233            downstream_client: None,
 234            breakpoint_store,
 235            worktree_store,
 236            sessions: Default::default(),
 237            adapter_options: Default::default(),
 238        }
 239    }
 240
 241    pub fn get_debug_adapter_binary(
 242        &mut self,
 243        definition: DebugTaskDefinition,
 244        session_id: SessionId,
 245        worktree: &Entity<Worktree>,
 246        console: UnboundedSender<String>,
 247        cx: &mut Context<Self>,
 248    ) -> Task<Result<DebugAdapterBinary>> {
 249        match &self.mode {
 250            DapStoreMode::Local(_) => {
 251                let Some(adapter) = DapRegistry::global(cx).adapter(&definition.adapter) else {
 252                    return Task::ready(Err(anyhow!("Failed to find a debug adapter")));
 253                };
 254
 255                let settings_location = SettingsLocation {
 256                    worktree_id: worktree.read(cx).id(),
 257                    path: RelPath::empty(),
 258                };
 259                let dap_settings = ProjectSettings::get(Some(settings_location), cx)
 260                    .dap
 261                    .get(&adapter.name());
 262                let user_installed_path = dap_settings.and_then(|s| match &s.binary {
 263                    DapBinary::Default => None,
 264                    DapBinary::Custom(binary) => Some(PathBuf::from(binary)),
 265                });
 266                let user_args = dap_settings.map(|s| s.args.clone());
 267
 268                let delegate = self.delegate(worktree, console, cx);
 269                let cwd: Arc<Path> = worktree.read(cx).abs_path().as_ref().into();
 270
 271                cx.spawn(async move |this, cx| {
 272                    let mut binary = adapter
 273                        .get_binary(&delegate, &definition, user_installed_path, user_args, cx)
 274                        .await?;
 275
 276                    let env = this
 277                        .update(cx, |this, cx| {
 278                            this.as_local()
 279                                .unwrap()
 280                                .environment
 281                                .update(cx, |environment, cx| {
 282                                    environment.get_directory_environment(cwd, cx)
 283                                })
 284                        })?
 285                        .await;
 286
 287                    if let Some(mut env) = env {
 288                        env.extend(std::mem::take(&mut binary.envs));
 289                        binary.envs = env;
 290                    }
 291
 292                    Ok(binary)
 293                })
 294            }
 295            DapStoreMode::Remote(remote) => {
 296                let request = remote
 297                    .upstream_client
 298                    .request(proto::GetDebugAdapterBinary {
 299                        session_id: session_id.to_proto(),
 300                        project_id: remote.upstream_project_id,
 301                        worktree_id: worktree.read(cx).id().to_proto(),
 302                        definition: Some(definition.to_proto()),
 303                    });
 304                let remote = remote.remote_client.clone();
 305
 306                cx.spawn(async move |_, cx| {
 307                    let response = request.await?;
 308                    let binary = DebugAdapterBinary::from_proto(response)?;
 309
 310                    let port_forwarding;
 311                    let connection;
 312                    if let Some(c) = binary.connection {
 313                        let host = Ipv4Addr::LOCALHOST;
 314                        let port;
 315                        if remote.read_with(cx, |remote, _cx| remote.shares_network_interface())? {
 316                            port = c.port;
 317                            port_forwarding = None;
 318                        } else {
 319                            port = dap::transport::TcpTransport::unused_port(host).await?;
 320                            port_forwarding = Some((port, c.host.to_string(), c.port));
 321                        }
 322                        connection = Some(TcpArguments {
 323                            port,
 324                            host,
 325                            timeout: c.timeout,
 326                        })
 327                    } else {
 328                        port_forwarding = None;
 329                        connection = None;
 330                    }
 331
 332                    let command = remote.read_with(cx, |remote, _cx| {
 333                        remote.build_command(
 334                            binary.command,
 335                            &binary.arguments,
 336                            &binary.envs,
 337                            binary.cwd.map(|path| path.display().to_string()),
 338                            port_forwarding,
 339                        )
 340                    })??;
 341
 342                    Ok(DebugAdapterBinary {
 343                        command: Some(command.program),
 344                        arguments: command.args,
 345                        envs: command.env,
 346                        cwd: None,
 347                        connection,
 348                        request_args: binary.request_args,
 349                    })
 350                })
 351            }
 352            DapStoreMode::Collab => {
 353                Task::ready(Err(anyhow!("Debugging is not yet supported via collab")))
 354            }
 355        }
 356    }
 357
 358    pub fn debug_scenario_for_build_task(
 359        &self,
 360        build: TaskTemplate,
 361        adapter: DebugAdapterName,
 362        label: SharedString,
 363        cx: &mut App,
 364    ) -> Task<Option<DebugScenario>> {
 365        let locators = DapRegistry::global(cx).locators();
 366
 367        cx.background_spawn(async move {
 368            for locator in locators.values() {
 369                if let Some(scenario) = locator.create_scenario(&build, &label, &adapter).await {
 370                    return Some(scenario);
 371                }
 372            }
 373            None
 374        })
 375    }
 376
 377    pub fn run_debug_locator(
 378        &mut self,
 379        locator_name: &str,
 380        build_command: SpawnInTerminal,
 381        cx: &mut Context<Self>,
 382    ) -> Task<Result<DebugRequest>> {
 383        match &self.mode {
 384            DapStoreMode::Local(_) => {
 385                // Pre-resolve args with existing environment.
 386                let locators = DapRegistry::global(cx).locators();
 387                let locator = locators.get(locator_name);
 388
 389                if let Some(locator) = locator.cloned() {
 390                    cx.background_spawn(async move {
 391                        let result = locator
 392                            .run(build_command.clone())
 393                            .await
 394                            .log_with_level(log::Level::Error);
 395                        if let Some(result) = result {
 396                            return Ok(result);
 397                        }
 398
 399                        anyhow::bail!(
 400                            "None of the locators for task `{}` completed successfully",
 401                            build_command.label
 402                        )
 403                    })
 404                } else {
 405                    Task::ready(Err(anyhow!(
 406                        "Couldn't find any locator for task `{}`. Specify the `attach` or `launch` arguments in your debug scenario definition",
 407                        build_command.label
 408                    )))
 409                }
 410            }
 411            DapStoreMode::Remote(remote) => {
 412                let request = remote.upstream_client.request(proto::RunDebugLocators {
 413                    project_id: remote.upstream_project_id,
 414                    build_command: Some(build_command.to_proto()),
 415                    locator: locator_name.to_owned(),
 416                });
 417                cx.background_spawn(async move {
 418                    let response = request.await?;
 419                    DebugRequest::from_proto(response)
 420                })
 421            }
 422            DapStoreMode::Collab => {
 423                Task::ready(Err(anyhow!("Debugging is not yet supported via collab")))
 424            }
 425        }
 426    }
 427
 428    fn as_local(&self) -> Option<&LocalDapStore> {
 429        match &self.mode {
 430            DapStoreMode::Local(local_dap_store) => Some(local_dap_store),
 431            _ => None,
 432        }
 433    }
 434
 435    pub fn new_session(
 436        &mut self,
 437        label: Option<SharedString>,
 438        adapter: DebugAdapterName,
 439        task_context: TaskContext,
 440        parent_session: Option<Entity<Session>>,
 441        quirks: SessionQuirks,
 442        cx: &mut Context<Self>,
 443    ) -> Entity<Session> {
 444        let session_id = SessionId(util::post_inc(&mut self.next_session_id));
 445
 446        if let Some(session) = &parent_session {
 447            session.update(cx, |session, _| {
 448                session.add_child_session_id(session_id);
 449            });
 450        }
 451
 452        let (remote_client, node_runtime, http_client) = match &self.mode {
 453            DapStoreMode::Local(_) => (None, None, None),
 454            DapStoreMode::Remote(remote_dap_store) => (
 455                Some(remote_dap_store.remote_client.clone()),
 456                Some(remote_dap_store.node_runtime.clone()),
 457                Some(remote_dap_store.http_client.clone()),
 458            ),
 459            DapStoreMode::Collab => (None, None, None),
 460        };
 461        let session = Session::new(
 462            self.breakpoint_store.clone(),
 463            session_id,
 464            parent_session,
 465            label,
 466            adapter,
 467            task_context,
 468            quirks,
 469            remote_client,
 470            node_runtime,
 471            http_client,
 472            cx,
 473        );
 474
 475        self.sessions.insert(session_id, session.clone());
 476        cx.notify();
 477
 478        cx.subscribe(&session, {
 479            move |this: &mut DapStore, _, event: &SessionStateEvent, cx| match event {
 480                SessionStateEvent::Shutdown => {
 481                    this.shutdown_session(session_id, cx).detach_and_log_err(cx);
 482                }
 483                SessionStateEvent::Restart | SessionStateEvent::SpawnChildSession { .. } => {}
 484                SessionStateEvent::Running => {
 485                    cx.emit(DapStoreEvent::DebugClientStarted(session_id));
 486                }
 487            }
 488        })
 489        .detach();
 490
 491        session
 492    }
 493
 494    pub fn boot_session(
 495        &self,
 496        session: Entity<Session>,
 497        definition: DebugTaskDefinition,
 498        worktree: Entity<Worktree>,
 499        cx: &mut Context<Self>,
 500    ) -> Task<Result<()>> {
 501        let dap_store = cx.weak_entity();
 502        let console = session.update(cx, |session, cx| session.console_output(cx));
 503        let session_id = session.read(cx).session_id();
 504
 505        cx.spawn({
 506            let session = session.clone();
 507            async move |this, cx| {
 508                let binary = this
 509                    .update(cx, |this, cx| {
 510                        this.get_debug_adapter_binary(
 511                            definition.clone(),
 512                            session_id,
 513                            &worktree,
 514                            console,
 515                            cx,
 516                        )
 517                    })?
 518                    .await?;
 519                session
 520                    .update(cx, |session, cx| {
 521                        session.boot(binary, worktree, dap_store, cx)
 522                    })?
 523                    .await
 524            }
 525        })
 526    }
 527
 528    pub fn session_by_id(
 529        &self,
 530        session_id: impl Borrow<SessionId>,
 531    ) -> Option<Entity<session::Session>> {
 532        let session_id = session_id.borrow();
 533
 534        self.sessions.get(session_id).cloned()
 535    }
 536    pub fn sessions(&self) -> impl Iterator<Item = &Entity<Session>> {
 537        self.sessions.values()
 538    }
 539
 540    pub fn capabilities_by_id(
 541        &self,
 542        session_id: impl Borrow<SessionId>,
 543        cx: &App,
 544    ) -> Option<Capabilities> {
 545        let session_id = session_id.borrow();
 546        self.sessions
 547            .get(session_id)
 548            .map(|client| client.read(cx).capabilities.clone())
 549    }
 550
 551    pub fn breakpoint_store(&self) -> &Entity<BreakpointStore> {
 552        &self.breakpoint_store
 553    }
 554
 555    pub fn worktree_store(&self) -> &Entity<WorktreeStore> {
 556        &self.worktree_store
 557    }
 558
 559    #[allow(dead_code)]
 560    async fn handle_ignore_breakpoint_state(
 561        this: Entity<Self>,
 562        envelope: TypedEnvelope<proto::IgnoreBreakpointState>,
 563        mut cx: AsyncApp,
 564    ) -> Result<()> {
 565        let session_id = SessionId::from_proto(envelope.payload.session_id);
 566
 567        this.update(&mut cx, |this, cx| {
 568            if let Some(session) = this.session_by_id(&session_id) {
 569                session.update(cx, |session, cx| {
 570                    session.set_ignore_breakpoints(envelope.payload.ignore, cx)
 571                })
 572            } else {
 573                Task::ready(HashMap::default())
 574            }
 575        })?
 576        .await;
 577
 578        Ok(())
 579    }
 580
 581    fn delegate(
 582        &self,
 583        worktree: &Entity<Worktree>,
 584        console: UnboundedSender<String>,
 585        cx: &mut App,
 586    ) -> Arc<dyn DapDelegate> {
 587        let Some(local_store) = self.as_local() else {
 588            unimplemented!("Starting session on remote side");
 589        };
 590
 591        Arc::new(DapAdapterDelegate::new(
 592            local_store.fs.clone(),
 593            worktree.read(cx).snapshot(),
 594            console,
 595            local_store.node_runtime.clone(),
 596            local_store.http_client.clone(),
 597            local_store.toolchain_store.clone(),
 598            local_store.environment.update(cx, |env, cx| {
 599                env.get_worktree_environment(worktree.clone(), cx)
 600            }),
 601            local_store.is_headless,
 602        ))
 603    }
 604
 605    pub fn resolve_inline_value_locations(
 606        &self,
 607        session: Entity<Session>,
 608        stack_frame_id: StackFrameId,
 609        buffer_handle: Entity<Buffer>,
 610        inline_value_locations: Vec<dap::inline_value::InlineValueLocation>,
 611        cx: &mut Context<Self>,
 612    ) -> Task<Result<Vec<InlayHint>>> {
 613        let snapshot = buffer_handle.read(cx).snapshot();
 614        let local_variables =
 615            session
 616                .read(cx)
 617                .variables_by_stack_frame_id(stack_frame_id, false, true);
 618        let global_variables =
 619            session
 620                .read(cx)
 621                .variables_by_stack_frame_id(stack_frame_id, true, false);
 622
 623        fn format_value(mut value: String) -> String {
 624            const LIMIT: usize = 100;
 625
 626            if let Some(index) = value.find("\n") {
 627                value.truncate(index);
 628                value.push_str("");
 629            }
 630
 631            if value.len() > LIMIT {
 632                let mut index = LIMIT;
 633                // If index isn't a char boundary truncate will cause a panic
 634                while !value.is_char_boundary(index) {
 635                    index -= 1;
 636                }
 637                value.truncate(index);
 638                value.push_str("");
 639            }
 640
 641            format!(": {}", value)
 642        }
 643
 644        cx.spawn(async move |_, cx| {
 645            let mut inlay_hints = Vec::with_capacity(inline_value_locations.len());
 646            for inline_value_location in inline_value_locations.iter() {
 647                let point = snapshot.point_to_point_utf16(language::Point::new(
 648                    inline_value_location.row as u32,
 649                    inline_value_location.column as u32,
 650                ));
 651                let position = snapshot.anchor_after(point);
 652
 653                match inline_value_location.lookup {
 654                    VariableLookupKind::Variable => {
 655                        let variable_search =
 656                            if inline_value_location.scope
 657                                == dap::inline_value::VariableScope::Local
 658                            {
 659                                local_variables.iter().chain(global_variables.iter()).find(
 660                                    |variable| variable.name == inline_value_location.variable_name,
 661                                )
 662                            } else {
 663                                global_variables.iter().find(|variable| {
 664                                    variable.name == inline_value_location.variable_name
 665                                })
 666                            };
 667
 668                        let Some(variable) = variable_search else {
 669                            continue;
 670                        };
 671
 672                        inlay_hints.push(InlayHint {
 673                            position,
 674                            label: InlayHintLabel::String(format_value(variable.value.clone())),
 675                            kind: Some(InlayHintKind::Type),
 676                            padding_left: false,
 677                            padding_right: false,
 678                            tooltip: None,
 679                            resolve_state: ResolveState::Resolved,
 680                        });
 681                    }
 682                    VariableLookupKind::Expression => {
 683                        let Ok(eval_task) = session.read_with(cx, |session, _| {
 684                            session.mode.request_dap(EvaluateCommand {
 685                                expression: inline_value_location.variable_name.clone(),
 686                                frame_id: Some(stack_frame_id),
 687                                source: None,
 688                                context: Some(EvaluateArgumentsContext::Variables),
 689                            })
 690                        }) else {
 691                            continue;
 692                        };
 693
 694                        if let Some(response) = eval_task.await.log_err() {
 695                            inlay_hints.push(InlayHint {
 696                                position,
 697                                label: InlayHintLabel::String(format_value(response.result)),
 698                                kind: Some(InlayHintKind::Type),
 699                                padding_left: false,
 700                                padding_right: false,
 701                                tooltip: None,
 702                                resolve_state: ResolveState::Resolved,
 703                            });
 704                        };
 705                    }
 706                };
 707            }
 708
 709            Ok(inlay_hints)
 710        })
 711    }
 712
 713    pub fn shutdown_sessions(&mut self, cx: &mut Context<Self>) -> Task<()> {
 714        let mut tasks = vec![];
 715        for session_id in self.sessions.keys().cloned().collect::<Vec<_>>() {
 716            tasks.push(self.shutdown_session(session_id, cx));
 717        }
 718
 719        cx.background_executor().spawn(async move {
 720            futures::future::join_all(tasks).await;
 721        })
 722    }
 723
 724    pub fn shutdown_session(
 725        &mut self,
 726        session_id: SessionId,
 727        cx: &mut Context<Self>,
 728    ) -> Task<Result<()>> {
 729        let Some(session) = self.sessions.remove(&session_id) else {
 730            return Task::ready(Err(anyhow!("Could not find session: {:?}", session_id)));
 731        };
 732
 733        let shutdown_children = session
 734            .read(cx)
 735            .child_session_ids()
 736            .iter()
 737            .map(|session_id| self.shutdown_session(*session_id, cx))
 738            .collect::<Vec<_>>();
 739
 740        let shutdown_parent_task = if let Some(parent_session) = session
 741            .read(cx)
 742            .parent_id(cx)
 743            .and_then(|session_id| self.session_by_id(session_id))
 744        {
 745            let shutdown_id = parent_session.update(cx, |parent_session, _| {
 746                parent_session.remove_child_session_id(session_id);
 747
 748                if parent_session.child_session_ids().is_empty() {
 749                    Some(parent_session.session_id())
 750                } else {
 751                    None
 752                }
 753            });
 754
 755            shutdown_id.map(|session_id| self.shutdown_session(session_id, cx))
 756        } else {
 757            None
 758        };
 759
 760        let shutdown_task = session.update(cx, |this, cx| this.shutdown(cx));
 761
 762        cx.emit(DapStoreEvent::DebugClientShutdown(session_id));
 763
 764        cx.background_spawn(async move {
 765            if !shutdown_children.is_empty() {
 766                let _ = join_all(shutdown_children).await;
 767            }
 768
 769            shutdown_task.await;
 770
 771            if let Some(parent_task) = shutdown_parent_task {
 772                parent_task.await?;
 773            }
 774
 775            Ok(())
 776        })
 777    }
 778
 779    pub fn shared(
 780        &mut self,
 781        project_id: u64,
 782        downstream_client: AnyProtoClient,
 783        _: &mut Context<Self>,
 784    ) {
 785        self.downstream_client = Some((downstream_client, project_id));
 786    }
 787
 788    pub fn unshared(&mut self, cx: &mut Context<Self>) {
 789        self.downstream_client.take();
 790
 791        cx.notify();
 792    }
 793
 794    async fn handle_run_debug_locator(
 795        this: Entity<Self>,
 796        envelope: TypedEnvelope<proto::RunDebugLocators>,
 797        mut cx: AsyncApp,
 798    ) -> Result<proto::DebugRequest> {
 799        let task = envelope
 800            .payload
 801            .build_command
 802            .context("missing definition")?;
 803        let build_task = SpawnInTerminal::from_proto(task);
 804        let locator = envelope.payload.locator;
 805        let request = this
 806            .update(&mut cx, |this, cx| {
 807                this.run_debug_locator(&locator, build_task, cx)
 808            })?
 809            .await?;
 810
 811        Ok(request.to_proto())
 812    }
 813
 814    async fn handle_get_debug_adapter_binary(
 815        this: Entity<Self>,
 816        envelope: TypedEnvelope<proto::GetDebugAdapterBinary>,
 817        mut cx: AsyncApp,
 818    ) -> Result<proto::DebugAdapterBinary> {
 819        let definition = DebugTaskDefinition::from_proto(
 820            envelope.payload.definition.context("missing definition")?,
 821        )?;
 822        let (tx, mut rx) = mpsc::unbounded();
 823        let session_id = envelope.payload.session_id;
 824        cx.spawn({
 825            let this = this.clone();
 826            async move |cx| {
 827                while let Some(message) = rx.next().await {
 828                    this.read_with(cx, |this, _| {
 829                        if let Some((downstream, project_id)) = this.downstream_client.clone() {
 830                            downstream
 831                                .send(proto::LogToDebugConsole {
 832                                    project_id,
 833                                    session_id,
 834                                    message,
 835                                })
 836                                .ok();
 837                        }
 838                    })
 839                    .ok();
 840                }
 841            }
 842        })
 843        .detach();
 844
 845        let worktree = this
 846            .update(&mut cx, |this, cx| {
 847                this.worktree_store
 848                    .read(cx)
 849                    .worktree_for_id(WorktreeId::from_proto(envelope.payload.worktree_id), cx)
 850            })?
 851            .context("Failed to find worktree with a given ID")?;
 852        let binary = this
 853            .update(&mut cx, |this, cx| {
 854                this.get_debug_adapter_binary(
 855                    definition,
 856                    SessionId::from_proto(session_id),
 857                    &worktree,
 858                    tx,
 859                    cx,
 860                )
 861            })?
 862            .await?;
 863        Ok(binary.to_proto())
 864    }
 865
 866    async fn handle_log_to_debug_console(
 867        this: Entity<Self>,
 868        envelope: TypedEnvelope<proto::LogToDebugConsole>,
 869        mut cx: AsyncApp,
 870    ) -> Result<()> {
 871        let session_id = SessionId::from_proto(envelope.payload.session_id);
 872        this.update(&mut cx, |this, cx| {
 873            let Some(session) = this.sessions.get(&session_id) else {
 874                return;
 875            };
 876            session.update(cx, |session, cx| {
 877                session
 878                    .console_output(cx)
 879                    .unbounded_send(envelope.payload.message)
 880                    .ok();
 881            })
 882        })
 883    }
 884
 885    pub fn sync_adapter_options(
 886        &mut self,
 887        session: &Entity<Session>,
 888        cx: &App,
 889    ) -> Arc<PersistedAdapterOptions> {
 890        let session = session.read(cx);
 891        let adapter = session.adapter();
 892        let exceptions = session.exception_breakpoints();
 893        let exception_breakpoints = exceptions
 894            .map(|(exception, enabled)| {
 895                (
 896                    exception.filter.clone(),
 897                    PersistedExceptionBreakpoint { enabled: *enabled },
 898                )
 899            })
 900            .collect();
 901        let options = Arc::new(PersistedAdapterOptions {
 902            exception_breakpoints,
 903        });
 904        self.adapter_options.insert(adapter, options.clone());
 905        options
 906    }
 907
 908    pub fn set_adapter_options(
 909        &mut self,
 910        adapter: DebugAdapterName,
 911        options: PersistedAdapterOptions,
 912    ) {
 913        self.adapter_options.insert(adapter, Arc::new(options));
 914    }
 915
 916    pub fn adapter_options(&self, name: &str) -> Option<Arc<PersistedAdapterOptions>> {
 917        self.adapter_options.get(name).cloned()
 918    }
 919
 920    pub fn all_adapter_options(&self) -> &BTreeMap<DebugAdapterName, Arc<PersistedAdapterOptions>> {
 921        &self.adapter_options
 922    }
 923}
 924
 925#[derive(Clone)]
 926pub struct DapAdapterDelegate {
 927    fs: Arc<dyn Fs>,
 928    console: mpsc::UnboundedSender<String>,
 929    worktree: worktree::Snapshot,
 930    node_runtime: NodeRuntime,
 931    http_client: Arc<dyn HttpClient>,
 932    toolchain_store: Arc<dyn LanguageToolchainStore>,
 933    load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
 934    is_headless: bool,
 935}
 936
 937impl DapAdapterDelegate {
 938    pub fn new(
 939        fs: Arc<dyn Fs>,
 940        worktree: worktree::Snapshot,
 941        status: mpsc::UnboundedSender<String>,
 942        node_runtime: NodeRuntime,
 943        http_client: Arc<dyn HttpClient>,
 944        toolchain_store: Arc<dyn LanguageToolchainStore>,
 945        load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
 946        is_headless: bool,
 947    ) -> Self {
 948        Self {
 949            fs,
 950            console: status,
 951            worktree,
 952            http_client,
 953            node_runtime,
 954            toolchain_store,
 955            load_shell_env_task,
 956            is_headless,
 957        }
 958    }
 959}
 960
 961#[async_trait]
 962impl dap::adapters::DapDelegate for DapAdapterDelegate {
 963    fn worktree_id(&self) -> WorktreeId {
 964        self.worktree.id()
 965    }
 966
 967    fn worktree_root_path(&self) -> &Path {
 968        self.worktree.abs_path()
 969    }
 970    fn http_client(&self) -> Arc<dyn HttpClient> {
 971        self.http_client.clone()
 972    }
 973
 974    fn node_runtime(&self) -> NodeRuntime {
 975        self.node_runtime.clone()
 976    }
 977
 978    fn fs(&self) -> Arc<dyn Fs> {
 979        self.fs.clone()
 980    }
 981
 982    fn output_to_console(&self, msg: String) {
 983        self.console.unbounded_send(msg).ok();
 984    }
 985
 986    #[cfg(not(target_os = "windows"))]
 987    async fn which(&self, command: &OsStr) -> Option<PathBuf> {
 988        let worktree_abs_path = self.worktree.abs_path();
 989        let shell_path = self.shell_env().await.get("PATH").cloned();
 990        which::which_in(command, shell_path.as_ref(), worktree_abs_path).ok()
 991    }
 992
 993    #[cfg(target_os = "windows")]
 994    async fn which(&self, command: &OsStr) -> Option<PathBuf> {
 995        // On Windows, `PATH` is handled differently from Unix. Windows generally expects users to modify the `PATH` themselves,
 996        // and every program loads it directly from the system at startup.
 997        // There's also no concept of a default shell on Windows, and you can't really retrieve one, so trying to get shell environment variables
 998        // from a specific directory doesn’t make sense on Windows.
 999        which::which(command).ok()
1000    }
1001
1002    async fn shell_env(&self) -> HashMap<String, String> {
1003        let task = self.load_shell_env_task.clone();
1004        task.await.unwrap_or_default()
1005    }
1006
1007    fn toolchain_store(&self) -> Arc<dyn LanguageToolchainStore> {
1008        self.toolchain_store.clone()
1009    }
1010
1011    async fn read_text_file(&self, path: &RelPath) -> Result<String> {
1012        let entry = self
1013            .worktree
1014            .entry_for_path(path)
1015            .with_context(|| format!("no worktree entry for path {path:?}"))?;
1016        let abs_path = self.worktree.absolutize(&entry.path);
1017
1018        self.fs.load(&abs_path).await
1019    }
1020
1021    fn is_headless(&self) -> bool {
1022        self.is_headless
1023    }
1024}