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) => {
 265                        let path = PathBuf::from(binary);
 266                        Some(worktree.read(cx).resolve_executable_path(path))
 267                    }
 268                });
 269                let user_args = dap_settings.map(|s| s.args.clone());
 270                let user_env = dap_settings.map(|s| s.env.clone());
 271
 272                let delegate = self.delegate(worktree, console, cx);
 273
 274                let worktree = worktree.clone();
 275                cx.spawn(async move |this, cx| {
 276                    let mut binary = adapter
 277                        .get_binary(
 278                            &delegate,
 279                            &definition,
 280                            user_installed_path,
 281                            user_args,
 282                            user_env,
 283                            cx,
 284                        )
 285                        .await?;
 286
 287                    let env = this
 288                        .update(cx, |this, cx| {
 289                            this.as_local()
 290                                .unwrap()
 291                                .environment
 292                                .update(cx, |environment, cx| {
 293                                    environment.worktree_environment(worktree, cx)
 294                                })
 295                        })?
 296                        .await;
 297
 298                    if let Some(mut env) = env {
 299                        env.extend(std::mem::take(&mut binary.envs));
 300                        binary.envs = env;
 301                    }
 302
 303                    Ok(binary)
 304                })
 305            }
 306            DapStoreMode::Remote(remote) => {
 307                let request = remote
 308                    .upstream_client
 309                    .request(proto::GetDebugAdapterBinary {
 310                        session_id: session_id.to_proto(),
 311                        project_id: remote.upstream_project_id,
 312                        worktree_id: worktree.read(cx).id().to_proto(),
 313                        definition: Some(definition.to_proto()),
 314                    });
 315                let remote = remote.remote_client.clone();
 316
 317                cx.spawn(async move |_, cx| {
 318                    let response = request.await?;
 319                    let binary = DebugAdapterBinary::from_proto(response)?;
 320
 321                    let port_forwarding;
 322                    let connection;
 323                    if let Some(c) = binary.connection {
 324                        let host = Ipv4Addr::LOCALHOST;
 325                        let port;
 326                        if remote.read_with(cx, |remote, _cx| remote.shares_network_interface()) {
 327                            port = c.port;
 328                            port_forwarding = None;
 329                        } else {
 330                            port = dap::transport::TcpTransport::unused_port(host).await?;
 331                            port_forwarding = Some((port, c.host.to_string(), c.port));
 332                        }
 333                        connection = Some(TcpArguments {
 334                            port,
 335                            host,
 336                            timeout: c.timeout,
 337                        })
 338                    } else {
 339                        port_forwarding = None;
 340                        connection = None;
 341                    }
 342
 343                    let command = remote.read_with(cx, |remote, _cx| {
 344                        remote.build_command(
 345                            binary.command,
 346                            &binary.arguments,
 347                            &binary.envs,
 348                            binary.cwd.map(|path| path.display().to_string()),
 349                            port_forwarding,
 350                        )
 351                    })?;
 352
 353                    Ok(DebugAdapterBinary {
 354                        command: Some(command.program),
 355                        arguments: command.args,
 356                        envs: command.env,
 357                        cwd: None,
 358                        connection,
 359                        request_args: binary.request_args,
 360                    })
 361                })
 362            }
 363            DapStoreMode::Collab => {
 364                Task::ready(Err(anyhow!("Debugging is not yet supported via collab")))
 365            }
 366        }
 367    }
 368
 369    pub fn debug_scenario_for_build_task(
 370        &self,
 371        build: TaskTemplate,
 372        adapter: DebugAdapterName,
 373        label: SharedString,
 374        cx: &mut App,
 375    ) -> Task<Option<DebugScenario>> {
 376        let locators = DapRegistry::global(cx).locators();
 377
 378        cx.background_spawn(async move {
 379            for locator in locators.values() {
 380                if let Some(scenario) = locator.create_scenario(&build, &label, &adapter).await {
 381                    return Some(scenario);
 382                }
 383            }
 384            None
 385        })
 386    }
 387
 388    pub fn run_debug_locator(
 389        &mut self,
 390        locator_name: &str,
 391        build_command: SpawnInTerminal,
 392        cx: &mut Context<Self>,
 393    ) -> Task<Result<DebugRequest>> {
 394        match &self.mode {
 395            DapStoreMode::Local(_) => {
 396                // Pre-resolve args with existing environment.
 397                let locators = DapRegistry::global(cx).locators();
 398                let locator = locators.get(locator_name);
 399
 400                if let Some(locator) = locator.cloned() {
 401                    cx.background_spawn(async move {
 402                        let result = locator
 403                            .run(build_command.clone())
 404                            .await
 405                            .log_with_level(log::Level::Error);
 406                        if let Some(result) = result {
 407                            return Ok(result);
 408                        }
 409
 410                        anyhow::bail!(
 411                            "None of the locators for task `{}` completed successfully",
 412                            build_command.label
 413                        )
 414                    })
 415                } else {
 416                    Task::ready(Err(anyhow!(
 417                        "Couldn't find any locator for task `{}`. Specify the `attach` or `launch` arguments in your debug scenario definition",
 418                        build_command.label
 419                    )))
 420                }
 421            }
 422            DapStoreMode::Remote(remote) => {
 423                let request = remote.upstream_client.request(proto::RunDebugLocators {
 424                    project_id: remote.upstream_project_id,
 425                    build_command: Some(build_command.to_proto()),
 426                    locator: locator_name.to_owned(),
 427                });
 428                cx.background_spawn(async move {
 429                    let response = request.await?;
 430                    DebugRequest::from_proto(response)
 431                })
 432            }
 433            DapStoreMode::Collab => {
 434                Task::ready(Err(anyhow!("Debugging is not yet supported via collab")))
 435            }
 436        }
 437    }
 438
 439    fn as_local(&self) -> Option<&LocalDapStore> {
 440        match &self.mode {
 441            DapStoreMode::Local(local_dap_store) => Some(local_dap_store),
 442            _ => None,
 443        }
 444    }
 445
 446    pub fn new_session(
 447        &mut self,
 448        label: Option<SharedString>,
 449        adapter: DebugAdapterName,
 450        task_context: TaskContext,
 451        parent_session: Option<Entity<Session>>,
 452        quirks: SessionQuirks,
 453        cx: &mut Context<Self>,
 454    ) -> Entity<Session> {
 455        let session_id = SessionId(util::post_inc(&mut self.next_session_id));
 456
 457        if let Some(session) = &parent_session {
 458            session.update(cx, |session, _| {
 459                session.add_child_session_id(session_id);
 460            });
 461        }
 462
 463        let (remote_client, node_runtime, http_client) = match &self.mode {
 464            DapStoreMode::Local(_) => (None, None, None),
 465            DapStoreMode::Remote(remote_dap_store) => (
 466                Some(remote_dap_store.remote_client.clone()),
 467                Some(remote_dap_store.node_runtime.clone()),
 468                Some(remote_dap_store.http_client.clone()),
 469            ),
 470            DapStoreMode::Collab => (None, None, None),
 471        };
 472        let session = Session::new(
 473            self.breakpoint_store.clone(),
 474            session_id,
 475            parent_session,
 476            label,
 477            adapter,
 478            task_context,
 479            quirks,
 480            remote_client,
 481            node_runtime,
 482            http_client,
 483            cx,
 484        );
 485
 486        self.sessions.insert(session_id, session.clone());
 487        cx.notify();
 488
 489        cx.subscribe(&session, {
 490            move |this: &mut DapStore, _, event: &SessionStateEvent, cx| match event {
 491                SessionStateEvent::Shutdown => {
 492                    this.shutdown_session(session_id, cx).detach_and_log_err(cx);
 493                }
 494                SessionStateEvent::Restart | SessionStateEvent::SpawnChildSession { .. } => {}
 495                SessionStateEvent::Running => {
 496                    cx.emit(DapStoreEvent::DebugClientStarted(session_id));
 497                }
 498            }
 499        })
 500        .detach();
 501
 502        session
 503    }
 504
 505    pub fn boot_session(
 506        &self,
 507        session: Entity<Session>,
 508        definition: DebugTaskDefinition,
 509        worktree: Entity<Worktree>,
 510        cx: &mut Context<Self>,
 511    ) -> Task<Result<()>> {
 512        let dap_store = cx.weak_entity();
 513        let console = session.update(cx, |session, cx| session.console_output(cx));
 514        let session_id = session.read(cx).session_id();
 515
 516        cx.spawn({
 517            let session = session.clone();
 518            async move |this, cx| {
 519                let binary = this
 520                    .update(cx, |this, cx| {
 521                        this.get_debug_adapter_binary(
 522                            definition.clone(),
 523                            session_id,
 524                            &worktree,
 525                            console,
 526                            cx,
 527                        )
 528                    })?
 529                    .await?;
 530                session
 531                    .update(cx, |session, cx| {
 532                        session.boot(binary, worktree, dap_store, cx)
 533                    })
 534                    .await
 535            }
 536        })
 537    }
 538
 539    pub fn session_by_id(
 540        &self,
 541        session_id: impl Borrow<SessionId>,
 542    ) -> Option<Entity<session::Session>> {
 543        let session_id = session_id.borrow();
 544
 545        self.sessions.get(session_id).cloned()
 546    }
 547    pub fn sessions(&self) -> impl Iterator<Item = &Entity<Session>> {
 548        self.sessions.values()
 549    }
 550
 551    pub fn capabilities_by_id(
 552        &self,
 553        session_id: impl Borrow<SessionId>,
 554        cx: &App,
 555    ) -> Option<Capabilities> {
 556        let session_id = session_id.borrow();
 557        self.sessions
 558            .get(session_id)
 559            .map(|client| client.read(cx).capabilities.clone())
 560    }
 561
 562    pub fn breakpoint_store(&self) -> &Entity<BreakpointStore> {
 563        &self.breakpoint_store
 564    }
 565
 566    pub fn worktree_store(&self) -> &Entity<WorktreeStore> {
 567        &self.worktree_store
 568    }
 569
 570    #[allow(dead_code)]
 571    async fn handle_ignore_breakpoint_state(
 572        this: Entity<Self>,
 573        envelope: TypedEnvelope<proto::IgnoreBreakpointState>,
 574        mut cx: AsyncApp,
 575    ) -> Result<()> {
 576        let session_id = SessionId::from_proto(envelope.payload.session_id);
 577
 578        this.update(&mut cx, |this, cx| {
 579            if let Some(session) = this.session_by_id(&session_id) {
 580                session.update(cx, |session, cx| {
 581                    session.set_ignore_breakpoints(envelope.payload.ignore, cx)
 582                })
 583            } else {
 584                Task::ready(HashMap::default())
 585            }
 586        })
 587        .await;
 588
 589        Ok(())
 590    }
 591
 592    fn delegate(
 593        &self,
 594        worktree: &Entity<Worktree>,
 595        console: UnboundedSender<String>,
 596        cx: &mut App,
 597    ) -> Arc<dyn DapDelegate> {
 598        let Some(local_store) = self.as_local() else {
 599            unimplemented!("Starting session on remote side");
 600        };
 601
 602        Arc::new(DapAdapterDelegate::new(
 603            local_store.fs.clone(),
 604            worktree.read(cx).snapshot(),
 605            console,
 606            local_store.node_runtime.clone(),
 607            local_store.http_client.clone(),
 608            local_store.toolchain_store.clone(),
 609            local_store
 610                .environment
 611                .update(cx, |env, cx| env.worktree_environment(worktree.clone(), cx)),
 612            local_store.is_headless,
 613        ))
 614    }
 615
 616    pub fn resolve_inline_value_locations(
 617        &self,
 618        session: Entity<Session>,
 619        stack_frame_id: StackFrameId,
 620        buffer_handle: Entity<Buffer>,
 621        inline_value_locations: Vec<dap::inline_value::InlineValueLocation>,
 622        cx: &mut Context<Self>,
 623    ) -> Task<Result<Vec<InlayHint>>> {
 624        let snapshot = buffer_handle.read(cx).snapshot();
 625        let local_variables =
 626            session
 627                .read(cx)
 628                .variables_by_stack_frame_id(stack_frame_id, false, true);
 629        let global_variables =
 630            session
 631                .read(cx)
 632                .variables_by_stack_frame_id(stack_frame_id, true, false);
 633
 634        fn format_value(mut value: String) -> String {
 635            const LIMIT: usize = 100;
 636
 637            if let Some(index) = value.find("\n") {
 638                value.truncate(index);
 639                value.push_str("");
 640            }
 641
 642            if value.len() > LIMIT {
 643                let mut index = LIMIT;
 644                // If index isn't a char boundary truncate will cause a panic
 645                while !value.is_char_boundary(index) {
 646                    index -= 1;
 647                }
 648                value.truncate(index);
 649                value.push_str("");
 650            }
 651
 652            format!(": {}", value)
 653        }
 654
 655        cx.spawn(async move |_, cx| {
 656            let mut inlay_hints = Vec::with_capacity(inline_value_locations.len());
 657            for inline_value_location in inline_value_locations.iter() {
 658                let point = snapshot.point_to_point_utf16(language::Point::new(
 659                    inline_value_location.row as u32,
 660                    inline_value_location.column as u32,
 661                ));
 662                let position = snapshot.anchor_after(point);
 663
 664                match inline_value_location.lookup {
 665                    VariableLookupKind::Variable => {
 666                        let variable_search =
 667                            if inline_value_location.scope
 668                                == dap::inline_value::VariableScope::Local
 669                            {
 670                                local_variables.iter().chain(global_variables.iter()).find(
 671                                    |variable| variable.name == inline_value_location.variable_name,
 672                                )
 673                            } else {
 674                                global_variables.iter().find(|variable| {
 675                                    variable.name == inline_value_location.variable_name
 676                                })
 677                            };
 678
 679                        let Some(variable) = variable_search else {
 680                            continue;
 681                        };
 682
 683                        inlay_hints.push(InlayHint {
 684                            position,
 685                            label: InlayHintLabel::String(format_value(variable.value.clone())),
 686                            kind: Some(InlayHintKind::Type),
 687                            padding_left: false,
 688                            padding_right: false,
 689                            tooltip: None,
 690                            resolve_state: ResolveState::Resolved,
 691                        });
 692                    }
 693                    VariableLookupKind::Expression => {
 694                        let eval_task = session.read_with(cx, |session, _| {
 695                            session.state.request_dap(EvaluateCommand {
 696                                expression: inline_value_location.variable_name.clone(),
 697                                frame_id: Some(stack_frame_id),
 698                                source: None,
 699                                context: Some(EvaluateArgumentsContext::Variables),
 700                            })
 701                        });
 702
 703                        if let Some(response) = eval_task.await.log_err() {
 704                            inlay_hints.push(InlayHint {
 705                                position,
 706                                label: InlayHintLabel::String(format_value(response.result)),
 707                                kind: Some(InlayHintKind::Type),
 708                                padding_left: false,
 709                                padding_right: false,
 710                                tooltip: None,
 711                                resolve_state: ResolveState::Resolved,
 712                            });
 713                        };
 714                    }
 715                };
 716            }
 717
 718            Ok(inlay_hints)
 719        })
 720    }
 721
 722    pub fn shutdown_sessions(&mut self, cx: &mut Context<Self>) -> Task<()> {
 723        let mut tasks = vec![];
 724        for session_id in self.sessions.keys().cloned().collect::<Vec<_>>() {
 725            tasks.push(self.shutdown_session(session_id, cx));
 726        }
 727
 728        cx.background_executor().spawn(async move {
 729            futures::future::join_all(tasks).await;
 730        })
 731    }
 732
 733    pub fn shutdown_session(
 734        &mut self,
 735        session_id: SessionId,
 736        cx: &mut Context<Self>,
 737    ) -> Task<Result<()>> {
 738        let Some(session) = self.sessions.remove(&session_id) else {
 739            return Task::ready(Err(anyhow!("Could not find session: {:?}", session_id)));
 740        };
 741
 742        let shutdown_children = session
 743            .read(cx)
 744            .child_session_ids()
 745            .iter()
 746            .map(|session_id| self.shutdown_session(*session_id, cx))
 747            .collect::<Vec<_>>();
 748
 749        let shutdown_parent_task = if let Some(parent_session) = session
 750            .read(cx)
 751            .parent_id(cx)
 752            .and_then(|session_id| self.session_by_id(session_id))
 753        {
 754            let shutdown_id = parent_session.update(cx, |parent_session, _| {
 755                parent_session.remove_child_session_id(session_id);
 756
 757                if parent_session.child_session_ids().is_empty() {
 758                    Some(parent_session.session_id())
 759                } else {
 760                    None
 761                }
 762            });
 763
 764            shutdown_id.map(|session_id| self.shutdown_session(session_id, cx))
 765        } else {
 766            None
 767        };
 768
 769        let shutdown_task = session.update(cx, |this, cx| this.shutdown(cx));
 770
 771        cx.emit(DapStoreEvent::DebugClientShutdown(session_id));
 772
 773        cx.background_spawn(async move {
 774            if !shutdown_children.is_empty() {
 775                let _ = join_all(shutdown_children).await;
 776            }
 777
 778            shutdown_task.await;
 779
 780            if let Some(parent_task) = shutdown_parent_task {
 781                parent_task.await?;
 782            }
 783
 784            Ok(())
 785        })
 786    }
 787
 788    pub fn shared(
 789        &mut self,
 790        project_id: u64,
 791        downstream_client: AnyProtoClient,
 792        _: &mut Context<Self>,
 793    ) {
 794        self.downstream_client = Some((downstream_client, project_id));
 795    }
 796
 797    pub fn unshared(&mut self, cx: &mut Context<Self>) {
 798        self.downstream_client.take();
 799
 800        cx.notify();
 801    }
 802
 803    async fn handle_run_debug_locator(
 804        this: Entity<Self>,
 805        envelope: TypedEnvelope<proto::RunDebugLocators>,
 806        mut cx: AsyncApp,
 807    ) -> Result<proto::DebugRequest> {
 808        let task = envelope
 809            .payload
 810            .build_command
 811            .context("missing definition")?;
 812        let build_task = SpawnInTerminal::from_proto(task);
 813        let locator = envelope.payload.locator;
 814        let request = this
 815            .update(&mut cx, |this, cx| {
 816                this.run_debug_locator(&locator, build_task, cx)
 817            })
 818            .await?;
 819
 820        Ok(request.to_proto())
 821    }
 822
 823    async fn handle_get_debug_adapter_binary(
 824        this: Entity<Self>,
 825        envelope: TypedEnvelope<proto::GetDebugAdapterBinary>,
 826        mut cx: AsyncApp,
 827    ) -> Result<proto::DebugAdapterBinary> {
 828        let definition = DebugTaskDefinition::from_proto(
 829            envelope.payload.definition.context("missing definition")?,
 830        )?;
 831        let (tx, mut rx) = mpsc::unbounded();
 832        let session_id = envelope.payload.session_id;
 833        cx.spawn({
 834            let this = this.clone();
 835            async move |cx| {
 836                while let Some(message) = rx.next().await {
 837                    this.read_with(cx, |this, _| {
 838                        if let Some((downstream, project_id)) = this.downstream_client.clone() {
 839                            downstream
 840                                .send(proto::LogToDebugConsole {
 841                                    project_id,
 842                                    session_id,
 843                                    message,
 844                                })
 845                                .ok();
 846                        }
 847                    });
 848                }
 849            }
 850        })
 851        .detach();
 852
 853        let worktree = this
 854            .update(&mut cx, |this, cx| {
 855                this.worktree_store
 856                    .read(cx)
 857                    .worktree_for_id(WorktreeId::from_proto(envelope.payload.worktree_id), cx)
 858            })
 859            .context("Failed to find worktree with a given ID")?;
 860        let binary = this
 861            .update(&mut cx, |this, cx| {
 862                this.get_debug_adapter_binary(
 863                    definition,
 864                    SessionId::from_proto(session_id),
 865                    &worktree,
 866                    tx,
 867                    cx,
 868                )
 869            })
 870            .await?;
 871        Ok(binary.to_proto())
 872    }
 873
 874    async fn handle_log_to_debug_console(
 875        this: Entity<Self>,
 876        envelope: TypedEnvelope<proto::LogToDebugConsole>,
 877        mut cx: AsyncApp,
 878    ) -> Result<()> {
 879        let session_id = SessionId::from_proto(envelope.payload.session_id);
 880        this.update(&mut cx, |this, cx| {
 881            let Some(session) = this.sessions.get(&session_id) else {
 882                return;
 883            };
 884            session.update(cx, |session, cx| {
 885                session
 886                    .console_output(cx)
 887                    .unbounded_send(envelope.payload.message)
 888                    .ok();
 889            })
 890        });
 891        Ok(())
 892    }
 893
 894    pub fn sync_adapter_options(
 895        &mut self,
 896        session: &Entity<Session>,
 897        cx: &App,
 898    ) -> Arc<PersistedAdapterOptions> {
 899        let session = session.read(cx);
 900        let adapter = session.adapter();
 901        let exceptions = session.exception_breakpoints();
 902        let exception_breakpoints = exceptions
 903            .map(|(exception, enabled)| {
 904                (
 905                    exception.filter.clone(),
 906                    PersistedExceptionBreakpoint { enabled: *enabled },
 907                )
 908            })
 909            .collect();
 910        let options = Arc::new(PersistedAdapterOptions {
 911            exception_breakpoints,
 912        });
 913        self.adapter_options.insert(adapter, options.clone());
 914        options
 915    }
 916
 917    pub fn set_adapter_options(
 918        &mut self,
 919        adapter: DebugAdapterName,
 920        options: PersistedAdapterOptions,
 921    ) {
 922        self.adapter_options.insert(adapter, Arc::new(options));
 923    }
 924
 925    pub fn adapter_options(&self, name: &str) -> Option<Arc<PersistedAdapterOptions>> {
 926        self.adapter_options.get(name).cloned()
 927    }
 928
 929    pub fn all_adapter_options(&self) -> &BTreeMap<DebugAdapterName, Arc<PersistedAdapterOptions>> {
 930        &self.adapter_options
 931    }
 932}
 933
 934#[derive(Clone)]
 935pub struct DapAdapterDelegate {
 936    fs: Arc<dyn Fs>,
 937    console: mpsc::UnboundedSender<String>,
 938    worktree: worktree::Snapshot,
 939    node_runtime: NodeRuntime,
 940    http_client: Arc<dyn HttpClient>,
 941    toolchain_store: Arc<dyn LanguageToolchainStore>,
 942    load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
 943    is_headless: bool,
 944}
 945
 946impl DapAdapterDelegate {
 947    pub fn new(
 948        fs: Arc<dyn Fs>,
 949        worktree: worktree::Snapshot,
 950        status: mpsc::UnboundedSender<String>,
 951        node_runtime: NodeRuntime,
 952        http_client: Arc<dyn HttpClient>,
 953        toolchain_store: Arc<dyn LanguageToolchainStore>,
 954        load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
 955        is_headless: bool,
 956    ) -> Self {
 957        Self {
 958            fs,
 959            console: status,
 960            worktree,
 961            http_client,
 962            node_runtime,
 963            toolchain_store,
 964            load_shell_env_task,
 965            is_headless,
 966        }
 967    }
 968}
 969
 970#[async_trait]
 971impl dap::adapters::DapDelegate for DapAdapterDelegate {
 972    fn worktree_id(&self) -> WorktreeId {
 973        self.worktree.id()
 974    }
 975
 976    fn worktree_root_path(&self) -> &Path {
 977        self.worktree.abs_path()
 978    }
 979    fn http_client(&self) -> Arc<dyn HttpClient> {
 980        self.http_client.clone()
 981    }
 982
 983    fn node_runtime(&self) -> NodeRuntime {
 984        self.node_runtime.clone()
 985    }
 986
 987    fn fs(&self) -> Arc<dyn Fs> {
 988        self.fs.clone()
 989    }
 990
 991    fn output_to_console(&self, msg: String) {
 992        self.console.unbounded_send(msg).ok();
 993    }
 994
 995    #[cfg(not(target_os = "windows"))]
 996    async fn which(&self, command: &OsStr) -> Option<PathBuf> {
 997        let worktree_abs_path = self.worktree.abs_path();
 998        let shell_path = self.shell_env().await.get("PATH").cloned();
 999        which::which_in(command, shell_path.as_ref(), worktree_abs_path).ok()
1000    }
1001
1002    #[cfg(target_os = "windows")]
1003    async fn which(&self, command: &OsStr) -> Option<PathBuf> {
1004        // On Windows, `PATH` is handled differently from Unix. Windows generally expects users to modify the `PATH` themselves,
1005        // and every program loads it directly from the system at startup.
1006        // 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
1007        // from a specific directory doesn’t make sense on Windows.
1008        which::which(command).ok()
1009    }
1010
1011    async fn shell_env(&self) -> HashMap<String, String> {
1012        let task = self.load_shell_env_task.clone();
1013        task.await.unwrap_or_default()
1014    }
1015
1016    fn toolchain_store(&self) -> Arc<dyn LanguageToolchainStore> {
1017        self.toolchain_store.clone()
1018    }
1019
1020    async fn read_text_file(&self, path: &RelPath) -> Result<String> {
1021        let entry = self
1022            .worktree
1023            .entry_for_path(path)
1024            .with_context(|| format!("no worktree entry for path {path:?}"))?;
1025        let abs_path = self.worktree.absolutize(&entry.path);
1026
1027        self.fs.load(&abs_path).await
1028    }
1029
1030    fn is_headless(&self) -> bool {
1031        self.is_headless
1032    }
1033}