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