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::{Context as _, 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::{
 20        DapDelegate, DebugAdapterBinary, DebugAdapterName, DebugTaskDefinition, TcpArguments,
 21    },
 22    client::SessionId,
 23    inline_value::VariableLookupKind,
 24    messages::Message,
 25    requests::{Completions, Evaluate},
 26};
 27use fs::Fs;
 28use futures::{
 29    StreamExt,
 30    channel::mpsc::{self, UnboundedSender},
 31    future::{Shared, join_all},
 32};
 33use gpui::{App, AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task};
 34use http_client::HttpClient;
 35use language::{Buffer, LanguageToolchainStore, language_settings::InlayHintKind};
 36use node_runtime::NodeRuntime;
 37
 38use remote::SshRemoteClient;
 39use rpc::{
 40    AnyProtoClient, TypedEnvelope,
 41    proto::{self},
 42};
 43use settings::{Settings, 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, TaskTemplate};
 53use util::ResultExt as _;
 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    Ssh(SshDapStore),
 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}
 82
 83pub struct SshDapStore {
 84    ssh_client: Entity<SshRemoteClient>,
 85    upstream_client: AnyProtoClient,
 86    upstream_project_id: u64,
 87}
 88
 89pub struct DapStore {
 90    mode: DapStoreMode,
 91    downstream_client: Option<(AnyProtoClient, u64)>,
 92    breakpoint_store: Entity<BreakpointStore>,
 93    worktree_store: Entity<WorktreeStore>,
 94    sessions: BTreeMap<SessionId, Entity<Session>>,
 95    next_session_id: u32,
 96}
 97
 98impl EventEmitter<DapStoreEvent> for DapStore {}
 99
