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