1use super::{
2 breakpoint_store::BreakpointStore,
3 locator_store::LocatorStore,
4 session::{self, Session},
5};
6use crate::{debugger, worktree_store::WorktreeStore, ProjectEnvironment};
7use anyhow::{anyhow, Result};
8use async_trait::async_trait;
9use collections::HashMap;
10use dap::{
11 adapters::{DapStatus, DebugAdapterName},
12 client::SessionId,
13 messages::Message,
14 requests::{Completions, Evaluate, Request as _, RunInTerminal, StartDebugging},
15 Capabilities, CompletionItem, CompletionsArguments, DapRegistry, ErrorResponse,
16 EvaluateArguments, EvaluateArgumentsContext, EvaluateResponse, RunInTerminalRequestArguments,
17 Source, StartDebuggingRequestArguments,
18};
19use fs::Fs;
20use futures::{
21 channel::{mpsc, oneshot},
22 future::{join_all, Shared},
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 proto::{self},
32 AnyProtoClient, TypedEnvelope,
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::{atomic::Ordering::SeqCst, Arc},
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(Some(worktree.id()), Some(worktree.abs_path()), 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.id()), 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 };
476
477 #[cfg(any(test, feature = "test-support"))]
478 let new_session_task = {
479 let caps = parent_session.read(cx).capabilities.clone();
480 self.new_fake_session(
481 debug_config,
482 &worktree,
483 Some(parent_session.clone()),
484 caps,
485 false,
486 cx,
487 )
488 .1
489 };
490 #[cfg(not(any(test, feature = "test-support")))]
491 let new_session_task = self
492 .new_session(debug_config, &worktree, Some(parent_session.clone()), cx)
493 .1;
494
495 let request_seq = request.seq;
496 cx.spawn(async move |_, cx| {
497 let (success, body) = match new_session_task.await {
498 Ok(_) => (true, None),
499 Err(error) => (
500 false,
501 Some(serde_json::to_value(ErrorResponse {
502 error: Some(dap::Message {
503 id: request_seq,
504 format: error.to_string(),
505 variables: None,
506 send_telemetry: None,
507 show_user: None,
508 url: None,
509 url_label: None,
510 }),
511 })?),
512 ),
513 };
514
515 parent_session
516 .update(cx, |session, cx| {
517 session.respond_to_client(
518 request_seq,
519 success,
520 StartDebugging::COMMAND.to_string(),
521 body,
522 cx,
523 )
524 })?
525 .await
526 })
527 }
528
529 fn handle_run_in_terminal_request(
530 &mut self,
531 session_id: SessionId,
532 request: dap::messages::Request,
533 cx: &mut Context<Self>,
534 ) -> Task<Result<()>> {
535 let Some(session) = self.session_by_id(session_id) else {
536 return Task::ready(Err(anyhow!("Session not found")));
537 };
538
539 let request_args = serde_json::from_value::<RunInTerminalRequestArguments>(
540 request.arguments.unwrap_or_default(),
541 )
542 .expect("To parse StartDebuggingRequestArguments");
543
544 let seq = request.seq;
545
546 let cwd = PathBuf::from(request_args.cwd);
547 match cwd.try_exists() {
548 Ok(true) => (),
549 Ok(false) | Err(_) => {
550 return session.update(cx, |session, cx| {
551 session.respond_to_client(
552 seq,
553 false,
554 RunInTerminal::COMMAND.to_string(),
555 serde_json::to_value(dap::ErrorResponse {
556 error: Some(dap::Message {
557 id: seq,
558 format: format!("Received invalid/unknown cwd: {cwd:?}"),
559 variables: None,
560 send_telemetry: None,
561 show_user: None,
562 url: None,
563 url_label: None,
564 }),
565 })
566 .ok(),
567 cx,
568 )
569 });
570 }
571 }
572
573 let mut args = request_args.args.clone();
574
575 // Handle special case for NodeJS debug adapter
576 // If only the Node binary path is provided, we set the command to None
577 // This prevents the NodeJS REPL from appearing, which is not the desired behavior
578 // The expected usage is for users to provide their own Node command, e.g., `node test.js`
579 // This allows the NodeJS debug client to attach correctly
580 let command = if args.len() > 1 {
581 Some(args.remove(0))
582 } else {
583 None
584 };
585
586 let mut envs: HashMap<String, String> = Default::default();
587 if let Some(Value::Object(env)) = request_args.env {
588 for (key, value) in env {
589 let value_str = match (key.as_str(), value) {
590 (_, Value::String(value)) => value,
591 _ => continue,
592 };
593
594 envs.insert(key, value_str);
595 }
596 }
597
598 let (tx, mut rx) = mpsc::channel::<Result<u32>>(1);
599
600 cx.emit(DapStoreEvent::RunInTerminal {
601 session_id,
602 title: request_args.title,
603 cwd,
604 command,
605 args,
606 envs,
607 sender: tx,
608 });
609 cx.notify();
610
611 let session = session.downgrade();
612 cx.spawn(async move |_, cx| {
613 let (success, body) = match rx.next().await {
614 Some(Ok(pid)) => (
615 true,
616 serde_json::to_value(dap::RunInTerminalResponse {
617 process_id: None,
618 shell_process_id: Some(pid as u64),
619 })
620 .ok(),
621 ),
622 Some(Err(error)) => (
623 false,
624 serde_json::to_value(dap::ErrorResponse {
625 error: Some(dap::Message {
626 id: seq,
627 format: error.to_string(),
628 variables: None,
629 send_telemetry: None,
630 show_user: None,
631 url: None,
632 url_label: None,
633 }),
634 })
635 .ok(),
636 ),
637 None => (
638 false,
639 serde_json::to_value(dap::ErrorResponse {
640 error: Some(dap::Message {
641 id: seq,
642 format: "failed to receive response from spawn terminal".to_string(),
643 variables: None,
644 send_telemetry: None,
645 show_user: None,
646 url: None,
647 url_label: None,
648 }),
649 })
650 .ok(),
651 ),
652 };
653
654 session
655 .update(cx, |session, cx| {
656 session.respond_to_client(
657 seq,
658 success,
659 RunInTerminal::COMMAND.to_string(),
660 body,
661 cx,
662 )
663 })?
664 .await
665 })
666 }
667
668 pub fn evaluate(
669 &self,
670 session_id: &SessionId,
671 stack_frame_id: u64,
672 expression: String,
673 context: EvaluateArgumentsContext,
674 source: Option<Source>,
675 cx: &mut Context<Self>,
676 ) -> Task<Result<EvaluateResponse>> {
677 let Some(client) = self
678 .session_by_id(session_id)
679 .and_then(|client| client.read(cx).adapter_client())
680 else {
681 return Task::ready(Err(anyhow!("Could not find client: {:?}", session_id)));
682 };
683
684 cx.background_executor().spawn(async move {
685 client
686 .request::<Evaluate>(EvaluateArguments {
687 expression: expression.clone(),
688 frame_id: Some(stack_frame_id),
689 context: Some(context),
690 format: None,
691 line: None,
692 column: None,
693 source,
694 })
695 .await
696 })
697 }
698
699 pub fn completions(
700 &self,
701 session_id: &SessionId,
702 stack_frame_id: u64,
703 text: String,
704 completion_column: u64,
705 cx: &mut Context<Self>,
706 ) -> Task<Result<Vec<CompletionItem>>> {
707 let Some(client) = self
708 .session_by_id(session_id)
709 .and_then(|client| client.read(cx).adapter_client())
710 else {
711 return Task::ready(Err(anyhow!("Could not find client: {:?}", session_id)));
712 };
713
714 cx.background_executor().spawn(async move {
715 Ok(client
716 .request::<Completions>(CompletionsArguments {
717 frame_id: Some(stack_frame_id),
718 line: None,
719 text,
720 column: completion_column,
721 })
722 .await?
723 .targets)
724 })
725 }
726
727 pub fn shutdown_sessions(&mut self, cx: &mut Context<Self>) -> Task<()> {
728 let mut tasks = vec![];
729 for session_id in self.sessions.keys().cloned().collect::<Vec<_>>() {
730 tasks.push(self.shutdown_session(session_id, cx));
731 }
732
733 cx.background_executor().spawn(async move {
734 futures::future::join_all(tasks).await;
735 })
736 }
737
738 pub fn shutdown_session(
739 &mut self,
740 session_id: SessionId,
741 cx: &mut Context<Self>,
742 ) -> Task<Result<()>> {
743 let Some(_) = self.as_local_mut() else {
744 return Task::ready(Err(anyhow!("Cannot shutdown session on remote side")));
745 };
746
747 let Some(session) = self.sessions.remove(&session_id) else {
748 return Task::ready(Err(anyhow!("Could not find session: {:?}", session_id)));
749 };
750
751 let shutdown_children = session
752 .read(cx)
753 .child_session_ids()
754 .iter()
755 .map(|session_id| self.shutdown_session(*session_id, cx))
756 .collect::<Vec<_>>();
757
758 let shutdown_parent_task = if let Some(parent_session) = session
759 .read(cx)
760 .parent_id()
761 .and_then(|session_id| self.session_by_id(session_id))
762 {
763 let shutdown_id = parent_session.update(cx, |parent_session, _| {
764 parent_session.remove_child_session_id(session_id);
765
766 if parent_session.child_session_ids().len() == 0 {
767 Some(parent_session.session_id())
768 } else {
769 None
770 }
771 });
772
773 shutdown_id.map(|session_id| self.shutdown_session(session_id, cx))
774 } else {
775 None
776 };
777
778 let shutdown_task = session.update(cx, |this, cx| this.shutdown(cx));
779
780 cx.background_spawn(async move {
781 if shutdown_children.len() > 0 {
782 let _ = join_all(shutdown_children).await;
783 }
784
785 shutdown_task.await;
786
787 if let Some(parent_task) = shutdown_parent_task {
788 parent_task.await?;
789 }
790
791 Ok(())
792 })
793 }
794
795 pub fn shared(
796 &mut self,
797 project_id: u64,
798 downstream_client: AnyProtoClient,
799 _: &mut Context<Self>,
800 ) {
801 self.downstream_client = Some((downstream_client.clone(), project_id));
802 }
803
804 pub fn unshared(&mut self, cx: &mut Context<Self>) {
805 self.downstream_client.take();
806
807 cx.notify();
808 }
809}
810
811fn create_new_session(
812 session_id: SessionId,
813 initialized_rx: oneshot::Receiver<()>,
814 start_client_task: Task<Result<Entity<Session>, anyhow::Error>>,
815 cx: &mut Context<DapStore>,
816) -> Task<Result<Entity<Session>>> {
817 let task = cx.spawn(async move |this, cx| {
818 let session = match start_client_task.await {
819 Ok(session) => session,
820 Err(error) => {
821 this.update(cx, |_, cx| {
822 cx.emit(DapStoreEvent::Notification(error.to_string()));
823 })
824 .log_err();
825
826 return Err(error);
827 }
828 };
829
830 // we have to insert the session early, so we can handle reverse requests
831 // that need the session to be available
832 this.update(cx, |store, cx| {
833 store.sessions.insert(session_id, session.clone());
834 cx.emit(DapStoreEvent::DebugClientStarted(session_id));
835 cx.notify();
836 })?;
837
838 match session
839 .update(cx, |session, cx| {
840 session.initialize_sequence(initialized_rx, cx)
841 })?
842 .await
843 {
844 Ok(_) => {}
845 Err(error) => {
846 this.update(cx, |this, cx| {
847 cx.emit(DapStoreEvent::Notification(error.to_string()));
848
849 this.shutdown_session(session_id, cx)
850 })?
851 .await
852 .log_err();
853
854 return Err(error);
855 }
856 }
857
858 Ok(session)
859 });
860 task
861}
862
863#[derive(Clone)]
864pub struct DapAdapterDelegate {
865 fs: Arc<dyn Fs>,
866 worktree_id: WorktreeId,
867 node_runtime: NodeRuntime,
868 http_client: Arc<dyn HttpClient>,
869 language_registry: Arc<LanguageRegistry>,
870 toolchain_store: Arc<dyn LanguageToolchainStore>,
871 updated_adapters: Arc<Mutex<HashSet<DebugAdapterName>>>,
872 load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
873}
874
875impl DapAdapterDelegate {
876 pub fn new(
877 fs: Arc<dyn Fs>,
878 worktree_id: WorktreeId,
879 node_runtime: NodeRuntime,
880 http_client: Arc<dyn HttpClient>,
881 language_registry: Arc<LanguageRegistry>,
882 toolchain_store: Arc<dyn LanguageToolchainStore>,
883 load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
884 ) -> Self {
885 Self {
886 fs,
887 worktree_id,
888 http_client,
889 node_runtime,
890 toolchain_store,
891 language_registry,
892 load_shell_env_task,
893 updated_adapters: Default::default(),
894 }
895 }
896}
897
898#[async_trait(?Send)]
899impl dap::adapters::DapDelegate for DapAdapterDelegate {
900 fn worktree_id(&self) -> WorktreeId {
901 self.worktree_id
902 }
903
904 fn http_client(&self) -> Arc<dyn HttpClient> {
905 self.http_client.clone()
906 }
907
908 fn node_runtime(&self) -> NodeRuntime {
909 self.node_runtime.clone()
910 }
911
912 fn fs(&self) -> Arc<dyn Fs> {
913 self.fs.clone()
914 }
915
916 fn updated_adapters(&self) -> Arc<Mutex<HashSet<DebugAdapterName>>> {
917 self.updated_adapters.clone()
918 }
919
920 fn update_status(&self, dap_name: DebugAdapterName, status: dap::adapters::DapStatus) {
921 let name = SharedString::from(dap_name.to_string());
922 let status = match status {
923 DapStatus::None => BinaryStatus::None,
924 DapStatus::Downloading => BinaryStatus::Downloading,
925 DapStatus::Failed { error } => BinaryStatus::Failed { error },
926 DapStatus::CheckingForUpdate => BinaryStatus::CheckingForUpdate,
927 };
928
929 self.language_registry
930 .update_dap_status(LanguageServerName(name), status);
931 }
932
933 fn which(&self, command: &OsStr) -> Option<PathBuf> {
934 which::which(command).ok()
935 }
936
937 async fn shell_env(&self) -> HashMap<String, String> {
938 let task = self.load_shell_env_task.clone();
939 task.await.unwrap_or_default()
940 }
941
942 fn toolchain_store(&self) -> Arc<dyn LanguageToolchainStore> {
943 self.toolchain_store.clone()
944 }
945}