dap_store.rs

  1use super::{
  2    breakpoint_store::BreakpointStore,
  3    locator_store::LocatorStore,
  4    session::{self, Session},
  5};
  6use crate::{ProjectEnvironment, debugger, worktree_store::WorktreeStore};
  7use anyhow::{Result, anyhow};
  8use async_trait::async_trait;
  9use collections::HashMap;
 10use dap::{
 11    Capabilities, CompletionItem, CompletionsArguments, DapRegistry, ErrorResponse,
 12    EvaluateArguments, EvaluateArgumentsContext, EvaluateResponse, RunInTerminalRequestArguments,
 13    Source, StartDebuggingRequestArguments,
 14    adapters::{DapStatus, DebugAdapterName},
 15    client::SessionId,
 16    messages::Message,
 17    requests::{Completions, Evaluate, Request as _, RunInTerminal, StartDebugging},
 18};
 19use fs::Fs;
 20use futures::{
 21    channel::{mpsc, oneshot},
 22    future::{Shared, join_all},
 23};
 24use gpui::{App, AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task};
 25use http_client::HttpClient;
 26use language::{BinaryStatus, LanguageRegistry, LanguageToolchainStore};
 27use lsp::LanguageServerName;
 28use node_runtime::NodeRuntime;
 29
 30use rpc::{
 31    AnyProtoClient, TypedEnvelope,
 32    proto::{self},
 33};
 34use serde_json::Value;
 35use settings::WorktreeId;
 36use smol::{lock::Mutex, stream::StreamExt};
 37use std::{
 38    borrow::Borrow,
 39    collections::{BTreeMap, HashSet},
 40    ffi::OsStr,
 41    path::PathBuf,
 42    sync::{Arc, atomic::Ordering::SeqCst},
 43};
 44use std::{collections::VecDeque, sync::atomic::AtomicU32};
 45use task::{DebugAdapterConfig, DebugRequestDisposition};
 46use util::ResultExt as _;
 47use worktree::Worktree;
 48
 49pub enum DapStoreEvent {
 50    DebugClientStarted(SessionId),
 51    DebugClientShutdown(SessionId),
 52    DebugClientEvent {
 53        session_id: SessionId,
 54        message: Message,
 55    },
 56    RunInTerminal {
 57        session_id: SessionId,
 58        title: Option<String>,
 59        cwd: PathBuf,
 60        command: Option<String>,
 61        args: Vec<String>,
 62        envs: HashMap<String, String>,
 63        sender: mpsc::Sender<Result<u32>>,
 64    },
 65    Notification(String),
 66    RemoteHasInitialized,
 67}
 68
 69#[allow(clippy::large_enum_variant)]
 70pub enum DapStoreMode {
 71    Local(LocalDapStore),   // ssh host and collab host
 72    Remote(RemoteDapStore), // collab guest
 73}
 74
 75pub struct LocalDapStore {
 76    fs: Arc<dyn Fs>,
 77    node_runtime: NodeRuntime,
 78    next_session_id: AtomicU32,
 79    http_client: Arc<dyn HttpClient>,
 80    worktree_store: Entity<WorktreeStore>,
 81    environment: Entity<ProjectEnvironment>,
 82    language_registry: Arc<LanguageRegistry>,
 83    debug_adapters: Arc<DapRegistry>,
 84    toolchain_store: Arc<dyn LanguageToolchainStore>,
 85    locator_store: Arc<LocatorStore>,
 86    start_debugging_tx: futures::channel::mpsc::UnboundedSender<(SessionId, Message)>,
 87    _start_debugging_task: Task<()>,
 88}
 89
 90impl LocalDapStore {
 91    fn next_session_id(&self) -> SessionId {
 92        SessionId(self.next_session_id.fetch_add(1, SeqCst))
 93    }
 94}
 95
 96pub struct RemoteDapStore {
 97    upstream_client: AnyProtoClient,
 98    upstream_project_id: u64,
 99    event_queue: Option<VecDeque<DapStoreEvent>>,
100}
101
102pub struct DapStore {
103    mode: DapStoreMode,
104    downstream_client: Option<(AnyProtoClient, u64)>,
105    breakpoint_store: Entity<BreakpointStore>,
106    sessions: BTreeMap<SessionId, Entity<Session>>,
107}
108
109impl EventEmitter<DapStoreEvent> for DapStore {}
110
111impl DapStore {
112    pub fn init(_client: &AnyProtoClient) {
113        // todo(debugger): Reenable these after we finish handle_dap_command refactor
114        // client.add_entity_request_handler(Self::handle_dap_command::<NextCommand>);
115        // client.add_entity_request_handler(Self::handle_dap_command::<StepInCommand>);
116        // client.add_entity_request_handler(Self::handle_dap_command::<StepOutCommand>);
117        // client.add_entity_request_handler(Self::handle_dap_command::<StepBackCommand>);
118        // client.add_entity_request_handler(Self::handle_dap_command::<ContinueCommand>);
119        // client.add_entity_request_handler(Self::handle_dap_command::<PauseCommand>);
120        // client.add_entity_request_handler(Self::handle_dap_command::<DisconnectCommand>);
121        // client.add_entity_request_handler(Self::handle_dap_command::<TerminateThreadsCommand>);
122        // client.add_entity_request_handler(Self::handle_dap_command::<TerminateCommand>);
123        // client.add_entity_request_handler(Self::handle_dap_command::<RestartCommand>);
124        // client.add_entity_request_handler(Self::handle_dap_command::<VariablesCommand>);
125        // client.add_entity_request_handler(Self::handle_dap_command::<RestartStackFrameCommand>);
126    }
127
128    #[expect(clippy::too_many_arguments)]
129    pub fn new_local(
130        http_client: Arc<dyn HttpClient>,
131        node_runtime: NodeRuntime,
132        fs: Arc<dyn Fs>,
133        language_registry: Arc<LanguageRegistry>,
134        debug_adapters: Arc<DapRegistry>,
135        environment: Entity<ProjectEnvironment>,
136        toolchain_store: Arc<dyn LanguageToolchainStore>,
137        breakpoint_store: Entity<BreakpointStore>,
138        worktree_store: Entity<WorktreeStore>,
139        cx: &mut Context<Self>,
140    ) -> Self {
141        cx.on_app_quit(Self::shutdown_sessions).detach();
142
143        let (start_debugging_tx, mut message_rx) =
144            futures::channel::mpsc::unbounded::<(SessionId, Message)>();
145
146        let _start_debugging_task = cx.spawn(async move |this, cx| {
147            while let Some((session_id, message)) = message_rx.next().await {
148                match message {
149                    Message::Request(request) => {
150                        let _ = this
151                            .update(cx, |this, cx| {
152                                if request.command == StartDebugging::COMMAND {
153                                    this.handle_start_debugging_request(session_id, request, cx)
154                                        .detach_and_log_err(cx);
155                                } else if request.command == RunInTerminal::COMMAND {
156                                    this.handle_run_in_terminal_request(session_id, request, cx)
157                                        .detach_and_log_err(cx);
158                                }
159                            })
160                            .log_err();
161                    }
162                    _ => {}
163                }
164            }
165        });
166        Self {
167            mode: DapStoreMode::Local(LocalDapStore {
168                fs,
169                environment,
170                http_client,
171                node_runtime,
172                worktree_store,
173                toolchain_store,
174                language_registry,
175                debug_adapters,
176                start_debugging_tx,
177                _start_debugging_task,
178                locator_store: Arc::from(LocatorStore::new()),
179                next_session_id: Default::default(),
180            }),
181            downstream_client: None,
182            breakpoint_store,
183            sessions: Default::default(),
184        }
185    }
186
187    pub fn new_remote(
188        project_id: u64,
189        upstream_client: AnyProtoClient,
190        breakpoint_store: Entity<BreakpointStore>,
191    ) -> Self {
192        Self {
193            mode: DapStoreMode::Remote(RemoteDapStore {
194                upstream_client,
195                upstream_project_id: project_id,
196                event_queue: Some(VecDeque::default()),
197            }),
198            downstream_client: None,
199            breakpoint_store,
200            sessions: Default::default(),
201        }
202    }
203
204    pub fn as_remote(&self) -> Option<&RemoteDapStore> {
205        match &self.mode {
206            DapStoreMode::Remote(remote_dap_store) => Some(remote_dap_store),
207            _ => None,
208        }
209    }
210
211    pub fn remote_event_queue(&mut self) -> Option<VecDeque<DapStoreEvent>> {
212        if let DapStoreMode::Remote(remote) = &mut self.mode {
213            remote.event_queue.take()
214        } else {
215            None
216        }
217    }
218
219    pub fn as_local(&self) -> Option<&LocalDapStore> {
220        match &self.mode {
221            DapStoreMode::Local(local_dap_store) => Some(local_dap_store),
222            _ => None,
223        }
224    }
225
226    pub fn as_local_mut(&mut self) -> Option<&mut LocalDapStore> {
227        match &mut self.mode {
228            DapStoreMode::Local(local_dap_store) => Some(local_dap_store),
229            _ => None,
230        }
231    }
232
233    pub fn upstream_client(&self) -> Option<(AnyProtoClient, u64)> {
234        match &self.mode {
235            DapStoreMode::Remote(RemoteDapStore {
236                upstream_client,
237                upstream_project_id,
238                ..
239            }) => Some((upstream_client.clone(), *upstream_project_id)),
240
241            DapStoreMode::Local(_) => None,
242        }
243    }
244
245    pub fn downstream_client(&self) -> Option<&(AnyProtoClient, u64)> {
246        self.downstream_client.as_ref()
247    }
248
249    pub fn add_remote_client(
250        &mut self,
251        session_id: SessionId,
252        ignore: Option<bool>,
253        cx: &mut Context<Self>,
254    ) {
255        if let DapStoreMode::Remote(remote) = &self.mode {
256            self.sessions.insert(
257                session_id,
258                cx.new(|_| {
259                    debugger::session::Session::remote(
260                        session_id,
261                        remote.upstream_client.clone(),
262                        remote.upstream_project_id,
263                        ignore.unwrap_or(false),
264                    )
265                }),
266            );
267        } else {
268            debug_assert!(false);
269        }
270    }
271
272    pub fn session_by_id(
273        &self,
274        session_id: impl Borrow<SessionId>,
275    ) -> Option<Entity<session::Session>> {
276        let session_id = session_id.borrow();
277        let client = self.sessions.get(session_id).cloned();
278
279        client
280    }
281    pub fn sessions(&self) -> impl Iterator<Item = &Entity<Session>> {
282        self.sessions.values()
283    }
284
285    pub fn capabilities_by_id(
286        &self,
287        session_id: impl Borrow<SessionId>,
288        cx: &App,
289    ) -> Option<Capabilities> {
290        let session_id = session_id.borrow();
291        self.sessions
292            .get(session_id)
293            .map(|client| client.read(cx).capabilities.clone())
294    }
295
296    pub fn breakpoint_store(&self) -> &Entity<BreakpointStore> {
297        &self.breakpoint_store
298    }
299
300    #[allow(dead_code)]
301    async fn handle_ignore_breakpoint_state(
302        this: Entity<Self>,
303        envelope: TypedEnvelope<proto::IgnoreBreakpointState>,
304        mut cx: AsyncApp,
305    ) -> Result<()> {
306        let session_id = SessionId::from_proto(envelope.payload.session_id);
307
308        this.update(&mut cx, |this, cx| {
309            if let Some(session) = this.session_by_id(&session_id) {
310                session.update(cx, |session, cx| {
311                    session.set_ignore_breakpoints(envelope.payload.ignore, cx)
312                })
313            } else {
314                Task::ready(())
315            }
316        })?
317        .await;
318
319        Ok(())
320    }
321
322    pub fn new_session(
323        &mut self,
324        mut config: DebugAdapterConfig,
325        worktree: &Entity<Worktree>,
326        parent_session: Option<Entity<Session>>,
327        cx: &mut Context<Self>,
328    ) -> (SessionId, Task<Result<Entity<Session>>>) {
329        let Some(local_store) = self.as_local() else {
330            unimplemented!("Starting session on remote side");
331        };
332
333        let delegate = DapAdapterDelegate::new(
334            local_store.fs.clone(),
335            worktree.read(cx).id(),
336            local_store.node_runtime.clone(),
337            local_store.http_client.clone(),
338            local_store.language_registry.clone(),
339            local_store.toolchain_store.clone(),
340            local_store.environment.update(cx, |env, cx| {
341                let worktree = worktree.read(cx);
342                env.get_environment(worktree.abs_path().into(), cx)
343            }),
344        );
345        let session_id = local_store.next_session_id();
346
347        if let Some(session) = &parent_session {
348            session.update(cx, |session, _| {
349                session.add_child_session_id(session_id);
350            });
351        }
352
353        let (initialized_tx, initialized_rx) = oneshot::channel();
354        let locator_store = local_store.locator_store.clone();
355        let debug_adapters = local_store.debug_adapters.clone();
356
357        let start_debugging_tx = local_store.start_debugging_tx.clone();
358
359        let task = cx.spawn(async move |this, cx| {
360            if config.locator.is_some() {
361                locator_store.resolve_debug_config(&mut config).await?;
362            }
363
364            let start_client_task = this.update(cx, |this, cx| {
365                Session::local(
366                    this.breakpoint_store.clone(),
367                    session_id,
368                    parent_session,
369                    delegate,
370                    config,
371                    start_debugging_tx.clone(),
372                    initialized_tx,
373                    debug_adapters,
374                    cx,
375                )
376            })?;
377
378            this.update(cx, |_, cx| {
379                create_new_session(session_id, initialized_rx, start_client_task, cx)
380            })?
381            .await
382        });
383
384        (session_id, task)
385    }
386
387    #[cfg(any(test, feature = "test-support"))]
388    pub fn new_fake_session(
389        &mut self,
390        config: DebugAdapterConfig,
391        worktree: &Entity<Worktree>,
392        parent_session: Option<Entity<Session>>,
393        caps: Capabilities,
394        fails: bool,
395        cx: &mut Context<Self>,
396    ) -> (SessionId, Task<Result<Entity<Session>>>) {
397        let Some(local_store) = self.as_local() else {
398            unimplemented!("Starting session on remote side");
399        };
400
401        let delegate = DapAdapterDelegate::new(
402            local_store.fs.clone(),
403            worktree.read(cx).id(),
404            local_store.node_runtime.clone(),
405            local_store.http_client.clone(),
406            local_store.language_registry.clone(),
407            local_store.toolchain_store.clone(),
408            local_store.environment.update(cx, |env, cx| {
409                let worktree = worktree.read(cx);
410                env.get_environment(Some(worktree.abs_path()), cx)
411            }),
412        );
413        let session_id = local_store.next_session_id();
414
415        if let Some(session) = &parent_session {
416            session.update(cx, |session, _| {
417                session.add_child_session_id(session_id);
418            });
419        }
420
421        let (initialized_tx, initialized_rx) = oneshot::channel();
422
423        let start_client_task = Session::fake(
424            self.breakpoint_store.clone(),
425            session_id,
426            parent_session,
427            delegate,
428            config,
429            local_store.start_debugging_tx.clone(),
430            initialized_tx,
431            caps,
432            fails,
433            cx,
434        );
435
436        let task = create_new_session(session_id, initialized_rx, start_client_task, cx);
437        (session_id, task)
438    }
439
440    fn handle_start_debugging_request(
441        &mut self,
442        session_id: SessionId,
443        request: dap::messages::Request,
444        cx: &mut Context<Self>,
445    ) -> Task<Result<()>> {
446        let Some(local_store) = self.as_local() else {
447            unreachable!("Cannot response for non-local session");
448        };
449
450        let Some(parent_session) = self.session_by_id(session_id) else {
451            return Task::ready(Err(anyhow!("Session not found")));
452        };
453
454        let args = serde_json::from_value::<StartDebuggingRequestArguments>(
455            request.arguments.unwrap_or_default(),
456        )
457        .expect("To parse StartDebuggingRequestArguments");
458        let worktree = local_store
459            .worktree_store
460            .update(cx, |this, _| this.worktrees().next())
461            .expect("worktree-less project");
462
463        let Some(config) = parent_session.read(cx).configuration() else {
464            unreachable!("there must be a config for local sessions");
465        };
466
467        let debug_config = DebugAdapterConfig {
468            label: config.label,
469            adapter: config.adapter,
470            request: DebugRequestDisposition::ReverseRequest(args),
471            initialize_args: config.initialize_args.clone(),
472            tcp_connection: config.tcp_connection.clone(),
473            locator: None,
474            args: Default::default(),
475            stop_on_entry: config.stop_on_entry,
476        };
477
478        #[cfg(any(test, feature = "test-support"))]
479        let new_session_task = {
480            let caps = parent_session.read(cx).capabilities.clone();
481            self.new_fake_session(
482                debug_config,
483                &worktree,
484                Some(parent_session.clone()),
485                caps,
486                false,
487                cx,
488            )
489            .1
490        };
491        #[cfg(not(any(test, feature = "test-support")))]
492        let new_session_task = self
493            .new_session(debug_config, &worktree, Some(parent_session.clone()), cx)
494            .1;
495
496        let request_seq = request.seq;
497        cx.spawn(async move |_, cx| {
498            let (success, body) = match new_session_task.await {
499                Ok(_) => (true, None),
500                Err(error) => (
501                    false,
502                    Some(serde_json::to_value(ErrorResponse {
503                        error: Some(dap::Message {
504                            id: request_seq,
505                            format: error.to_string(),
506                            variables: None,
507                            send_telemetry: None,
508                            show_user: None,
509                            url: None,
510                            url_label: None,
511                        }),
512                    })?),
513                ),
514            };
515
516            parent_session
517                .update(cx, |session, cx| {
518                    session.respond_to_client(
519                        request_seq,
520                        success,
521                        StartDebugging::COMMAND.to_string(),
522                        body,
523                        cx,
524                    )
525                })?
526                .await
527        })
528    }
529
530    fn handle_run_in_terminal_request(
531        &mut self,
532        session_id: SessionId,
533        request: dap::messages::Request,
534        cx: &mut Context<Self>,
535    ) -> Task<Result<()>> {
536        let Some(session) = self.session_by_id(session_id) else {
537            return Task::ready(Err(anyhow!("Session not found")));
538        };
539
540        let request_args = serde_json::from_value::<RunInTerminalRequestArguments>(
541            request.arguments.unwrap_or_default(),
542        )
543        .expect("To parse StartDebuggingRequestArguments");
544
545        let seq = request.seq;
546
547        let cwd = PathBuf::from(request_args.cwd);
548        match cwd.try_exists() {
549            Ok(true) => (),
550            Ok(false) | Err(_) => {
551                return session.update(cx, |session, cx| {
552                    session.respond_to_client(
553                        seq,
554                        false,
555                        RunInTerminal::COMMAND.to_string(),
556                        serde_json::to_value(dap::ErrorResponse {
557                            error: Some(dap::Message {
558                                id: seq,
559                                format: format!("Received invalid/unknown cwd: {cwd:?}"),
560                                variables: None,
561                                send_telemetry: None,
562                                show_user: None,
563                                url: None,
564                                url_label: None,
565                            }),
566                        })
567                        .ok(),
568                        cx,
569                    )
570                });
571            }
572        }
573
574        let mut args = request_args.args.clone();
575
576        // Handle special case for NodeJS debug adapter
577        // If only the Node binary path is provided, we set the command to None
578        // This prevents the NodeJS REPL from appearing, which is not the desired behavior
579        // The expected usage is for users to provide their own Node command, e.g., `node test.js`
580        // This allows the NodeJS debug client to attach correctly
581        let command = if args.len() > 1 {
582            Some(args.remove(0))
583        } else {
584            None
585        };
586
587        let mut envs: HashMap<String, String> = Default::default();
588        if let Some(Value::Object(env)) = request_args.env {
589            for (key, value) in env {
590                let value_str = match (key.as_str(), value) {
591                    (_, Value::String(value)) => value,
592                    _ => continue,
593                };
594
595                envs.insert(key, value_str);
596            }
597        }
598
599        let (tx, mut rx) = mpsc::channel::<Result<u32>>(1);
600
601        cx.emit(DapStoreEvent::RunInTerminal {
602            session_id,
603            title: request_args.title,
604            cwd,
605            command,
606            args,
607            envs,
608            sender: tx,
609        });
610        cx.notify();
611
612        let session = session.downgrade();
613        cx.spawn(async move |_, cx| {
614            let (success, body) = match rx.next().await {
615                Some(Ok(pid)) => (
616                    true,
617                    serde_json::to_value(dap::RunInTerminalResponse {
618                        process_id: None,
619                        shell_process_id: Some(pid as u64),
620                    })
621                    .ok(),
622                ),
623                Some(Err(error)) => (
624                    false,
625                    serde_json::to_value(dap::ErrorResponse {
626                        error: Some(dap::Message {
627                            id: seq,
628                            format: error.to_string(),
629                            variables: None,
630                            send_telemetry: None,
631                            show_user: None,
632                            url: None,
633                            url_label: None,
634                        }),
635                    })
636                    .ok(),
637                ),
638                None => (
639                    false,
640                    serde_json::to_value(dap::ErrorResponse {
641                        error: Some(dap::Message {
642                            id: seq,
643                            format: "failed to receive response from spawn terminal".to_string(),
644                            variables: None,
645                            send_telemetry: None,
646                            show_user: None,
647                            url: None,
648                            url_label: None,
649                        }),
650                    })
651                    .ok(),
652                ),
653            };
654
655            session
656                .update(cx, |session, cx| {
657                    session.respond_to_client(
658                        seq,
659                        success,
660                        RunInTerminal::COMMAND.to_string(),
661                        body,
662                        cx,
663                    )
664                })?
665                .await
666        })
667    }
668
669    pub fn evaluate(
670        &self,
671        session_id: &SessionId,
672        stack_frame_id: u64,
673        expression: String,
674        context: EvaluateArgumentsContext,
675        source: Option<Source>,
676        cx: &mut Context<Self>,
677    ) -> Task<Result<EvaluateResponse>> {
678        let Some(client) = self
679            .session_by_id(session_id)
680            .and_then(|client| client.read(cx).adapter_client())
681        else {
682            return Task::ready(Err(anyhow!("Could not find client: {:?}", session_id)));
683        };
684
685        cx.background_executor().spawn(async move {
686            client
687                .request::<Evaluate>(EvaluateArguments {
688                    expression: expression.clone(),
689                    frame_id: Some(stack_frame_id),
690                    context: Some(context),
691                    format: None,
692                    line: None,
693                    column: None,
694                    source,
695                })
696                .await
697        })
698    }
699
700    pub fn completions(
701        &self,
702        session_id: &SessionId,
703        stack_frame_id: u64,
704        text: String,
705        completion_column: u64,
706        cx: &mut Context<Self>,
707    ) -> Task<Result<Vec<CompletionItem>>> {
708        let Some(client) = self
709            .session_by_id(session_id)
710            .and_then(|client| client.read(cx).adapter_client())
711        else {
712            return Task::ready(Err(anyhow!("Could not find client: {:?}", session_id)));
713        };
714
715        cx.background_executor().spawn(async move {
716            Ok(client
717                .request::<Completions>(CompletionsArguments {
718                    frame_id: Some(stack_frame_id),
719                    line: None,
720                    text,
721                    column: completion_column,
722                })
723                .await?
724                .targets)
725        })
726    }
727
728    pub fn shutdown_sessions(&mut self, cx: &mut Context<Self>) -> Task<()> {
729        let mut tasks = vec![];
730        for session_id in self.sessions.keys().cloned().collect::<Vec<_>>() {
731            tasks.push(self.shutdown_session(session_id, cx));
732        }
733
734        cx.background_executor().spawn(async move {
735            futures::future::join_all(tasks).await;
736        })
737    }
738
739    pub fn shutdown_session(
740        &mut self,
741        session_id: SessionId,
742        cx: &mut Context<Self>,
743    ) -> Task<Result<()>> {
744        let Some(_) = self.as_local_mut() else {
745            return Task::ready(Err(anyhow!("Cannot shutdown session on remote side")));
746        };
747
748        let Some(session) = self.sessions.remove(&session_id) else {
749            return Task::ready(Err(anyhow!("Could not find session: {:?}", session_id)));
750        };
751
752        let shutdown_children = session
753            .read(cx)
754            .child_session_ids()
755            .iter()
756            .map(|session_id| self.shutdown_session(*session_id, cx))
757            .collect::<Vec<_>>();
758
759        let shutdown_parent_task = if let Some(parent_session) = session
760            .read(cx)
761            .parent_id()
762            .and_then(|session_id| self.session_by_id(session_id))
763        {
764            let shutdown_id = parent_session.update(cx, |parent_session, _| {
765                parent_session.remove_child_session_id(session_id);
766
767                if parent_session.child_session_ids().len() == 0 {
768                    Some(parent_session.session_id())
769                } else {
770                    None
771                }
772            });
773
774            shutdown_id.map(|session_id| self.shutdown_session(session_id, cx))
775        } else {
776            None
777        };
778
779        let shutdown_task = session.update(cx, |this, cx| this.shutdown(cx));
780
781        cx.background_spawn(async move {
782            if shutdown_children.len() > 0 {
783                let _ = join_all(shutdown_children).await;
784            }
785
786            shutdown_task.await;
787
788            if let Some(parent_task) = shutdown_parent_task {
789                parent_task.await?;
790            }
791
792            Ok(())
793        })
794    }
795
796    pub fn shared(
797        &mut self,
798        project_id: u64,
799        downstream_client: AnyProtoClient,
800        _: &mut Context<Self>,
801    ) {
802        self.downstream_client = Some((downstream_client.clone(), project_id));
803    }
804
805    pub fn unshared(&mut self, cx: &mut Context<Self>) {
806        self.downstream_client.take();
807
808        cx.notify();
809    }
810}
811
812fn create_new_session(
813    session_id: SessionId,
814    initialized_rx: oneshot::Receiver<()>,
815    start_client_task: Task<Result<Entity<Session>, anyhow::Error>>,
816    cx: &mut Context<DapStore>,
817) -> Task<Result<Entity<Session>>> {
818    let task = cx.spawn(async move |this, cx| {
819        let session = match start_client_task.await {
820            Ok(session) => session,
821            Err(error) => {
822                this.update(cx, |_, cx| {
823                    cx.emit(DapStoreEvent::Notification(error.to_string()));
824                })
825                .log_err();
826
827                return Err(error);
828            }
829        };
830
831        // we have to insert the session early, so we can handle reverse requests
832        // that need the session to be available
833        this.update(cx, |store, cx| {
834            store.sessions.insert(session_id, session.clone());
835            cx.emit(DapStoreEvent::DebugClientStarted(session_id));
836            cx.notify();
837        })?;
838
839        match session
840            .update(cx, |session, cx| {
841                session.initialize_sequence(initialized_rx, cx)
842            })?
843            .await
844        {
845            Ok(_) => {}
846            Err(error) => {
847                this.update(cx, |this, cx| {
848                    cx.emit(DapStoreEvent::Notification(error.to_string()));
849
850                    this.shutdown_session(session_id, cx)
851                })?
852                .await
853                .log_err();
854
855                return Err(error);
856            }
857        }
858
859        Ok(session)
860    });
861    task
862}
863
864#[derive(Clone)]
865pub struct DapAdapterDelegate {
866    fs: Arc<dyn Fs>,
867    worktree_id: WorktreeId,
868    node_runtime: NodeRuntime,
869    http_client: Arc<dyn HttpClient>,
870    language_registry: Arc<LanguageRegistry>,
871    toolchain_store: Arc<dyn LanguageToolchainStore>,
872    updated_adapters: Arc<Mutex<HashSet<DebugAdapterName>>>,
873    load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
874}
875
876impl DapAdapterDelegate {
877    pub fn new(
878        fs: Arc<dyn Fs>,
879        worktree_id: WorktreeId,
880        node_runtime: NodeRuntime,
881        http_client: Arc<dyn HttpClient>,
882        language_registry: Arc<LanguageRegistry>,
883        toolchain_store: Arc<dyn LanguageToolchainStore>,
884        load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
885    ) -> Self {
886        Self {
887            fs,
888            worktree_id,
889            http_client,
890            node_runtime,
891            toolchain_store,
892            language_registry,
893            load_shell_env_task,
894            updated_adapters: Default::default(),
895        }
896    }
897}
898
899#[async_trait(?Send)]
900impl dap::adapters::DapDelegate for DapAdapterDelegate {
901    fn worktree_id(&self) -> WorktreeId {
902        self.worktree_id
903    }
904
905    fn http_client(&self) -> Arc<dyn HttpClient> {
906        self.http_client.clone()
907    }
908
909    fn node_runtime(&self) -> NodeRuntime {
910        self.node_runtime.clone()
911    }
912
913    fn fs(&self) -> Arc<dyn Fs> {
914        self.fs.clone()
915    }
916
917    fn updated_adapters(&self) -> Arc<Mutex<HashSet<DebugAdapterName>>> {
918        self.updated_adapters.clone()
919    }
920
921    fn update_status(&self, dap_name: DebugAdapterName, status: dap::adapters::DapStatus) {
922        let name = SharedString::from(dap_name.to_string());
923        let status = match status {
924            DapStatus::None => BinaryStatus::None,
925            DapStatus::Downloading => BinaryStatus::Downloading,
926            DapStatus::Failed { error } => BinaryStatus::Failed { error },
927            DapStatus::CheckingForUpdate => BinaryStatus::CheckingForUpdate,
928        };
929
930        self.language_registry
931            .update_dap_status(LanguageServerName(name), status);
932    }
933
934    fn which(&self, command: &OsStr) -> Option<PathBuf> {
935        which::which(command).ok()
936    }
937
938    async fn shell_env(&self) -> HashMap<String, String> {
939        let task = self.load_shell_env_task.clone();
940        task.await.unwrap_or_default()
941    }
942
943    fn toolchain_store(&self) -> Arc<dyn LanguageToolchainStore> {
944        self.toolchain_store.clone()
945    }
946}