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 env.get_worktree_environment(worktree.clone(), cx)
342 }),
343 );
344 let session_id = local_store.next_session_id();
345
346 if let Some(session) = &parent_session {
347 session.update(cx, |session, _| {
348 session.add_child_session_id(session_id);
349 });
350 }
351
352 let (initialized_tx, initialized_rx) = oneshot::channel();
353 let locator_store = local_store.locator_store.clone();
354 let debug_adapters = local_store.debug_adapters.clone();
355
356 let start_debugging_tx = local_store.start_debugging_tx.clone();
357
358 let task = cx.spawn(async move |this, cx| {
359 if config.locator.is_some() {
360 locator_store.resolve_debug_config(&mut config).await?;
361 }
362
363 let start_client_task = this.update(cx, |this, cx| {
364 Session::local(
365 this.breakpoint_store.clone(),
366 session_id,
367 parent_session,
368 delegate,
369 config,
370 start_debugging_tx.clone(),
371 initialized_tx,
372 debug_adapters,
373 cx,
374 )
375 })?;
376
377 this.update(cx, |_, cx| {
378 create_new_session(session_id, initialized_rx, start_client_task, cx)
379 })?
380 .await
381 });
382
383 (session_id, task)
384 }
385
386 #[cfg(any(test, feature = "test-support"))]
387 pub fn new_fake_session(
388 &mut self,
389 config: DebugAdapterConfig,
390 worktree: &Entity<Worktree>,
391 parent_session: Option<Entity<Session>>,
392 caps: Capabilities,
393 fails: bool,
394 cx: &mut Context<Self>,
395 ) -> (SessionId, Task<Result<Entity<Session>>>) {
396 let Some(local_store) = self.as_local() else {
397 unimplemented!("Starting session on remote side");
398 };
399
400 let delegate = DapAdapterDelegate::new(
401 local_store.fs.clone(),
402 worktree.read(cx).id(),
403 local_store.node_runtime.clone(),
404 local_store.http_client.clone(),
405 local_store.language_registry.clone(),
406 local_store.toolchain_store.clone(),
407 local_store.environment.update(cx, |env, cx| {
408 env.get_worktree_environment(worktree.clone(), cx)
409 }),
410 );
411 let session_id = local_store.next_session_id();
412
413 if let Some(session) = &parent_session {
414 session.update(cx, |session, _| {
415 session.add_child_session_id(session_id);
416 });
417 }
418
419 let (initialized_tx, initialized_rx) = oneshot::channel();
420
421 let start_client_task = Session::fake(
422 self.breakpoint_store.clone(),
423 session_id,
424 parent_session,
425 delegate,
426 config,
427 local_store.start_debugging_tx.clone(),
428 initialized_tx,
429 caps,
430 fails,
431 cx,
432 );
433
434 let task = create_new_session(session_id, initialized_rx, start_client_task, cx);
435 (session_id, task)
436 }
437
438 fn handle_start_debugging_request(
439 &mut self,
440 session_id: SessionId,
441 request: dap::messages::Request,
442 cx: &mut Context<Self>,
443 ) -> Task<Result<()>> {
444 let Some(local_store) = self.as_local() else {
445 unreachable!("Cannot response for non-local session");
446 };
447
448 let Some(parent_session) = self.session_by_id(session_id) else {
449 return Task::ready(Err(anyhow!("Session not found")));
450 };
451
452 let args = serde_json::from_value::<StartDebuggingRequestArguments>(
453 request.arguments.unwrap_or_default(),
454 )
455 .expect("To parse StartDebuggingRequestArguments");
456 let worktree = local_store
457 .worktree_store
458 .update(cx, |this, _| this.worktrees().next())
459 .expect("worktree-less project");
460
461 let Some(config) = parent_session.read(cx).configuration() else {
462 unreachable!("there must be a config for local sessions");
463 };
464
465 let debug_config = DebugAdapterConfig {
466 label: config.label,
467 adapter: config.adapter,
468 request: DebugRequestDisposition::ReverseRequest(args),
469 initialize_args: config.initialize_args.clone(),
470 tcp_connection: config.tcp_connection.clone(),
471 locator: None,
472 args: Default::default(),
473 };
474
475 #[cfg(any(test, feature = "test-support"))]
476 let new_session_task = {
477 let caps = parent_session.read(cx).capabilities.clone();
478 self.new_fake_session(
479 debug_config,
480 &worktree,
481 Some(parent_session.clone()),
482 caps,
483 false,
484 cx,
485 )
486 .1
487 };
488 #[cfg(not(any(test, feature = "test-support")))]
489 let new_session_task = self
490 .new_session(debug_config, &worktree, Some(parent_session.clone()), cx)
491 .1;
492
493 let request_seq = request.seq;
494 cx.spawn(async move |_, cx| {
495 let (success, body) = match new_session_task.await {
496 Ok(_) => (true, None),
497 Err(error) => (
498 false,
499 Some(serde_json::to_value(ErrorResponse {
500 error: Some(dap::Message {
501 id: request_seq,
502 format: error.to_string(),
503 variables: None,
504 send_telemetry: None,
505 show_user: None,
506 url: None,
507 url_label: None,
508 }),
509 })?),
510 ),
511 };
512
513 parent_session
514 .update(cx, |session, cx| {
515 session.respond_to_client(
516 request_seq,
517 success,
518 StartDebugging::COMMAND.to_string(),
519 body,
520 cx,
521 )
522 })?
523 .await
524 })
525 }
526
527 fn handle_run_in_terminal_request(
528 &mut self,
529 session_id: SessionId,
530 request: dap::messages::Request,
531 cx: &mut Context<Self>,
532 ) -> Task<Result<()>> {
533 let Some(session) = self.session_by_id(session_id) else {
534 return Task::ready(Err(anyhow!("Session not found")));
535 };
536
537 let request_args = serde_json::from_value::<RunInTerminalRequestArguments>(
538 request.arguments.unwrap_or_default(),
539 )
540 .expect("To parse StartDebuggingRequestArguments");
541
542 let seq = request.seq;
543
544 let cwd = PathBuf::from(request_args.cwd);
545 match cwd.try_exists() {
546 Ok(true) => (),
547 Ok(false) | Err(_) => {
548 return session.update(cx, |session, cx| {
549 session.respond_to_client(
550 seq,
551 false,
552 RunInTerminal::COMMAND.to_string(),
553 serde_json::to_value(dap::ErrorResponse {
554 error: Some(dap::Message {
555 id: seq,
556 format: format!("Received invalid/unknown cwd: {cwd:?}"),
557 variables: None,
558 send_telemetry: None,
559 show_user: None,
560 url: None,
561 url_label: None,
562 }),
563 })
564 .ok(),
565 cx,
566 )
567 });
568 }
569 }
570
571 let mut args = request_args.args.clone();
572
573 // Handle special case for NodeJS debug adapter
574 // If only the Node binary path is provided, we set the command to None
575 // This prevents the NodeJS REPL from appearing, which is not the desired behavior
576 // The expected usage is for users to provide their own Node command, e.g., `node test.js`
577 // This allows the NodeJS debug client to attach correctly
578 let command = if args.len() > 1 {
579 Some(args.remove(0))
580 } else {
581 None
582 };
583
584 let mut envs: HashMap<String, String> = Default::default();
585 if let Some(Value::Object(env)) = request_args.env {
586 for (key, value) in env {
587 let value_str = match (key.as_str(), value) {
588 (_, Value::String(value)) => value,
589 _ => continue,
590 };
591
592 envs.insert(key, value_str);
593 }
594 }
595
596 let (tx, mut rx) = mpsc::channel::<Result<u32>>(1);
597
598 cx.emit(DapStoreEvent::RunInTerminal {
599 session_id,
600 title: request_args.title,
601 cwd,
602 command,
603 args,
604 envs,
605 sender: tx,
606 });
607 cx.notify();
608
609 let session = session.downgrade();
610 cx.spawn(async move |_, cx| {
611 let (success, body) = match rx.next().await {
612 Some(Ok(pid)) => (
613 true,
614 serde_json::to_value(dap::RunInTerminalResponse {
615 process_id: None,
616 shell_process_id: Some(pid as u64),
617 })
618 .ok(),
619 ),
620 Some(Err(error)) => (
621 false,
622 serde_json::to_value(dap::ErrorResponse {
623 error: Some(dap::Message {
624 id: seq,
625 format: error.to_string(),
626 variables: None,
627 send_telemetry: None,
628 show_user: None,
629 url: None,
630 url_label: None,
631 }),
632 })
633 .ok(),
634 ),
635 None => (
636 false,
637 serde_json::to_value(dap::ErrorResponse {
638 error: Some(dap::Message {
639 id: seq,
640 format: "failed to receive response from spawn terminal".to_string(),
641 variables: None,
642 send_telemetry: None,
643 show_user: None,
644 url: None,
645 url_label: None,
646 }),
647 })
648 .ok(),
649 ),
650 };
651
652 session
653 .update(cx, |session, cx| {
654 session.respond_to_client(
655 seq,
656 success,
657 RunInTerminal::COMMAND.to_string(),
658 body,
659 cx,
660 )
661 })?
662 .await
663 })
664 }
665
666 pub fn evaluate(
667 &self,
668 session_id: &SessionId,
669 stack_frame_id: u64,
670 expression: String,
671 context: EvaluateArgumentsContext,
672 source: Option<Source>,
673 cx: &mut Context<Self>,
674 ) -> Task<Result<EvaluateResponse>> {
675 let Some(client) = self
676 .session_by_id(session_id)
677 .and_then(|client| client.read(cx).adapter_client())
678 else {
679 return Task::ready(Err(anyhow!("Could not find client: {:?}", session_id)));
680 };
681
682 cx.background_executor().spawn(async move {
683 client
684 .request::<Evaluate>(EvaluateArguments {
685 expression: expression.clone(),
686 frame_id: Some(stack_frame_id),
687 context: Some(context),
688 format: None,
689 line: None,
690 column: None,
691 source,
692 })
693 .await
694 })
695 }
696
697 pub fn completions(
698 &self,
699 session_id: &SessionId,
700 stack_frame_id: u64,
701 text: String,
702 completion_column: u64,
703 cx: &mut Context<Self>,
704 ) -> Task<Result<Vec<CompletionItem>>> {
705 let Some(client) = self
706 .session_by_id(session_id)
707 .and_then(|client| client.read(cx).adapter_client())
708 else {
709 return Task::ready(Err(anyhow!("Could not find client: {:?}", session_id)));
710 };
711
712 cx.background_executor().spawn(async move {
713 Ok(client
714 .request::<Completions>(CompletionsArguments {
715 frame_id: Some(stack_frame_id),
716 line: None,
717 text,
718 column: completion_column,
719 })
720 .await?
721 .targets)
722 })
723 }
724
725 pub fn shutdown_sessions(&mut self, cx: &mut Context<Self>) -> Task<()> {
726 let mut tasks = vec![];
727 for session_id in self.sessions.keys().cloned().collect::<Vec<_>>() {
728 tasks.push(self.shutdown_session(session_id, cx));
729 }
730
731 cx.background_executor().spawn(async move {
732 futures::future::join_all(tasks).await;
733 })
734 }
735
736 pub fn shutdown_session(
737 &mut self,
738 session_id: SessionId,
739 cx: &mut Context<Self>,
740 ) -> Task<Result<()>> {
741 let Some(_) = self.as_local_mut() else {
742 return Task::ready(Err(anyhow!("Cannot shutdown session on remote side")));
743 };
744
745 let Some(session) = self.sessions.remove(&session_id) else {
746 return Task::ready(Err(anyhow!("Could not find session: {:?}", session_id)));
747 };
748
749 let shutdown_children = session
750 .read(cx)
751 .child_session_ids()
752 .iter()
753 .map(|session_id| self.shutdown_session(*session_id, cx))
754 .collect::<Vec<_>>();
755
756 let shutdown_parent_task = if let Some(parent_session) = session
757 .read(cx)
758 .parent_id()
759 .and_then(|session_id| self.session_by_id(session_id))
760 {
761 let shutdown_id = parent_session.update(cx, |parent_session, _| {
762 parent_session.remove_child_session_id(session_id);
763
764 if parent_session.child_session_ids().len() == 0 {
765 Some(parent_session.session_id())
766 } else {
767 None
768 }
769 });
770
771 shutdown_id.map(|session_id| self.shutdown_session(session_id, cx))
772 } else {
773 None
774 };
775
776 let shutdown_task = session.update(cx, |this, cx| this.shutdown(cx));
777
778 cx.background_spawn(async move {
779 if shutdown_children.len() > 0 {
780 let _ = join_all(shutdown_children).await;
781 }
782
783 shutdown_task.await;
784
785 if let Some(parent_task) = shutdown_parent_task {
786 parent_task.await?;
787 }
788
789 Ok(())
790 })
791 }
792
793 pub fn shared(
794 &mut self,
795 project_id: u64,
796 downstream_client: AnyProtoClient,
797 _: &mut Context<Self>,
798 ) {
799 self.downstream_client = Some((downstream_client.clone(), project_id));
800 }
801
802 pub fn unshared(&mut self, cx: &mut Context<Self>) {
803 self.downstream_client.take();
804
805 cx.notify();
806 }
807}
808
809fn create_new_session(
810 session_id: SessionId,
811 initialized_rx: oneshot::Receiver<()>,
812 start_client_task: Task<Result<Entity<Session>, anyhow::Error>>,
813 cx: &mut Context<DapStore>,
814) -> Task<Result<Entity<Session>>> {
815 let task = cx.spawn(async move |this, cx| {
816 let session = match start_client_task.await {
817 Ok(session) => session,
818 Err(error) => {
819 this.update(cx, |_, cx| {
820 cx.emit(DapStoreEvent::Notification(error.to_string()));
821 })
822 .log_err();
823
824 return Err(error);
825 }
826 };
827
828 // we have to insert the session early, so we can handle reverse requests
829 // that need the session to be available
830 this.update(cx, |store, cx| {
831 store.sessions.insert(session_id, session.clone());
832 cx.emit(DapStoreEvent::DebugClientStarted(session_id));
833 cx.notify();
834 })?;
835
836 match session
837 .update(cx, |session, cx| {
838 session.initialize_sequence(initialized_rx, cx)
839 })?
840 .await
841 {
842 Ok(_) => {}
843 Err(error) => {
844 this.update(cx, |this, cx| {
845 cx.emit(DapStoreEvent::Notification(error.to_string()));
846
847 this.shutdown_session(session_id, cx)
848 })?
849 .await
850 .log_err();
851
852 return Err(error);
853 }
854 }
855
856 Ok(session)
857 });
858 task
859}
860
861#[derive(Clone)]
862pub struct DapAdapterDelegate {
863 fs: Arc<dyn Fs>,
864 worktree_id: WorktreeId,
865 node_runtime: NodeRuntime,
866 http_client: Arc<dyn HttpClient>,
867 language_registry: Arc<LanguageRegistry>,
868 toolchain_store: Arc<dyn LanguageToolchainStore>,
869 updated_adapters: Arc<Mutex<HashSet<DebugAdapterName>>>,
870 load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
871}
872
873impl DapAdapterDelegate {
874 pub fn new(
875 fs: Arc<dyn Fs>,
876 worktree_id: WorktreeId,
877 node_runtime: NodeRuntime,
878 http_client: Arc<dyn HttpClient>,
879 language_registry: Arc<LanguageRegistry>,
880 toolchain_store: Arc<dyn LanguageToolchainStore>,
881 load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
882 ) -> Self {
883 Self {
884 fs,
885 worktree_id,
886 http_client,
887 node_runtime,
888 toolchain_store,
889 language_registry,
890 load_shell_env_task,
891 updated_adapters: Default::default(),
892 }
893 }
894}
895
896#[async_trait(?Send)]
897impl dap::adapters::DapDelegate for DapAdapterDelegate {
898 fn worktree_id(&self) -> WorktreeId {
899 self.worktree_id
900 }
901
902 fn http_client(&self) -> Arc<dyn HttpClient> {
903 self.http_client.clone()
904 }
905
906 fn node_runtime(&self) -> NodeRuntime {
907 self.node_runtime.clone()
908 }
909
910 fn fs(&self) -> Arc<dyn Fs> {
911 self.fs.clone()
912 }
913
914 fn updated_adapters(&self) -> Arc<Mutex<HashSet<DebugAdapterName>>> {
915 self.updated_adapters.clone()
916 }
917
918 fn update_status(&self, dap_name: DebugAdapterName, status: dap::adapters::DapStatus) {
919 let name = SharedString::from(dap_name.to_string());
920 let status = match status {
921 DapStatus::None => BinaryStatus::None,
922 DapStatus::Downloading => BinaryStatus::Downloading,
923 DapStatus::Failed { error } => BinaryStatus::Failed { error },
924 DapStatus::CheckingForUpdate => BinaryStatus::CheckingForUpdate,
925 };
926
927 self.language_registry
928 .update_dap_status(LanguageServerName(name), status);
929 }
930
931 fn which(&self, command: &OsStr) -> Option<PathBuf> {
932 which::which(command).ok()
933 }
934
935 async fn shell_env(&self) -> HashMap<String, String> {
936 let task = self.load_shell_env_task.clone();
937 task.await.unwrap_or_default()
938 }
939
940 fn toolchain_store(&self) -> Arc<dyn LanguageToolchainStore> {
941 self.toolchain_store.clone()
942 }
943}