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 debugger::session::SessionQuirks,
10 project_settings::{DapBinary, ProjectSettings},
11 worktree_store::WorktreeStore,
12};
13use anyhow::{Context as _, Result, anyhow};
14use async_trait::async_trait;
15use collections::HashMap;
16use dap::{
17 Capabilities, DapRegistry, DebugRequest, EvaluateArgumentsContext, StackFrameId,
18 adapters::{
19 DapDelegate, DebugAdapterBinary, DebugAdapterName, DebugTaskDefinition, TcpArguments,
20 },
21 client::SessionId,
22 inline_value::VariableLookupKind,
23 messages::Message,
24};
25use fs::{Fs, RemoveOptions};
26use futures::{
27 StreamExt, TryStreamExt as _,
28 channel::mpsc::{self, UnboundedSender},
29 future::{Shared, join_all},
30};
31use gpui::{App, AppContext, AsyncApp, Context, Entity, EventEmitter, SharedString, Task};
32use http_client::HttpClient;
33use language::{Buffer, LanguageToolchainStore};
34use node_runtime::NodeRuntime;
35use settings::InlayHintKind;
36
37use remote::RemoteClient;
38use rpc::{
39 AnyProtoClient, TypedEnvelope,
40 proto::{self},
41};
42use serde::{Deserialize, Serialize};
43use settings::{Settings, SettingsLocation, 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, Shell, SpawnInTerminal, TaskContext, TaskTemplate};
53use util::{ResultExt as _, rel_path::RelPath};
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 Remote(RemoteDapStore),
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 is_headless: bool,
82}
83
84pub struct RemoteDapStore {
85 remote_client: Entity<RemoteClient>,
86 upstream_client: AnyProtoClient,
87 upstream_project_id: u64,
88 node_runtime: NodeRuntime,
89 http_client: Arc<dyn HttpClient>,
90}
91
92pub struct DapStore {
93 mode: DapStoreMode,
94 downstream_client: Option<(AnyProtoClient, u64)>,
95 breakpoint_store: Entity<BreakpointStore>,
96 worktree_store: Entity<WorktreeStore>,
97 sessions: BTreeMap<SessionId, Entity<Session>>,
98 next_session_id: u32,
99 adapter_options: BTreeMap<DebugAdapterName, Arc<PersistedAdapterOptions>>,
100}
101
102impl EventEmitter<DapStoreEvent> for DapStore {}
103
104#[derive(Clone, Serialize, Deserialize)]
105pub struct PersistedExceptionBreakpoint {
106 pub enabled: bool,
107}
108
109/// Represents best-effort serialization of adapter state during last session (e.g. watches)
110#[derive(Clone, Default, Serialize, Deserialize)]
111pub struct PersistedAdapterOptions {
112 /// Which exception breakpoints were enabled during the last session with this adapter?
113 pub exception_breakpoints: BTreeMap<String, PersistedExceptionBreakpoint>,
114}
115
116impl DapStore {
117 pub fn init(client: &AnyProtoClient, cx: &mut App) {
118 static ADD_LOCATORS: Once = Once::new();
119 ADD_LOCATORS.call_once(|| {
120 let registry = DapRegistry::global(cx);
121 registry.add_locator(Arc::new(locators::cargo::CargoLocator {}));
122 registry.add_locator(Arc::new(locators::go::GoLocator {}));
123 registry.add_locator(Arc::new(locators::node::NodeLocator));
124 registry.add_locator(Arc::new(locators::python::PythonLocator));
125 });
126 client.add_entity_request_handler(Self::handle_run_debug_locator);
127 client.add_entity_request_handler(Self::handle_get_debug_adapter_binary);
128 client.add_entity_message_handler(Self::handle_log_to_debug_console);
129 }
130
131 #[expect(clippy::too_many_arguments)]
132 pub fn new_local(
133 http_client: Arc<dyn HttpClient>,
134 node_runtime: NodeRuntime,
135 fs: Arc<dyn Fs>,
136 environment: Entity<ProjectEnvironment>,
137 toolchain_store: Arc<dyn LanguageToolchainStore>,
138 worktree_store: Entity<WorktreeStore>,
139 breakpoint_store: Entity<BreakpointStore>,
140 is_headless: bool,
141 cx: &mut Context<Self>,
142 ) -> Self {
143 let mode = DapStoreMode::Local(LocalDapStore {
144 fs: fs.clone(),
145 environment,
146 http_client,
147 node_runtime,
148 toolchain_store,
149 is_headless,
150 });
151
152 Self::new(mode, breakpoint_store, worktree_store, fs, cx)
153 }
154
155 pub fn new_remote(
156 project_id: u64,
157 remote_client: Entity<RemoteClient>,
158 breakpoint_store: Entity<BreakpointStore>,
159 worktree_store: Entity<WorktreeStore>,
160 node_runtime: NodeRuntime,
161 http_client: Arc<dyn HttpClient>,
162 fs: Arc<dyn Fs>,
163 cx: &mut Context<Self>,
164 ) -> Self {
165 let mode = DapStoreMode::Remote(RemoteDapStore {
166 upstream_client: remote_client.read(cx).proto_client(),
167 remote_client,
168 upstream_project_id: project_id,
169 node_runtime,
170 http_client,
171 });
172
173 Self::new(mode, breakpoint_store, worktree_store, fs, cx)
174 }
175
176 pub fn new_collab(
177 _project_id: u64,
178 _upstream_client: AnyProtoClient,
179 breakpoint_store: Entity<BreakpointStore>,
180 worktree_store: Entity<WorktreeStore>,
181 fs: Arc<dyn Fs>,
182 cx: &mut Context<Self>,
183 ) -> Self {
184 Self::new(
185 DapStoreMode::Collab,
186 breakpoint_store,
187 worktree_store,
188 fs,
189 cx,
190 )
191 }
192
193 fn new(
194 mode: DapStoreMode,
195 breakpoint_store: Entity<BreakpointStore>,
196 worktree_store: Entity<WorktreeStore>,
197 fs: Arc<dyn Fs>,
198 cx: &mut Context<Self>,
199 ) -> Self {
200 cx.background_spawn(async move {
201 let dir = paths::debug_adapters_dir().join("js-debug-companion");
202
203 let mut children = fs.read_dir(&dir).await?.try_collect::<Vec<_>>().await?;
204 children.sort_by_key(|child| semver::Version::parse(child.file_name()?.to_str()?).ok());
205
206 if let Some(child) = children.last()
207 && let Some(name) = child.file_name()
208 && let Some(name) = name.to_str()
209 && semver::Version::parse(name).is_ok()
210 {
211 children.pop();
212 }
213
214 for child in children {
215 fs.remove_dir(
216 &child,
217 RemoveOptions {
218 recursive: true,
219 ignore_if_not_exists: true,
220 },
221 )
222 .await
223 .ok();
224 }
225
226 anyhow::Ok(())
227 })
228 .detach();
229
230 Self {
231 mode,
232 next_session_id: 0,
233 downstream_client: None,
234 breakpoint_store,
235 worktree_store,
236 sessions: Default::default(),
237 adapter_options: Default::default(),
238 }
239 }
240
241 pub fn get_debug_adapter_binary(
242 &mut self,
243 definition: DebugTaskDefinition,
244 session_id: SessionId,
245 worktree: &Entity<Worktree>,
246 console: UnboundedSender<String>,
247 cx: &mut Context<Self>,
248 ) -> Task<Result<DebugAdapterBinary>> {
249 match &self.mode {
250 DapStoreMode::Local(_) => {
251 let Some(adapter) = DapRegistry::global(cx).adapter(&definition.adapter) else {
252 return Task::ready(Err(anyhow!("Failed to find a debug adapter")));
253 };
254
255 let settings_location = SettingsLocation {
256 worktree_id: worktree.read(cx).id(),
257 path: RelPath::empty(),
258 };
259 let dap_settings = ProjectSettings::get(Some(settings_location), cx)
260 .dap
261 .get(&adapter.name());
262 let user_installed_path = dap_settings.and_then(|s| match &s.binary {
263 DapBinary::Default => None,
264 DapBinary::Custom(binary) => Some(PathBuf::from(binary)),
265 });
266 let user_args = dap_settings.map(|s| s.args.clone());
267
268 let delegate = self.delegate(worktree, console, cx);
269 let cwd: Arc<Path> = worktree.read(cx).abs_path().as_ref().into();
270
271 cx.spawn(async move |this, cx| {
272 let mut binary = adapter
273 .get_binary(&delegate, &definition, user_installed_path, user_args, cx)
274 .await?;
275
276 let env = this
277 .update(cx, |this, cx| {
278 this.as_local()
279 .unwrap()
280 .environment
281 .update(cx, |environment, cx| {
282 environment.get_local_directory_environment(
283 &Shell::System,
284 cwd,
285 cx,
286 )
287 })
288 })?
289 .await;
290
291 if let Some(mut env) = env {
292 env.extend(std::mem::take(&mut binary.envs));
293 binary.envs = env;
294 }
295
296 Ok(binary)
297 })
298 }
299 DapStoreMode::Remote(remote) => {
300 let request = remote
301 .upstream_client
302 .request(proto::GetDebugAdapterBinary {
303 session_id: session_id.to_proto(),
304 project_id: remote.upstream_project_id,
305 worktree_id: worktree.read(cx).id().to_proto(),
306 definition: Some(definition.to_proto()),
307 });
308 let remote = remote.remote_client.clone();
309
310 cx.spawn(async move |_, cx| {
311 let response = request.await?;
312 let binary = DebugAdapterBinary::from_proto(response)?;
313
314 let port_forwarding;
315 let connection;
316 if let Some(c) = binary.connection {
317 let host = Ipv4Addr::LOCALHOST;
318 let port;
319 if remote.read_with(cx, |remote, _cx| remote.shares_network_interface())? {
320 port = c.port;
321 port_forwarding = None;
322 } else {
323 port = dap::transport::TcpTransport::unused_port(host).await?;
324 port_forwarding = Some((port, c.host.to_string(), c.port));
325 }
326 connection = Some(TcpArguments {
327 port,
328 host,
329 timeout: c.timeout,
330 })
331 } else {
332 port_forwarding = None;
333 connection = None;
334 }
335
336 let command = remote.read_with(cx, |remote, _cx| {
337 remote.build_command(
338 binary.command,
339 &binary.arguments,
340 &binary.envs,
341 binary.cwd.map(|path| path.display().to_string()),
342 port_forwarding,
343 )
344 })??;
345
346 Ok(DebugAdapterBinary {
347 command: Some(command.program),
348 arguments: command.args,
349 envs: command.env,
350 cwd: None,
351 connection,
352 request_args: binary.request_args,
353 })
354 })
355 }
356 DapStoreMode::Collab => {
357 Task::ready(Err(anyhow!("Debugging is not yet supported via collab")))
358 }
359 }
360 }
361
362 pub fn debug_scenario_for_build_task(
363 &self,
364 build: TaskTemplate,
365 adapter: DebugAdapterName,
366 label: SharedString,
367 cx: &mut App,
368 ) -> Task<Option<DebugScenario>> {
369 let locators = DapRegistry::global(cx).locators();
370
371 cx.background_spawn(async move {
372 for locator in locators.values() {
373 if let Some(scenario) = locator.create_scenario(&build, &label, &adapter).await {
374 return Some(scenario);
375 }
376 }
377 None
378 })
379 }
380
381 pub fn run_debug_locator(
382 &mut self,
383 locator_name: &str,
384 build_command: SpawnInTerminal,
385 cx: &mut Context<Self>,
386 ) -> Task<Result<DebugRequest>> {
387 match &self.mode {
388 DapStoreMode::Local(_) => {
389 // Pre-resolve args with existing environment.
390 let locators = DapRegistry::global(cx).locators();
391 let locator = locators.get(locator_name);
392
393 if let Some(locator) = locator.cloned() {
394 cx.background_spawn(async move {
395 let result = locator
396 .run(build_command.clone())
397 .await
398 .log_with_level(log::Level::Error);
399 if let Some(result) = result {
400 return Ok(result);
401 }
402
403 anyhow::bail!(
404 "None of the locators for task `{}` completed successfully",
405 build_command.label
406 )
407 })
408 } else {
409 Task::ready(Err(anyhow!(
410 "Couldn't find any locator for task `{}`. Specify the `attach` or `launch` arguments in your debug scenario definition",
411 build_command.label
412 )))
413 }
414 }
415 DapStoreMode::Remote(remote) => {
416 let request = remote.upstream_client.request(proto::RunDebugLocators {
417 project_id: remote.upstream_project_id,
418 build_command: Some(build_command.to_proto()),
419 locator: locator_name.to_owned(),
420 });
421 cx.background_spawn(async move {
422 let response = request.await?;
423 DebugRequest::from_proto(response)
424 })
425 }
426 DapStoreMode::Collab => {
427 Task::ready(Err(anyhow!("Debugging is not yet supported via collab")))
428 }
429 }
430 }
431
432 fn as_local(&self) -> Option<&LocalDapStore> {
433 match &self.mode {
434 DapStoreMode::Local(local_dap_store) => Some(local_dap_store),
435 _ => None,
436 }
437 }
438
439 pub fn new_session(
440 &mut self,
441 label: Option<SharedString>,
442 adapter: DebugAdapterName,
443 task_context: TaskContext,
444 parent_session: Option<Entity<Session>>,
445 quirks: SessionQuirks,
446 cx: &mut Context<Self>,
447 ) -> Entity<Session> {
448 let session_id = SessionId(util::post_inc(&mut self.next_session_id));
449
450 if let Some(session) = &parent_session {
451 session.update(cx, |session, _| {
452 session.add_child_session_id(session_id);
453 });
454 }
455
456 let (remote_client, node_runtime, http_client) = match &self.mode {
457 DapStoreMode::Local(_) => (None, None, None),
458 DapStoreMode::Remote(remote_dap_store) => (
459 Some(remote_dap_store.remote_client.clone()),
460 Some(remote_dap_store.node_runtime.clone()),
461 Some(remote_dap_store.http_client.clone()),
462 ),
463 DapStoreMode::Collab => (None, None, None),
464 };
465 let session = Session::new(
466 self.breakpoint_store.clone(),
467 session_id,
468 parent_session,
469 label,
470 adapter,
471 task_context,
472 quirks,
473 remote_client,
474 node_runtime,
475 http_client,
476 cx,
477 );
478
479 self.sessions.insert(session_id, session.clone());
480 cx.notify();
481
482 cx.subscribe(&session, {
483 move |this: &mut DapStore, _, event: &SessionStateEvent, cx| match event {
484 SessionStateEvent::Shutdown => {
485 this.shutdown_session(session_id, cx).detach_and_log_err(cx);
486 }
487 SessionStateEvent::Restart | SessionStateEvent::SpawnChildSession { .. } => {}
488 SessionStateEvent::Running => {
489 cx.emit(DapStoreEvent::DebugClientStarted(session_id));
490 }
491 }
492 })
493 .detach();
494
495 session
496 }
497
498 pub fn boot_session(
499 &self,
500 session: Entity<Session>,
501 definition: DebugTaskDefinition,
502 worktree: Entity<Worktree>,
503 cx: &mut Context<Self>,
504 ) -> Task<Result<()>> {
505 let dap_store = cx.weak_entity();
506 let console = session.update(cx, |session, cx| session.console_output(cx));
507 let session_id = session.read(cx).session_id();
508
509 cx.spawn({
510 let session = session.clone();
511 async move |this, cx| {
512 let binary = this
513 .update(cx, |this, cx| {
514 this.get_debug_adapter_binary(
515 definition.clone(),
516 session_id,
517 &worktree,
518 console,
519 cx,
520 )
521 })?
522 .await?;
523 session
524 .update(cx, |session, cx| {
525 session.boot(binary, worktree, dap_store, cx)
526 })?
527 .await
528 }
529 })
530 }
531
532 pub fn session_by_id(
533 &self,
534 session_id: impl Borrow<SessionId>,
535 ) -> Option<Entity<session::Session>> {
536 let session_id = session_id.borrow();
537
538 self.sessions.get(session_id).cloned()
539 }
540 pub fn sessions(&self) -> impl Iterator<Item = &Entity<Session>> {
541 self.sessions.values()
542 }
543
544 pub fn capabilities_by_id(
545 &self,
546 session_id: impl Borrow<SessionId>,
547 cx: &App,
548 ) -> Option<Capabilities> {
549 let session_id = session_id.borrow();
550 self.sessions
551 .get(session_id)
552 .map(|client| client.read(cx).capabilities.clone())
553 }
554
555 pub fn breakpoint_store(&self) -> &Entity<BreakpointStore> {
556 &self.breakpoint_store
557 }
558
559 pub fn worktree_store(&self) -> &Entity<WorktreeStore> {
560 &self.worktree_store
561 }
562
563 #[allow(dead_code)]
564 async fn handle_ignore_breakpoint_state(
565 this: Entity<Self>,
566 envelope: TypedEnvelope<proto::IgnoreBreakpointState>,
567 mut cx: AsyncApp,
568 ) -> Result<()> {
569 let session_id = SessionId::from_proto(envelope.payload.session_id);
570
571 this.update(&mut cx, |this, cx| {
572 if let Some(session) = this.session_by_id(&session_id) {
573 session.update(cx, |session, cx| {
574 session.set_ignore_breakpoints(envelope.payload.ignore, cx)
575 })
576 } else {
577 Task::ready(HashMap::default())
578 }
579 })?
580 .await;
581
582 Ok(())
583 }
584
585 fn delegate(
586 &self,
587 worktree: &Entity<Worktree>,
588 console: UnboundedSender<String>,
589 cx: &mut App,
590 ) -> Arc<dyn DapDelegate> {
591 let Some(local_store) = self.as_local() else {
592 unimplemented!("Starting session on remote side");
593 };
594
595 Arc::new(DapAdapterDelegate::new(
596 local_store.fs.clone(),
597 worktree.read(cx).snapshot(),
598 console,
599 local_store.node_runtime.clone(),
600 local_store.http_client.clone(),
601 local_store.toolchain_store.clone(),
602 local_store.environment.update(cx, |env, cx| {
603 env.get_worktree_environment(worktree.clone(), cx)
604 }),
605 local_store.is_headless,
606 ))
607 }
608
609 pub fn resolve_inline_value_locations(
610 &self,
611 session: Entity<Session>,
612 stack_frame_id: StackFrameId,
613 buffer_handle: Entity<Buffer>,
614 inline_value_locations: Vec<dap::inline_value::InlineValueLocation>,
615 cx: &mut Context<Self>,
616 ) -> Task<Result<Vec<InlayHint>>> {
617 let snapshot = buffer_handle.read(cx).snapshot();
618 let local_variables =
619 session
620 .read(cx)
621 .variables_by_stack_frame_id(stack_frame_id, false, true);
622 let global_variables =
623 session
624 .read(cx)
625 .variables_by_stack_frame_id(stack_frame_id, true, false);
626
627 fn format_value(mut value: String) -> String {
628 const LIMIT: usize = 100;
629
630 if let Some(index) = value.find("\n") {
631 value.truncate(index);
632 value.push_str("…");
633 }
634
635 if value.len() > LIMIT {
636 let mut index = LIMIT;
637 // If index isn't a char boundary truncate will cause a panic
638 while !value.is_char_boundary(index) {
639 index -= 1;
640 }
641 value.truncate(index);
642 value.push_str("…");
643 }
644
645 format!(": {}", value)
646 }
647
648 cx.spawn(async move |_, cx| {
649 let mut inlay_hints = Vec::with_capacity(inline_value_locations.len());
650 for inline_value_location in inline_value_locations.iter() {
651 let point = snapshot.point_to_point_utf16(language::Point::new(
652 inline_value_location.row as u32,
653 inline_value_location.column as u32,
654 ));
655 let position = snapshot.anchor_after(point);
656
657 match inline_value_location.lookup {
658 VariableLookupKind::Variable => {
659 let variable_search =
660 if inline_value_location.scope
661 == dap::inline_value::VariableScope::Local
662 {
663 local_variables.iter().chain(global_variables.iter()).find(
664 |variable| variable.name == inline_value_location.variable_name,
665 )
666 } else {
667 global_variables.iter().find(|variable| {
668 variable.name == inline_value_location.variable_name
669 })
670 };
671
672 let Some(variable) = variable_search else {
673 continue;
674 };
675
676 inlay_hints.push(InlayHint {
677 position,
678 label: InlayHintLabel::String(format_value(variable.value.clone())),
679 kind: Some(InlayHintKind::Type),
680 padding_left: false,
681 padding_right: false,
682 tooltip: None,
683 resolve_state: ResolveState::Resolved,
684 });
685 }
686 VariableLookupKind::Expression => {
687 let Ok(eval_task) = session.read_with(cx, |session, _| {
688 session.mode.request_dap(EvaluateCommand {
689 expression: inline_value_location.variable_name.clone(),
690 frame_id: Some(stack_frame_id),
691 source: None,
692 context: Some(EvaluateArgumentsContext::Variables),
693 })
694 }) else {
695 continue;
696 };
697
698 if let Some(response) = eval_task.await.log_err() {
699 inlay_hints.push(InlayHint {
700 position,
701 label: InlayHintLabel::String(format_value(response.result)),
702 kind: Some(InlayHintKind::Type),
703 padding_left: false,
704 padding_right: false,
705 tooltip: None,
706 resolve_state: ResolveState::Resolved,
707 });
708 };
709 }
710 };
711 }
712
713 Ok(inlay_hints)
714 })
715 }
716
717 pub fn shutdown_sessions(&mut self, cx: &mut Context<Self>) -> Task<()> {
718 let mut tasks = vec![];
719 for session_id in self.sessions.keys().cloned().collect::<Vec<_>>() {
720 tasks.push(self.shutdown_session(session_id, cx));
721 }
722
723 cx.background_executor().spawn(async move {
724 futures::future::join_all(tasks).await;
725 })
726 }
727
728 pub fn shutdown_session(
729 &mut self,
730 session_id: SessionId,
731 cx: &mut Context<Self>,
732 ) -> Task<Result<()>> {
733 let Some(session) = self.sessions.remove(&session_id) else {
734 return Task::ready(Err(anyhow!("Could not find session: {:?}", session_id)));
735 };
736
737 let shutdown_children = session
738 .read(cx)
739 .child_session_ids()
740 .iter()
741 .map(|session_id| self.shutdown_session(*session_id, cx))
742 .collect::<Vec<_>>();
743
744 let shutdown_parent_task = if let Some(parent_session) = session
745 .read(cx)
746 .parent_id(cx)
747 .and_then(|session_id| self.session_by_id(session_id))
748 {
749 let shutdown_id = parent_session.update(cx, |parent_session, _| {
750 parent_session.remove_child_session_id(session_id);
751
752 if parent_session.child_session_ids().is_empty() {
753 Some(parent_session.session_id())
754 } else {
755 None
756 }
757 });
758
759 shutdown_id.map(|session_id| self.shutdown_session(session_id, cx))
760 } else {
761 None
762 };
763
764 let shutdown_task = session.update(cx, |this, cx| this.shutdown(cx));
765
766 cx.emit(DapStoreEvent::DebugClientShutdown(session_id));
767
768 cx.background_spawn(async move {
769 if !shutdown_children.is_empty() {
770 let _ = join_all(shutdown_children).await;
771 }
772
773 shutdown_task.await;
774
775 if let Some(parent_task) = shutdown_parent_task {
776 parent_task.await?;
777 }
778
779 Ok(())
780 })
781 }
782
783 pub fn shared(
784 &mut self,
785 project_id: u64,
786 downstream_client: AnyProtoClient,
787 _: &mut Context<Self>,
788 ) {
789 self.downstream_client = Some((downstream_client, project_id));
790 }
791
792 pub fn unshared(&mut self, cx: &mut Context<Self>) {
793 self.downstream_client.take();
794
795 cx.notify();
796 }
797
798 async fn handle_run_debug_locator(
799 this: Entity<Self>,
800 envelope: TypedEnvelope<proto::RunDebugLocators>,
801 mut cx: AsyncApp,
802 ) -> Result<proto::DebugRequest> {
803 let task = envelope
804 .payload
805 .build_command
806 .context("missing definition")?;
807 let build_task = SpawnInTerminal::from_proto(task);
808 let locator = envelope.payload.locator;
809 let request = this
810 .update(&mut cx, |this, cx| {
811 this.run_debug_locator(&locator, build_task, cx)
812 })?
813 .await?;
814
815 Ok(request.to_proto())
816 }
817
818 async fn handle_get_debug_adapter_binary(
819 this: Entity<Self>,
820 envelope: TypedEnvelope<proto::GetDebugAdapterBinary>,
821 mut cx: AsyncApp,
822 ) -> Result<proto::DebugAdapterBinary> {
823 let definition = DebugTaskDefinition::from_proto(
824 envelope.payload.definition.context("missing definition")?,
825 )?;
826 let (tx, mut rx) = mpsc::unbounded();
827 let session_id = envelope.payload.session_id;
828 cx.spawn({
829 let this = this.clone();
830 async move |cx| {
831 while let Some(message) = rx.next().await {
832 this.read_with(cx, |this, _| {
833 if let Some((downstream, project_id)) = this.downstream_client.clone() {
834 downstream
835 .send(proto::LogToDebugConsole {
836 project_id,
837 session_id,
838 message,
839 })
840 .ok();
841 }
842 })
843 .ok();
844 }
845 }
846 })
847 .detach();
848
849 let worktree = this
850 .update(&mut cx, |this, cx| {
851 this.worktree_store
852 .read(cx)
853 .worktree_for_id(WorktreeId::from_proto(envelope.payload.worktree_id), cx)
854 })?
855 .context("Failed to find worktree with a given ID")?;
856 let binary = this
857 .update(&mut cx, |this, cx| {
858 this.get_debug_adapter_binary(
859 definition,
860 SessionId::from_proto(session_id),
861 &worktree,
862 tx,
863 cx,
864 )
865 })?
866 .await?;
867 Ok(binary.to_proto())
868 }
869
870 async fn handle_log_to_debug_console(
871 this: Entity<Self>,
872 envelope: TypedEnvelope<proto::LogToDebugConsole>,
873 mut cx: AsyncApp,
874 ) -> Result<()> {
875 let session_id = SessionId::from_proto(envelope.payload.session_id);
876 this.update(&mut cx, |this, cx| {
877 let Some(session) = this.sessions.get(&session_id) else {
878 return;
879 };
880 session.update(cx, |session, cx| {
881 session
882 .console_output(cx)
883 .unbounded_send(envelope.payload.message)
884 .ok();
885 })
886 })
887 }
888
889 pub fn sync_adapter_options(
890 &mut self,
891 session: &Entity<Session>,
892 cx: &App,
893 ) -> Arc<PersistedAdapterOptions> {
894 let session = session.read(cx);
895 let adapter = session.adapter();
896 let exceptions = session.exception_breakpoints();
897 let exception_breakpoints = exceptions
898 .map(|(exception, enabled)| {
899 (
900 exception.filter.clone(),
901 PersistedExceptionBreakpoint { enabled: *enabled },
902 )
903 })
904 .collect();
905 let options = Arc::new(PersistedAdapterOptions {
906 exception_breakpoints,
907 });
908 self.adapter_options.insert(adapter, options.clone());
909 options
910 }
911
912 pub fn set_adapter_options(
913 &mut self,
914 adapter: DebugAdapterName,
915 options: PersistedAdapterOptions,
916 ) {
917 self.adapter_options.insert(adapter, Arc::new(options));
918 }
919
920 pub fn adapter_options(&self, name: &str) -> Option<Arc<PersistedAdapterOptions>> {
921 self.adapter_options.get(name).cloned()
922 }
923
924 pub fn all_adapter_options(&self) -> &BTreeMap<DebugAdapterName, Arc<PersistedAdapterOptions>> {
925 &self.adapter_options
926 }
927}
928
929#[derive(Clone)]
930pub struct DapAdapterDelegate {
931 fs: Arc<dyn Fs>,
932 console: mpsc::UnboundedSender<String>,
933 worktree: worktree::Snapshot,
934 node_runtime: NodeRuntime,
935 http_client: Arc<dyn HttpClient>,
936 toolchain_store: Arc<dyn LanguageToolchainStore>,
937 load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
938 is_headless: bool,
939}
940
941impl DapAdapterDelegate {
942 pub fn new(
943 fs: Arc<dyn Fs>,
944 worktree: worktree::Snapshot,
945 status: mpsc::UnboundedSender<String>,
946 node_runtime: NodeRuntime,
947 http_client: Arc<dyn HttpClient>,
948 toolchain_store: Arc<dyn LanguageToolchainStore>,
949 load_shell_env_task: Shared<Task<Option<HashMap<String, String>>>>,
950 is_headless: bool,
951 ) -> Self {
952 Self {
953 fs,
954 console: status,
955 worktree,
956 http_client,
957 node_runtime,
958 toolchain_store,
959 load_shell_env_task,
960 is_headless,
961 }
962 }
963}
964
965#[async_trait]
966impl dap::adapters::DapDelegate for DapAdapterDelegate {
967 fn worktree_id(&self) -> WorktreeId {
968 self.worktree.id()
969 }
970
971 fn worktree_root_path(&self) -> &Path {
972 self.worktree.abs_path()
973 }
974 fn http_client(&self) -> Arc<dyn HttpClient> {
975 self.http_client.clone()
976 }
977
978 fn node_runtime(&self) -> NodeRuntime {
979 self.node_runtime.clone()
980 }
981
982 fn fs(&self) -> Arc<dyn Fs> {
983 self.fs.clone()
984 }
985
986 fn output_to_console(&self, msg: String) {
987 self.console.unbounded_send(msg).ok();
988 }
989
990 #[cfg(not(target_os = "windows"))]
991 async fn which(&self, command: &OsStr) -> Option<PathBuf> {
992 let worktree_abs_path = self.worktree.abs_path();
993 let shell_path = self.shell_env().await.get("PATH").cloned();
994 which::which_in(command, shell_path.as_ref(), worktree_abs_path).ok()
995 }
996
997 #[cfg(target_os = "windows")]
998 async fn which(&self, command: &OsStr) -> Option<PathBuf> {
999 // On Windows, `PATH` is handled differently from Unix. Windows generally expects users to modify the `PATH` themselves,
1000 // and every program loads it directly from the system at startup.
1001 // There's also no concept of a default shell on Windows, and you can't really retrieve one, so trying to get shell environment variables
1002 // from a specific directory doesn’t make sense on Windows.
1003 which::which(command).ok()
1004 }
1005
1006 async fn shell_env(&self) -> HashMap<String, String> {
1007 let task = self.load_shell_env_task.clone();
1008 task.await.unwrap_or_default()
1009 }
1010
1011 fn toolchain_store(&self) -> Arc<dyn LanguageToolchainStore> {
1012 self.toolchain_store.clone()
1013 }
1014
1015 async fn read_text_file(&self, path: &RelPath) -> Result<String> {
1016 let entry = self
1017 .worktree
1018 .entry_for_path(path)
1019 .with_context(|| format!("no worktree entry for path {path:?}"))?;
1020 let abs_path = self.worktree.absolutize(&entry.path);
1021
1022 self.fs.load(&abs_path).await
1023 }
1024
1025 fn is_headless(&self) -> bool {
1026 self.is_headless
1027 }
1028}