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