100impl DapStore {
101    pub fn init(client: &AnyProtoClient, cx: &mut App) {
102        static ADD_LOCATORS: Once = Once::new();
103        ADD_LOCATORS.call_once(|| {
104            let registry = DapRegistry::global(cx);
105            registry.add_locator(Arc::new(locators::cargo::CargoLocator {}));
106            registry.add_locator(Arc::new(locators::go::GoLocator {}));
107            registry.add_locator(Arc::new(locators::node::NodeLocator));
108            registry.add_locator(Arc::new(locators::python::PythonLocator));
109        });
110        client.add_entity_request_handler(Self::handle_run_debug_locator);
111        client.add_entity_request_handler(Self::handle_get_debug_adapter_binary);
112        client.add_entity_message_handler(Self::handle_log_to_debug_console);
113    }
114
115    #[expect(clippy::too_many_arguments)]
116    pub fn new_local(
117        http_client: Arc<dyn HttpClient>,
118        node_runtime: NodeRuntime,
119        fs: Arc<dyn Fs>,
120        environment: Entity<ProjectEnvironment>,
121        toolchain_store: Arc<dyn LanguageToolchainStore>,
122        worktree_store: Entity<WorktreeStore>,
123        breakpoint_store: Entity<BreakpointStore>,
124        cx: &mut Context<Self>,
125    ) -> Self {
126        let mode = DapStoreMode::Local(LocalDapStore {
127            fs,
128            environment,
129            http_client,
130            node_runtime,
131            toolchain_store,
132        });
133
134        Self::new(mode, breakpoint_store, worktree_store, cx)
135    }
136
137    pub fn new_ssh(
138        project_id: u64,
139        ssh_client: Entity<SshRemoteClient>,
140        breakpoint_store: Entity<BreakpointStore>,
141        worktree_store: Entity<WorktreeStore>,
142        cx: &mut Context<Self>,
143    ) -> Self {
144        let mode = DapStoreMode::Ssh(SshDapStore {
145            upstream_client: ssh_client.read(cx).proto_client(),
146            ssh_client,
147            upstream_project_id: project_id,
148        });
149
150        Self::new(mode, breakpoint_store, worktree_store, cx)
151    }
152
153    pub fn new_collab(
154        _project_id: u64,
155        _upstream_client: AnyProtoClient,
156        breakpoint_store: Entity<BreakpointStore>,
157        worktree_store: Entity<WorktreeStore>,
158        cx: &mut Context<Self>,
159    ) -> Self {
160        Self::new(DapStoreMode::Collab, breakpoint_store, worktree_store, cx)
161    }
162
163    fn new(
164        mode: DapStoreMode,
165        breakpoint_store: Entity<BreakpointStore>,
166        worktree_store: Entity<WorktreeStore>,
167        _cx: &mut Context<Self>,
168    ) -> Self {
169        Self {
170            mode,
171            next_session_id: 0,
172            downstream_client: None,
173            breakpoint_store,
174            worktree_store,
175            sessions: Default::default(),
176        }
177    }
178
179    pub fn get_debug_adapter_binary(
180        &mut self,
181        definition: DebugTaskDefinition,
182        session_id: SessionId,
183        worktree: &Entity<Worktree>,
184        console: UnboundedSender<String>,
185        cx: &mut Context<Self>,
186    ) -> Task<Result<DebugAdapterBinary>> {
187        match &self.mode {
188            DapStoreMode::Local(_) => {
189                let Some(adapter) = DapRegistry::global(cx).adapter(&definition.adapter) else {
190                    return Task::ready(Err(anyhow!("Failed to find a debug adapter")));
191                };
192
193                let user_installed_path = ProjectSettings::get_global(cx)
194                    .dap
195                    .get(&adapter.name())
196                    .and_then(|s| s.binary.as_ref().map(PathBuf::from));
197
198                let delegate = self.delegate(&worktree, console, cx);
199                let cwd: Arc<Path> = worktree.read(cx).abs_path().as_ref().into();
200
201                cx.spawn(async move |this, cx| {
202                    let mut binary = adapter
203                        .get_binary(&delegate, &definition, user_installed_path, cx)
204                        .await?;
205
206                    let env = this
207                        .update(cx, |this, cx| {
208                            this.as_local()
209                                .unwrap()
210                                .environment
211                                .update(cx, |environment, cx| {
212                                    environment.get_directory_environment(cwd, cx)
213                                })
214                        })?
215                        .await;
216
217                    if let Some(mut env) = env {
218                        env.extend(std::mem::take(&mut binary.envs));
219                        binary.envs = env;
220                    }
221
222                    Ok(binary)
223                })
224            }
225            DapStoreMode::Ssh(ssh) => {
226                let request = ssh.upstream_client.request(proto::GetDebugAdapterBinary {
227                    session_id: session_id.to_proto(),
228                    project_id: ssh.upstream_project_id,
229                    worktree_id: worktree.read(cx).id().to_proto(),
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.read_with(cx, |ssh, _| {
238                        anyhow::Ok(SshCommand {
239                            arguments: ssh.ssh_args().context("SSH arguments not found")?,
240                        })
241                    })??;
242
243                    let mut connection = None;
244                    if let Some(c) = binary.connection {
245                        let local_bind_addr = Ipv4Addr::LOCALHOST;
246                        let port =
247                            dap::transport::TcpTransport::unused_port(local_bind_addr).await?;
248
249                        ssh_command.add_port_forwarding(port, c.host.to_string(), c.port);
250                        connection = Some(TcpArguments {
251                            port,
252                            host: local_bind_addr,
253                            timeout: c.timeout,
254                        })
255                    }
256
257                    let (program, args) = wrap_for_ssh(
258                        &ssh_command,
259                        binary
260                            .command
261                            .as_ref()
262                            .map(|command| (command, &binary.arguments)),
263                        binary.cwd.as_deref(),
264                        binary.envs,
265                        None,
266                    );
267
268                    Ok(DebugAdapterBinary {
269                        command: Some(program),
270                        arguments: args,
271                        envs: HashMap::default(),
272                        cwd: None,
273                        connection,
274                        request_args: binary.request_args,
275                    })
276                })
277            }
278            DapStoreMode::Collab => {
279                Task::ready(Err(anyhow!("Debugging is not yet supported via collab")))
280            }
281        }
282    }
283
284    pub fn debug_scenario_for_build_task(
285        &self,
286        build: TaskTemplate,
287        adapter: DebugAdapterName,
288        label: SharedString,
289        cx: &mut App,
290    ) -> Option<DebugScenario> {
291        DapRegistry::global(cx)
292            .locators()
293            .values()
294            .find_map(|locator| locator.create_scenario(&build, &label, adapter.clone()))
295    }
296
297    pub fn run_debug_locator(
298        &mut self,
299        locator_name: &str,
300        build_command: SpawnInTerminal,
301        cx: &mut Context<Self>,
302    ) -> Task<Result<DebugRequest>> {
303        match &self.mode {
304            DapStoreMode::Local(_) => {
305                // Pre-resolve args with existing environment.
306                let locators = DapRegistry::global(cx).locators();
307                let locator = locators.get(locator_name);
308
309                if let Some(locator) = locator.cloned() {
310                    cx.background_spawn(async move {
311                        let result = locator
312                            .run(build_command.clone())
313                            .await
314                            .log_with_level(log::Level::Error);
315                        if let Some(result) = result {
316                            return Ok(result);
317                        }
318
319                        anyhow::bail!(
320                            "None of the locators for task `{}` completed successfully",
321                            build_command.label
322                        )
323                    })
324                } else {
325                    Task::ready(Err(anyhow!(
326                        "Couldn't find any locator for task `{}`. Specify the `attach` or `launch` arguments in your debug scenario definition",
327                        build_command.label
328                    )))
329                }
330            }
331            DapStoreMode::Ssh(ssh) => {
332                let request = ssh.upstream_client.request(proto::RunDebugLocators {
333                    project_id: ssh.upstream_project_id,
334                    build_command: Some(build_command.to_proto()),
335                    locator: locator_name.to_owned(),
336                });
337                cx.background_spawn(async move {
338                    let response = request.await?;
339                    DebugRequest::from_proto(response)
340                })
341            }
342            DapStoreMode::Collab => {
343                Task::ready(Err(anyhow!("Debugging is not yet supported via collab")))
344            }
345        }
346    }
347
348    fn as_local(&self) -> Option<&LocalDapStore> {
349        match &self.mode {
350            DapStoreMode::Local(local_dap_store) => Some(local_dap_store),
351            _ => None,
352        }
353    }
354
355    pub fn new_session(
356        &mut self,
357        label: SharedString,
358        adapter: DebugAdapterName,
359        parent_session: Option<Entity<Session>>,
360        cx: &mut Context<Self>,
361    ) -> Entity<Session> {
362        let session_id = SessionId(util::post_inc(&mut self.next_session_id));
363
364        if let Some(session) = &parent_session {
365            session.update(cx, |session, _| {
366                session.add_child_session_id(session_id);
367            });
368        }
369
370        let session = Session::new(
371            self.breakpoint_store.clone(),
372            session_id,
373            parent_session,
374            label,
375            adapter,
376            cx,
377        );
378
379        self.sessions.insert(session_id, session.clone());
380        cx.notify();
381
382        cx.subscribe(&session, {
383            move |this: &mut DapStore, _, event: &SessionStateEvent, cx| match event {
384                SessionStateEvent::Shutdown => {
385                    this.shutdown_session(session_id, cx).detach_and_log_err(cx);
386                }
387                SessionStateEvent::Restart | SessionStateEvent::SpawnChildSession { .. } => {}
388                SessionStateEvent::Running => {
389                    cx.emit(DapStoreEvent::DebugClientStarted(session_id));
390                }
391            }
392        })
393        .detach();
394
395        session
396    }
397
398    pub fn boot_session(
399        &self,
400        session: Entity<Session>,
401        definition: DebugTaskDefinition,
402        worktree: Entity<Worktree>,
403        cx: &mut Context<Self>,
404    ) -> Task<Result<()>> {
405        let dap_store = cx.weak_entity();
406        let console = session.update(cx, |session, cx| session.console_output(cx));
407        let session_id = session.read(cx).session_id();
408
409        cx.spawn({
410            let session = session.clone();
411            async move |this, cx| {
412                let binary = this
413                    .update(cx, |this, cx| {
414                        this.get_debug_adapter_binary(
415                            definition.clone(),
416                            session_id,
417                            &worktree,
418                            console,
419                            cx,
420                        )
421                    })?
422                    .await?;
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    ) -> Arc<dyn DapDelegate> {
492        let Some(local_store) = self.as_local() else {
493            unimplemented!("Starting session on remote side");
494        };
495
496        Arc::new(DapAdapterDelegate::new(
497            local_store.fs.clone(),
498            worktree.read(cx).snapshot(),
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        fn format_value(mut value: String) -> String {
580            const LIMIT: usize = 100;
581
582            if value.len() > LIMIT {
583                let mut index = LIMIT;
584                // If index isn't a char boundary truncate will cause a panic
585                while !value.is_char_boundary(index) {
586                    index -= 1;
587                }
588                value.truncate(index);
589                value.push_str("...");
590            }
591
592            format!(": {}", value)
593        }
594
595        cx.spawn(async move |_, cx| {
596            let mut inlay_hints = Vec::with_capacity(inline_value_locations.len());
597            for inline_value_location in inline_value_locations.iter() {
598                let point = snapshot.point_to_point_utf16(language::Point::new(
599                    inline_value_location.row as u32,
600                    inline_value_location.column as u32,
601                ));
602                let position = snapshot.anchor_after(point);
603
604                match inline_value_location.lookup {
605                    VariableLookupKind::Variable => {
606                        let Some(variable) = all_variables
607                            .iter()
608                            .find(|variable| variable.name == inline_value_location.variable_name)
609                        else {
610                            continue;
611                        };
612
613                        inlay_hints.push(InlayHint {
614                            position,
615                            label: InlayHintLabel::String(format_value(variable.value.clone())),
616                            kind: Some(InlayHintKind::Type),
617                            padding_left: false,
618                            padding_right: false,
619                            tooltip: None,
620                            resolve_state: ResolveState::Resolved,
621                        });
622                    }
623                    VariableLookupKind::Expression => {
624                        let Ok(eval_task) = session.read_with(cx, |session, _| {
625                            session.mode.request_dap(EvaluateCommand {
626                                expression: inline_value_location.variable_name.clone(),
627                                frame_id: Some(stack_frame_id),
628                                source: None,
629                                context: Some(EvaluateArgumentsContext::Variables),
630                            })
631                        }) else {
632                            continue;
633                        };
634
635                        if let Some(response) = eval_task.await.log_err() {
636                            inlay_hints.push(InlayHint {
637                                position,
638                                label: InlayHintLabel::String(format_value(response.result)),
639                                kind: Some(InlayHintKind::Type),
640                                padding_left: false,
641                                padding_right: false,
642                                tooltip: None,
643                                resolve_state: ResolveState::Resolved,
644                            });
645                        };
646                    }
647                };
648            }
649
650            Ok(inlay_hints)
651        })
652    }
653
654    pub fn shutdown_sessions(&mut self, cx: &mut Context<Self>) -> Task<()> {
655        let mut tasks = vec![];
656        for session_id in self.sessions.keys().cloned().collect::<Vec<_>>() {
657            tasks.push(self.shutdown_session(session_id, cx));
658        }
659
660        cx.background_executor().spawn(async move {
661            futures::future::join_all(tasks).await;
662        })
663    }
664
665    pub fn shutdown_session(
666        &mut self,
667        session_id: SessionId,
668        cx: &mut Context<Self>,
669    ) -> Task<Result<()>> {
670        let Some(session) = self.sessions.remove(&session_id) else {
671            return Task::ready(Err(anyhow!("Could not find session: {:?}", session_id)));
672        };
673
674        let shutdown_children = session
675            .read(cx)
676            .child_session_ids()
677            .iter()
678            .map(|session_id| self.shutdown_session(*session_id, cx))
679            .collect::<Vec<_>>();
680
681        let shutdown_parent_task = if let Some(parent_session) = session
682            .read(cx)
683            .parent_id(cx)
684            .and_then(|session_id| self.session_by_id(session_id))
685        {
686            let shutdown_id = parent_session.update(cx, |parent_session, _| {
687                parent_session.remove_child_session_id(session_id);
688
689                if parent_session.child_session_ids().len() == 0 {
690                    Some(parent_session.session_id())
691                } else {
692                    None
693                }
694            });
695
696            shutdown_id.map(|session_id| self.shutdown_session(session_id, cx))
697        } else {
698            None
699        };
700
701        let shutdown_task = session.update(cx, |this, cx| this.shutdown(cx));
702
703        cx.background_spawn(async move {
704            if shutdown_children.len() > 0 {
705                let _ = join_all(shutdown_children).await;
706            }
707
708            shutdown_task.await;
709
710            if let Some(parent_task) = shutdown_parent_task {
711                parent_task.await?;
712            }
713
714            Ok(())
715        })
716    }
717
718    pub fn shared(
719        &mut self,
720        project_id: u64,
721        downstream_client: AnyProtoClient,
722        _: &mut Context<Self>,
723    ) {
724        self.downstream_client = Some((downstream_client.clone(), project_id));
725    }
726
727    pub fn unshared(&mut self, cx: &mut Context<Self>) {
728        self.downstream_client.take();
729
730        cx.notify();
731    }
732
733    async fn handle_run_debug_locator(
734        this: Entity<Self>,
735        envelope: TypedEnvelope<proto::RunDebugLocators>,
736        mut cx: AsyncApp,
737    ) -> Result<proto::DebugRequest> {
738        let task = envelope
739            .payload
740            .build_command
741            .context("missing definition")?;
742        let build_task = SpawnInTerminal::from_proto(task);
743        let locator = envelope.payload.locator;
744        let request = this
745            .update(&mut cx, |this, cx| {
746                this.run_debug_locator(&locator, build_task, cx)
747            })?
748            .await?;
749
750        Ok(request.to_proto())
751    }
752
753    async fn handle_get_debug_adapter_binary(
754        this: Entity<Self>,
755        envelope: TypedEnvelope<proto::GetDebugAdapterBinary>,
756        mut cx: AsyncApp,
757    ) -> Result<proto::DebugAdapterBinary> {
758        let definition = DebugTaskDefinition::from_proto(
759            envelope.payload.definition.context("missing definition")?,
760        )?;
761        let (tx, mut rx) = mpsc::unbounded();
762        let session_id = envelope.payload.session_id;
763        cx.spawn({
764            let this = this.clone();
765            async move |cx| {
766                while let Some(message) = rx.next().await {
767                    this.read_with(cx, |this, _| {
768                        if let Some((downstream, project_id)) = this.downstream_client.clone() {
769                            downstream
770                                .send(proto::LogToDebugConsole {
771                                    project_id,
772                                    session_id,
773                                    message,
774                                })
775                                .ok();
776                        }
777                    })
778                    .ok();
779                }
780            }
781        })
782        .detach();
783
784        let worktree = this
785            .update(&mut cx, |this, cx| {
786                this.worktree_store
787                    .read(cx)
788                    .worktree_for_id(WorktreeId::from_proto(envelope.payload.worktree_id), cx)
789            })?
790            .context("Failed to find worktree with a given ID")?;
791        let binary = this
792            .update(&mut cx, |this, cx| {
793                this.get_debug_adapter_binary(
794                    definition,
795                    SessionId::from_proto(session_id),
796                    &worktree,
797                    tx,
798                    cx,
799                )
800            })?
801            .await?;
802        Ok(binary.to_proto())
803    }
804
805    async fn handle_log_to_debug_console(
806        this: Entity<Self>,
807        envelope: TypedEnvelope<proto::LogToDebugConsole>,
808        mut cx: AsyncApp,
809    ) -> Result<()> {
810        let session_id = SessionId::from_proto(envelope.payload.session_id);
811        this.update(&mut cx, |this, cx| {
812            let Some(session) = this.sessions.get(&session_id) else {
813                return;
814            };
815            session.update(cx, |session, cx| {
816                session
817                    .console_output(cx)
818                    .unbounded_send(envelope.payload.message)
819                    .ok();
820            })
821        })
822    }
823}
824
825#[derive(Clone)]
826pub struct DapAdapterDelegate {
827    fs: Arc<dyn Fs>,
828    console: mpsc::UnboundedSender<String>,
829    worktree: worktree::Snapshot,
830    node_runtime: NodeRuntime,
831    http_client: Arc<dyn HttpClient>,
832    toolchain_store: Arc<dyn LanguageToolchainStore>,
833    load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
834}
835
836impl DapAdapterDelegate {
837    pub fn new(
838        fs: Arc<dyn Fs>,
839        worktree: worktree::Snapshot,
840        status: mpsc::UnboundedSender<String>,
841        node_runtime: NodeRuntime,
842        http_client: Arc<dyn HttpClient>,
843        toolchain_store: Arc<dyn LanguageToolchainStore>,
844        load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
845    ) -> Self {
846        Self {
847            fs,
848            console: status,
849            worktree,
850            http_client,
851            node_runtime,
852            toolchain_store,
853            load_shell_env_task,
854        }
855    }
856}
857
858#[async_trait]
859impl dap::adapters::DapDelegate for DapAdapterDelegate {
860    fn worktree_id(&self) -> WorktreeId {
861        self.worktree.id()
862    }
863
864    fn worktree_root_path(&self) -> &Path {
865        &self.worktree.abs_path()
866    }
867    fn http_client(&self) -> Arc<dyn HttpClient> {
868        self.http_client.clone()
869    }
870
871    fn node_runtime(&self) -> NodeRuntime {
872        self.node_runtime.clone()
873    }
874
875    fn fs(&self) -> Arc<dyn Fs> {
876        self.fs.clone()
877    }
878
879    fn output_to_console(&self, msg: String) {
880        self.console.unbounded_send(msg).ok();
881    }
882
883    async fn which(&self, command: &OsStr) -> Option<PathBuf> {
884        which::which(command).ok()
885    }
886
887    async fn shell_env(&self) -> HashMap<String, String> {
888        let task = self.load_shell_env_task.clone();
889        task.await.unwrap_or_default()
890    }
891
892    fn toolchain_store(&self) -> Arc<dyn LanguageToolchainStore> {
893        self.toolchain_store.clone()
894    }
895    async fn read_text_file(&self, path: PathBuf) -> Result<String> {
896        let entry = self
897            .worktree
898            .entry_for_path(&path)
899            .with_context(|| format!("no worktree entry for path {path:?}"))?;
900        let abs_path = self
901            .worktree
902            .absolutize(&entry.path)
903            .with_context(|| format!("cannot absolutize path {path:?}"))?;
904
905        self.fs.load(&abs_path).await
906    }
907}