session.rs

   1use crate::debugger::breakpoint_store::BreakpointSessionState;
   2
   3use super::breakpoint_store::{
   4    BreakpointStore, BreakpointStoreEvent, BreakpointUpdatedReason, SourceBreakpoint,
   5};
   6use super::dap_command::{
   7    self, Attach, ConfigurationDone, ContinueCommand, DapCommand, DisconnectCommand,
   8    EvaluateCommand, Initialize, Launch, LoadedSourcesCommand, LocalDapCommand, LocationsCommand,
   9    ModulesCommand, NextCommand, PauseCommand, RestartCommand, RestartStackFrameCommand,
  10    ScopesCommand, SetExceptionBreakpoints, SetVariableValueCommand, StackTraceCommand,
  11    StepBackCommand, StepCommand, StepInCommand, StepOutCommand, TerminateCommand,
  12    TerminateThreadsCommand, ThreadsCommand, VariablesCommand,
  13};
  14use super::dap_store::DapStore;
  15use anyhow::{Context as _, Result, anyhow};
  16use collections::{HashMap, HashSet, IndexMap};
  17use dap::adapters::{DebugAdapterBinary, DebugAdapterName};
  18use dap::messages::Response;
  19use dap::requests::{Request, RunInTerminal, StartDebugging};
  20use dap::{
  21    Capabilities, ContinueArguments, EvaluateArgumentsContext, Module, Source, StackFrameId,
  22    SteppingGranularity, StoppedEvent, VariableReference,
  23    client::{DebugAdapterClient, SessionId},
  24    messages::{Events, Message},
  25};
  26use dap::{
  27    ExceptionBreakpointsFilter, ExceptionFilterOptions, OutputEvent, OutputEventCategory,
  28    RunInTerminalRequestArguments, StackFramePresentationHint, StartDebuggingRequestArguments,
  29    StartDebuggingRequestArgumentsRequest, VariablePresentationHint,
  30};
  31use futures::SinkExt;
  32use futures::channel::mpsc::UnboundedSender;
  33use futures::channel::{mpsc, oneshot};
  34use futures::{FutureExt, future::Shared};
  35use gpui::{
  36    App, AppContext, AsyncApp, BackgroundExecutor, Context, Entity, EventEmitter, SharedString,
  37    Task, WeakEntity,
  38};
  39
  40use rpc::ErrorExt;
  41use serde_json::Value;
  42use smol::stream::StreamExt;
  43use std::any::TypeId;
  44use std::collections::BTreeMap;
  45use std::u64;
  46use std::{
  47    any::Any,
  48    collections::hash_map::Entry,
  49    hash::{Hash, Hasher},
  50    path::Path,
  51    sync::Arc,
  52};
  53use task::TaskContext;
  54use text::{PointUtf16, ToPointUtf16};
  55use util::ResultExt;
  56use worktree::Worktree;
  57
  58#[derive(Debug, Copy, Clone, Hash, PartialEq, PartialOrd, Ord, Eq)]
  59#[repr(transparent)]
  60pub struct ThreadId(pub u64);
  61
  62impl ThreadId {
  63    pub const MIN: ThreadId = ThreadId(u64::MIN);
  64    pub const MAX: ThreadId = ThreadId(u64::MAX);
  65}
  66
  67impl From<u64> for ThreadId {
  68    fn from(id: u64) -> Self {
  69        Self(id)
  70    }
  71}
  72
  73#[derive(Clone, Debug)]
  74pub struct StackFrame {
  75    pub dap: dap::StackFrame,
  76    pub scopes: Vec<dap::Scope>,
  77}
  78
  79impl From<dap::StackFrame> for StackFrame {
  80    fn from(stack_frame: dap::StackFrame) -> Self {
  81        Self {
  82            scopes: vec![],
  83            dap: stack_frame,
  84        }
  85    }
  86}
  87
  88#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)]
  89pub enum ThreadStatus {
  90    #[default]
  91    Running,
  92    Stopped,
  93    Stepping,
  94    Exited,
  95    Ended,
  96}
  97
  98impl ThreadStatus {
  99    pub fn label(&self) -> &'static str {
 100        match self {
 101            ThreadStatus::Running => "Running",
 102            ThreadStatus::Stopped => "Stopped",
 103            ThreadStatus::Stepping => "Stepping",
 104            ThreadStatus::Exited => "Exited",
 105            ThreadStatus::Ended => "Ended",
 106        }
 107    }
 108}
 109
 110#[derive(Debug)]
 111pub struct Thread {
 112    dap: dap::Thread,
 113    stack_frames: Vec<StackFrame>,
 114    stack_frames_error: Option<anyhow::Error>,
 115    _has_stopped: bool,
 116}
 117
 118impl From<dap::Thread> for Thread {
 119    fn from(dap: dap::Thread) -> Self {
 120        Self {
 121            dap,
 122            stack_frames: Default::default(),
 123            stack_frames_error: None,
 124            _has_stopped: false,
 125        }
 126    }
 127}
 128
 129#[derive(Debug, Clone, PartialEq)]
 130pub struct Watcher {
 131    pub expression: SharedString,
 132    pub value: SharedString,
 133    pub variables_reference: u64,
 134    pub presentation_hint: Option<VariablePresentationHint>,
 135}
 136
 137pub enum Mode {
 138    Building,
 139    Running(RunningMode),
 140}
 141
 142#[derive(Clone)]
 143pub struct RunningMode {
 144    client: Arc<DebugAdapterClient>,
 145    binary: DebugAdapterBinary,
 146    tmp_breakpoint: Option<SourceBreakpoint>,
 147    worktree: WeakEntity<Worktree>,
 148    executor: BackgroundExecutor,
 149    is_started: bool,
 150    has_ever_stopped: bool,
 151    messages_tx: UnboundedSender<Message>,
 152}
 153
 154fn client_source(abs_path: &Path) -> dap::Source {
 155    dap::Source {
 156        name: abs_path
 157            .file_name()
 158            .map(|filename| filename.to_string_lossy().to_string()),
 159        path: Some(abs_path.to_string_lossy().to_string()),
 160        source_reference: None,
 161        presentation_hint: None,
 162        origin: None,
 163        sources: None,
 164        adapter_data: None,
 165        checksums: None,
 166    }
 167}
 168
 169impl RunningMode {
 170    async fn new(
 171        session_id: SessionId,
 172        parent_session: Option<Entity<Session>>,
 173        worktree: WeakEntity<Worktree>,
 174        binary: DebugAdapterBinary,
 175        messages_tx: futures::channel::mpsc::UnboundedSender<Message>,
 176        cx: &mut AsyncApp,
 177    ) -> Result<Self> {
 178        let message_handler = Box::new({
 179            let messages_tx = messages_tx.clone();
 180            move |message| {
 181                messages_tx.unbounded_send(message).ok();
 182            }
 183        });
 184
 185        let client = if let Some(client) = parent_session
 186            .and_then(|session| cx.update(|cx| session.read(cx).adapter_client()).ok())
 187            .flatten()
 188        {
 189            client
 190                .create_child_connection(session_id, binary.clone(), message_handler, cx)
 191                .await?
 192        } else {
 193            DebugAdapterClient::start(session_id, binary.clone(), message_handler, cx).await?
 194        };
 195
 196        Ok(Self {
 197            client: Arc::new(client),
 198            worktree,
 199            tmp_breakpoint: None,
 200            binary,
 201            executor: cx.background_executor().clone(),
 202            is_started: false,
 203            has_ever_stopped: false,
 204            messages_tx,
 205        })
 206    }
 207
 208    pub(crate) fn worktree(&self) -> &WeakEntity<Worktree> {
 209        &self.worktree
 210    }
 211
 212    fn unset_breakpoints_from_paths(&self, paths: &Vec<Arc<Path>>, cx: &mut App) -> Task<()> {
 213        let tasks: Vec<_> = paths
 214            .into_iter()
 215            .map(|path| {
 216                self.request(dap_command::SetBreakpoints {
 217                    source: client_source(path),
 218                    source_modified: None,
 219                    breakpoints: vec![],
 220                })
 221            })
 222            .collect();
 223
 224        cx.background_spawn(async move {
 225            futures::future::join_all(tasks)
 226                .await
 227                .iter()
 228                .for_each(|res| match res {
 229                    Ok(_) => {}
 230                    Err(err) => {
 231                        log::warn!("Set breakpoints request failed: {}", err);
 232                    }
 233                });
 234        })
 235    }
 236
 237    fn send_breakpoints_from_path(
 238        &self,
 239        abs_path: Arc<Path>,
 240        reason: BreakpointUpdatedReason,
 241        breakpoint_store: &Entity<BreakpointStore>,
 242        cx: &mut App,
 243    ) -> Task<()> {
 244        let breakpoints =
 245            breakpoint_store
 246                .read(cx)
 247                .source_breakpoints_from_path(&abs_path, cx)
 248                .into_iter()
 249                .filter(|bp| bp.state.is_enabled())
 250                .chain(self.tmp_breakpoint.iter().filter_map(|breakpoint| {
 251                    breakpoint.path.eq(&abs_path).then(|| breakpoint.clone())
 252                }))
 253                .map(Into::into)
 254                .collect();
 255
 256        let raw_breakpoints = breakpoint_store
 257            .read(cx)
 258            .breakpoints_from_path(&abs_path)
 259            .into_iter()
 260            .filter(|bp| bp.bp.state.is_enabled())
 261            .collect::<Vec<_>>();
 262
 263        let task = self.request(dap_command::SetBreakpoints {
 264            source: client_source(&abs_path),
 265            source_modified: Some(matches!(reason, BreakpointUpdatedReason::FileSaved)),
 266            breakpoints,
 267        });
 268        let session_id = self.client.id();
 269        let breakpoint_store = breakpoint_store.downgrade();
 270        cx.spawn(async move |cx| match cx.background_spawn(task).await {
 271            Ok(breakpoints) => {
 272                let breakpoints =
 273                    breakpoints
 274                        .into_iter()
 275                        .zip(raw_breakpoints)
 276                        .filter_map(|(dap_bp, zed_bp)| {
 277                            Some((
 278                                zed_bp,
 279                                BreakpointSessionState {
 280                                    id: dap_bp.id?,
 281                                    verified: dap_bp.verified,
 282                                },
 283                            ))
 284                        });
 285                breakpoint_store
 286                    .update(cx, |this, _| {
 287                        this.mark_breakpoints_verified(session_id, &abs_path, breakpoints);
 288                    })
 289                    .ok();
 290            }
 291            Err(err) => log::warn!("Set breakpoints request failed for path: {}", err),
 292        })
 293    }
 294
 295    fn send_exception_breakpoints(
 296        &self,
 297        filters: Vec<ExceptionBreakpointsFilter>,
 298        supports_filter_options: bool,
 299    ) -> Task<Result<Vec<dap::Breakpoint>>> {
 300        let arg = if supports_filter_options {
 301            SetExceptionBreakpoints::WithOptions {
 302                filters: filters
 303                    .into_iter()
 304                    .map(|filter| ExceptionFilterOptions {
 305                        filter_id: filter.filter,
 306                        condition: None,
 307                        mode: None,
 308                    })
 309                    .collect(),
 310            }
 311        } else {
 312            SetExceptionBreakpoints::Plain {
 313                filters: filters.into_iter().map(|filter| filter.filter).collect(),
 314            }
 315        };
 316        self.request(arg)
 317    }
 318
 319    fn send_source_breakpoints(
 320        &self,
 321        ignore_breakpoints: bool,
 322        breakpoint_store: &Entity<BreakpointStore>,
 323        cx: &App,
 324    ) -> Task<HashMap<Arc<Path>, anyhow::Error>> {
 325        let mut breakpoint_tasks = Vec::new();
 326        let breakpoints = breakpoint_store.read(cx).all_source_breakpoints(cx);
 327        let mut raw_breakpoints = breakpoint_store.read_with(cx, |this, _| this.all_breakpoints());
 328        debug_assert_eq!(raw_breakpoints.len(), breakpoints.len());
 329        let session_id = self.client.id();
 330        for (path, breakpoints) in breakpoints {
 331            let breakpoints = if ignore_breakpoints {
 332                vec![]
 333            } else {
 334                breakpoints
 335                    .into_iter()
 336                    .filter(|bp| bp.state.is_enabled())
 337                    .map(Into::into)
 338                    .collect()
 339            };
 340
 341            let raw_breakpoints = raw_breakpoints
 342                .remove(&path)
 343                .unwrap_or_default()
 344                .into_iter()
 345                .filter(|bp| bp.bp.state.is_enabled());
 346            let error_path = path.clone();
 347            let send_request = self
 348                .request(dap_command::SetBreakpoints {
 349                    source: client_source(&path),
 350                    source_modified: Some(false),
 351                    breakpoints,
 352                })
 353                .map(|result| result.map_err(move |e| (error_path, e)));
 354
 355            let task = cx.spawn({
 356                let breakpoint_store = breakpoint_store.downgrade();
 357                async move |cx| {
 358                    let breakpoints = cx.background_spawn(send_request).await?;
 359
 360                    let breakpoints = breakpoints.into_iter().zip(raw_breakpoints).filter_map(
 361                        |(dap_bp, zed_bp)| {
 362                            Some((
 363                                zed_bp,
 364                                BreakpointSessionState {
 365                                    id: dap_bp.id?,
 366                                    verified: dap_bp.verified,
 367                                },
 368                            ))
 369                        },
 370                    );
 371                    breakpoint_store
 372                        .update(cx, |this, _| {
 373                            this.mark_breakpoints_verified(session_id, &path, breakpoints);
 374                        })
 375                        .ok();
 376
 377                    Ok(())
 378                }
 379            });
 380            breakpoint_tasks.push(task);
 381        }
 382
 383        cx.background_spawn(async move {
 384            futures::future::join_all(breakpoint_tasks)
 385                .await
 386                .into_iter()
 387                .filter_map(Result::err)
 388                .collect::<HashMap<_, _>>()
 389        })
 390    }
 391
 392    fn initialize_sequence(
 393        &self,
 394        capabilities: &Capabilities,
 395        initialized_rx: oneshot::Receiver<()>,
 396        dap_store: WeakEntity<DapStore>,
 397        cx: &mut Context<Session>,
 398    ) -> Task<Result<()>> {
 399        let raw = self.binary.request_args.clone();
 400
 401        // Of relevance: https://github.com/microsoft/vscode/issues/4902#issuecomment-368583522
 402        let launch = match raw.request {
 403            dap::StartDebuggingRequestArgumentsRequest::Launch => self.request(Launch {
 404                raw: raw.configuration,
 405            }),
 406            dap::StartDebuggingRequestArgumentsRequest::Attach => self.request(Attach {
 407                raw: raw.configuration,
 408            }),
 409        };
 410
 411        let configuration_done_supported = ConfigurationDone::is_supported(capabilities);
 412        let exception_filters = capabilities
 413            .exception_breakpoint_filters
 414            .as_ref()
 415            .map(|exception_filters| {
 416                exception_filters
 417                    .iter()
 418                    .filter(|filter| filter.default == Some(true))
 419                    .cloned()
 420                    .collect::<Vec<_>>()
 421            })
 422            .unwrap_or_default();
 423        let supports_exception_filters = capabilities
 424            .supports_exception_filter_options
 425            .unwrap_or_default();
 426        let this = self.clone();
 427        let worktree = self.worktree().clone();
 428        let configuration_sequence = cx.spawn({
 429            async move |_, cx| {
 430                let breakpoint_store =
 431                    dap_store.read_with(cx, |dap_store, _| dap_store.breakpoint_store().clone())?;
 432                initialized_rx.await?;
 433                let errors_by_path = cx
 434                    .update(|cx| this.send_source_breakpoints(false, &breakpoint_store, cx))?
 435                    .await;
 436
 437                dap_store.update(cx, |_, cx| {
 438                    let Some(worktree) = worktree.upgrade() else {
 439                        return;
 440                    };
 441
 442                    for (path, error) in &errors_by_path {
 443                        log::error!("failed to set breakpoints for {path:?}: {error}");
 444                    }
 445
 446                    if let Some(failed_path) = errors_by_path.keys().next() {
 447                        let failed_path = failed_path
 448                            .strip_prefix(worktree.read(cx).abs_path())
 449                            .unwrap_or(failed_path)
 450                            .display();
 451                        let message = format!(
 452                            "Failed to set breakpoints for {failed_path}{}",
 453                            match errors_by_path.len() {
 454                                0 => unreachable!(),
 455                                1 => "".into(),
 456                                2 => " and 1 other path".into(),
 457                                n => format!(" and {} other paths", n - 1),
 458                            }
 459                        );
 460                        cx.emit(super::dap_store::DapStoreEvent::Notification(message));
 461                    }
 462                })?;
 463
 464                this.send_exception_breakpoints(exception_filters, supports_exception_filters)
 465                    .await
 466                    .ok();
 467                let ret = if configuration_done_supported {
 468                    this.request(ConfigurationDone {})
 469                } else {
 470                    Task::ready(Ok(()))
 471                }
 472                .await;
 473                ret
 474            }
 475        });
 476
 477        let task = cx.background_spawn(futures::future::try_join(launch, configuration_sequence));
 478
 479        cx.spawn(async move |this, cx| {
 480            let result = task.await;
 481
 482            this.update(cx, |this, cx| {
 483                if let Some(this) = this.as_running_mut() {
 484                    this.is_started = true;
 485                    cx.notify();
 486                }
 487            })
 488            .ok();
 489
 490            result?;
 491            anyhow::Ok(())
 492        })
 493    }
 494
 495    fn reconnect_for_ssh(&self, cx: &mut AsyncApp) -> Option<Task<Result<()>>> {
 496        let client = self.client.clone();
 497        let messages_tx = self.messages_tx.clone();
 498        let message_handler = Box::new(move |message| {
 499            messages_tx.unbounded_send(message).ok();
 500        });
 501        if client.should_reconnect_for_ssh() {
 502            Some(cx.spawn(async move |cx| {
 503                client.connect(message_handler, cx).await?;
 504                anyhow::Ok(())
 505            }))
 506        } else {
 507            None
 508        }
 509    }
 510
 511    fn request<R: LocalDapCommand>(&self, request: R) -> Task<Result<R::Response>>
 512    where
 513        <R::DapRequest as dap::requests::Request>::Response: 'static,
 514        <R::DapRequest as dap::requests::Request>::Arguments: 'static + Send,
 515    {
 516        let request = Arc::new(request);
 517
 518        let request_clone = request.clone();
 519        let connection = self.client.clone();
 520        self.executor.spawn(async move {
 521            let args = request_clone.to_dap();
 522            let response = connection.request::<R::DapRequest>(args).await?;
 523            request.response_from_dap(response)
 524        })
 525    }
 526}
 527
 528impl Mode {
 529    pub(super) fn request_dap<R: DapCommand>(&self, request: R) -> Task<Result<R::Response>>
 530    where
 531        <R::DapRequest as dap::requests::Request>::Response: 'static,
 532        <R::DapRequest as dap::requests::Request>::Arguments: 'static + Send,
 533    {
 534        match self {
 535            Mode::Running(debug_adapter_client) => debug_adapter_client.request(request),
 536            Mode::Building => Task::ready(Err(anyhow!(
 537                "no adapter running to send request: {request:?}"
 538            ))),
 539        }
 540    }
 541
 542    /// Did this debug session stop at least once?
 543    pub(crate) fn has_ever_stopped(&self) -> bool {
 544        match self {
 545            Mode::Building => false,
 546            Mode::Running(running_mode) => running_mode.has_ever_stopped,
 547        }
 548    }
 549
 550    fn stopped(&mut self) {
 551        if let Mode::Running(running) = self {
 552            running.has_ever_stopped = true;
 553        }
 554    }
 555}
 556
 557#[derive(Default)]
 558struct ThreadStates {
 559    global_state: Option<ThreadStatus>,
 560    known_thread_states: IndexMap<ThreadId, ThreadStatus>,
 561}
 562
 563impl ThreadStates {
 564    fn stop_all_threads(&mut self) {
 565        self.global_state = Some(ThreadStatus::Stopped);
 566        self.known_thread_states.clear();
 567    }
 568
 569    fn exit_all_threads(&mut self) {
 570        self.global_state = Some(ThreadStatus::Exited);
 571        self.known_thread_states.clear();
 572    }
 573
 574    fn continue_all_threads(&mut self) {
 575        self.global_state = Some(ThreadStatus::Running);
 576        self.known_thread_states.clear();
 577    }
 578
 579    fn stop_thread(&mut self, thread_id: ThreadId) {
 580        self.known_thread_states
 581            .insert(thread_id, ThreadStatus::Stopped);
 582    }
 583
 584    fn continue_thread(&mut self, thread_id: ThreadId) {
 585        self.known_thread_states
 586            .insert(thread_id, ThreadStatus::Running);
 587    }
 588
 589    fn process_step(&mut self, thread_id: ThreadId) {
 590        self.known_thread_states
 591            .insert(thread_id, ThreadStatus::Stepping);
 592    }
 593
 594    fn thread_status(&self, thread_id: ThreadId) -> ThreadStatus {
 595        self.thread_state(thread_id)
 596            .unwrap_or(ThreadStatus::Running)
 597    }
 598
 599    fn thread_state(&self, thread_id: ThreadId) -> Option<ThreadStatus> {
 600        self.known_thread_states
 601            .get(&thread_id)
 602            .copied()
 603            .or(self.global_state)
 604    }
 605
 606    fn exit_thread(&mut self, thread_id: ThreadId) {
 607        self.known_thread_states
 608            .insert(thread_id, ThreadStatus::Exited);
 609    }
 610
 611    fn any_stopped_thread(&self) -> bool {
 612        self.global_state
 613            .is_some_and(|state| state == ThreadStatus::Stopped)
 614            || self
 615                .known_thread_states
 616                .values()
 617                .any(|status| *status == ThreadStatus::Stopped)
 618    }
 619}
 620const MAX_TRACKED_OUTPUT_EVENTS: usize = 5000;
 621
 622type IsEnabled = bool;
 623
 624#[derive(Copy, Clone, Default, Debug, PartialEq, PartialOrd, Eq, Ord)]
 625pub struct OutputToken(pub usize);
 626/// Represents a current state of a single debug adapter and provides ways to mutate it.
 627pub struct Session {
 628    pub mode: Mode,
 629    id: SessionId,
 630    label: SharedString,
 631    adapter: DebugAdapterName,
 632    pub(super) capabilities: Capabilities,
 633    child_session_ids: HashSet<SessionId>,
 634    parent_session: Option<Entity<Session>>,
 635    modules: Vec<dap::Module>,
 636    loaded_sources: Vec<dap::Source>,
 637    output_token: OutputToken,
 638    output: Box<circular_buffer::CircularBuffer<MAX_TRACKED_OUTPUT_EVENTS, dap::OutputEvent>>,
 639    threads: IndexMap<ThreadId, Thread>,
 640    thread_states: ThreadStates,
 641    watchers: HashMap<SharedString, Watcher>,
 642    variables: HashMap<VariableReference, Vec<dap::Variable>>,
 643    stack_frames: IndexMap<StackFrameId, StackFrame>,
 644    locations: HashMap<u64, dap::LocationsResponse>,
 645    is_session_terminated: bool,
 646    requests: HashMap<TypeId, HashMap<RequestSlot, Shared<Task<Option<()>>>>>,
 647    pub(crate) breakpoint_store: Entity<BreakpointStore>,
 648    ignore_breakpoints: bool,
 649    exception_breakpoints: BTreeMap<String, (ExceptionBreakpointsFilter, IsEnabled)>,
 650    background_tasks: Vec<Task<()>>,
 651    task_context: TaskContext,
 652}
 653
 654trait CacheableCommand: Any + Send + Sync {
 655    fn dyn_eq(&self, rhs: &dyn CacheableCommand) -> bool;
 656    fn dyn_hash(&self, hasher: &mut dyn Hasher);
 657    fn as_any_arc(self: Arc<Self>) -> Arc<dyn Any + Send + Sync>;
 658}
 659
 660impl<T> CacheableCommand for T
 661where
 662    T: DapCommand + PartialEq + Eq + Hash,
 663{
 664    fn dyn_eq(&self, rhs: &dyn CacheableCommand) -> bool {
 665        (rhs as &dyn Any)
 666            .downcast_ref::<Self>()
 667            .map_or(false, |rhs| self == rhs)
 668    }
 669
 670    fn dyn_hash(&self, mut hasher: &mut dyn Hasher) {
 671        T::hash(self, &mut hasher);
 672    }
 673
 674    fn as_any_arc(self: Arc<Self>) -> Arc<dyn Any + Send + Sync> {
 675        self
 676    }
 677}
 678
 679pub(crate) struct RequestSlot(Arc<dyn CacheableCommand>);
 680
 681impl<T: DapCommand + PartialEq + Eq + Hash> From<T> for RequestSlot {
 682    fn from(request: T) -> Self {
 683        Self(Arc::new(request))
 684    }
 685}
 686
 687impl PartialEq for RequestSlot {
 688    fn eq(&self, other: &Self) -> bool {
 689        self.0.dyn_eq(other.0.as_ref())
 690    }
 691}
 692
 693impl Eq for RequestSlot {}
 694
 695impl Hash for RequestSlot {
 696    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
 697        self.0.dyn_hash(state);
 698        (&*self.0 as &dyn Any).type_id().hash(state)
 699    }
 700}
 701
 702#[derive(Debug, Clone, Hash, PartialEq, Eq)]
 703pub struct CompletionsQuery {
 704    pub query: String,
 705    pub column: u64,
 706    pub line: Option<u64>,
 707    pub frame_id: Option<u64>,
 708}
 709
 710impl CompletionsQuery {
 711    pub fn new(
 712        buffer: &language::Buffer,
 713        cursor_position: language::Anchor,
 714        frame_id: Option<u64>,
 715    ) -> Self {
 716        let PointUtf16 { row, column } = cursor_position.to_point_utf16(&buffer.snapshot());
 717        Self {
 718            query: buffer.text(),
 719            column: column as u64,
 720            frame_id,
 721            line: Some(row as u64),
 722        }
 723    }
 724}
 725
 726#[derive(Debug)]
 727pub enum SessionEvent {
 728    Modules,
 729    LoadedSources,
 730    Stopped(Option<ThreadId>),
 731    StackTrace,
 732    Variables,
 733    Watchers,
 734    Threads,
 735    InvalidateInlineValue,
 736    CapabilitiesLoaded,
 737    RunInTerminal {
 738        request: RunInTerminalRequestArguments,
 739        sender: mpsc::Sender<Result<u32>>,
 740    },
 741    ConsoleOutput,
 742}
 743
 744#[derive(Clone, Debug, PartialEq, Eq)]
 745pub enum SessionStateEvent {
 746    Running,
 747    Shutdown,
 748    Restart,
 749    SpawnChildSession {
 750        request: StartDebuggingRequestArguments,
 751    },
 752}
 753
 754impl EventEmitter<SessionEvent> for Session {}
 755impl EventEmitter<SessionStateEvent> for Session {}
 756
 757// local session will send breakpoint updates to DAP for all new breakpoints
 758// remote side will only send breakpoint updates when it is a breakpoint created by that peer
 759// BreakpointStore notifies session on breakpoint changes
 760impl Session {
 761    pub(crate) fn new(
 762        breakpoint_store: Entity<BreakpointStore>,
 763        session_id: SessionId,
 764        parent_session: Option<Entity<Session>>,
 765        label: SharedString,
 766        adapter: DebugAdapterName,
 767        task_context: TaskContext,
 768        cx: &mut App,
 769    ) -> Entity<Self> {
 770        cx.new::<Self>(|cx| {
 771            cx.subscribe(&breakpoint_store, |this, store, event, cx| match event {
 772                BreakpointStoreEvent::BreakpointsUpdated(path, reason) => {
 773                    if let Some(local) = (!this.ignore_breakpoints)
 774                        .then(|| this.as_running_mut())
 775                        .flatten()
 776                    {
 777                        local
 778                            .send_breakpoints_from_path(path.clone(), *reason, &store, cx)
 779                            .detach();
 780                    };
 781                }
 782                BreakpointStoreEvent::BreakpointsCleared(paths) => {
 783                    if let Some(local) = (!this.ignore_breakpoints)
 784                        .then(|| this.as_running_mut())
 785                        .flatten()
 786                    {
 787                        local.unset_breakpoints_from_paths(paths, cx).detach();
 788                    }
 789                }
 790                BreakpointStoreEvent::SetDebugLine | BreakpointStoreEvent::ClearDebugLines => {}
 791            })
 792            .detach();
 793            // cx.on_app_quit(Self::on_app_quit).detach();
 794
 795            let this = Self {
 796                mode: Mode::Building,
 797                id: session_id,
 798                child_session_ids: HashSet::default(),
 799                parent_session,
 800                capabilities: Capabilities::default(),
 801                watchers: HashMap::default(),
 802                variables: Default::default(),
 803                stack_frames: Default::default(),
 804                thread_states: ThreadStates::default(),
 805                output_token: OutputToken(0),
 806                output: circular_buffer::CircularBuffer::boxed(),
 807                requests: HashMap::default(),
 808                modules: Vec::default(),
 809                loaded_sources: Vec::default(),
 810                threads: IndexMap::default(),
 811                background_tasks: Vec::default(),
 812                locations: Default::default(),
 813                is_session_terminated: false,
 814                ignore_breakpoints: false,
 815                breakpoint_store,
 816                exception_breakpoints: Default::default(),
 817                label,
 818                adapter,
 819                task_context,
 820            };
 821
 822            this
 823        })
 824    }
 825
 826    pub fn task_context(&self) -> &TaskContext {
 827        &self.task_context
 828    }
 829
 830    pub fn worktree(&self) -> Option<Entity<Worktree>> {
 831        match &self.mode {
 832            Mode::Building => None,
 833            Mode::Running(local_mode) => local_mode.worktree.upgrade(),
 834        }
 835    }
 836
 837    pub fn boot(
 838        &mut self,
 839        binary: DebugAdapterBinary,
 840        worktree: Entity<Worktree>,
 841        dap_store: WeakEntity<DapStore>,
 842        cx: &mut Context<Self>,
 843    ) -> Task<Result<()>> {
 844        let (message_tx, mut message_rx) = futures::channel::mpsc::unbounded();
 845        let (initialized_tx, initialized_rx) = futures::channel::oneshot::channel();
 846
 847        let background_tasks = vec![cx.spawn(async move |this: WeakEntity<Session>, cx| {
 848            let mut initialized_tx = Some(initialized_tx);
 849            while let Some(message) = message_rx.next().await {
 850                if let Message::Event(event) = message {
 851                    if let Events::Initialized(_) = *event {
 852                        if let Some(tx) = initialized_tx.take() {
 853                            tx.send(()).ok();
 854                        }
 855                    } else {
 856                        let Ok(_) = this.update(cx, |session, cx| {
 857                            session.handle_dap_event(event, cx);
 858                        }) else {
 859                            break;
 860                        };
 861                    }
 862                } else if let Message::Request(request) = message {
 863                    let Ok(_) = this.update(cx, |this, cx| {
 864                        if request.command == StartDebugging::COMMAND {
 865                            this.handle_start_debugging_request(request, cx)
 866                                .detach_and_log_err(cx);
 867                        } else if request.command == RunInTerminal::COMMAND {
 868                            this.handle_run_in_terminal_request(request, cx)
 869                                .detach_and_log_err(cx);
 870                        }
 871                    }) else {
 872                        break;
 873                    };
 874                }
 875            }
 876        })];
 877        self.background_tasks = background_tasks;
 878        let id = self.id;
 879        let parent_session = self.parent_session.clone();
 880
 881        cx.spawn(async move |this, cx| {
 882            let mode = RunningMode::new(
 883                id,
 884                parent_session,
 885                worktree.downgrade(),
 886                binary.clone(),
 887                message_tx,
 888                cx,
 889            )
 890            .await?;
 891            this.update(cx, |this, cx| {
 892                this.mode = Mode::Running(mode);
 893                cx.emit(SessionStateEvent::Running);
 894            })?;
 895
 896            this.update(cx, |session, cx| session.request_initialize(cx))?
 897                .await?;
 898
 899            let result = this
 900                .update(cx, |session, cx| {
 901                    session.initialize_sequence(initialized_rx, dap_store.clone(), cx)
 902                })?
 903                .await;
 904
 905            if result.is_err() {
 906                let mut console = this.update(cx, |session, cx| session.console_output(cx))?;
 907
 908                console
 909                    .send(format!(
 910                        "Tried to launch debugger with: {}",
 911                        serde_json::to_string_pretty(&binary.request_args.configuration)
 912                            .unwrap_or_default(),
 913                    ))
 914                    .await
 915                    .ok();
 916            }
 917
 918            result
 919        })
 920    }
 921
 922    pub fn session_id(&self) -> SessionId {
 923        self.id
 924    }
 925
 926    pub fn child_session_ids(&self) -> HashSet<SessionId> {
 927        self.child_session_ids.clone()
 928    }
 929
 930    pub fn add_child_session_id(&mut self, session_id: SessionId) {
 931        self.child_session_ids.insert(session_id);
 932    }
 933
 934    pub fn remove_child_session_id(&mut self, session_id: SessionId) {
 935        self.child_session_ids.remove(&session_id);
 936    }
 937
 938    pub fn parent_id(&self, cx: &App) -> Option<SessionId> {
 939        self.parent_session
 940            .as_ref()
 941            .map(|session| session.read(cx).id)
 942    }
 943
 944    pub fn parent_session(&self) -> Option<&Entity<Self>> {
 945        self.parent_session.as_ref()
 946    }
 947
 948    pub fn on_app_quit(&mut self, cx: &mut Context<Self>) -> Task<()> {
 949        let Some(client) = self.adapter_client() else {
 950            return Task::ready(());
 951        };
 952
 953        let supports_terminate = self
 954            .capabilities
 955            .support_terminate_debuggee
 956            .unwrap_or(false);
 957
 958        cx.background_spawn(async move {
 959            if supports_terminate {
 960                client
 961                    .request::<dap::requests::Terminate>(dap::TerminateArguments {
 962                        restart: Some(false),
 963                    })
 964                    .await
 965                    .ok();
 966            } else {
 967                client
 968                    .request::<dap::requests::Disconnect>(dap::DisconnectArguments {
 969                        restart: Some(false),
 970                        terminate_debuggee: Some(true),
 971                        suspend_debuggee: Some(false),
 972                    })
 973                    .await
 974                    .ok();
 975            }
 976        })
 977    }
 978
 979    pub fn capabilities(&self) -> &Capabilities {
 980        &self.capabilities
 981    }
 982
 983    pub fn binary(&self) -> Option<&DebugAdapterBinary> {
 984        match &self.mode {
 985            Mode::Building => None,
 986            Mode::Running(running_mode) => Some(&running_mode.binary),
 987        }
 988    }
 989
 990    pub fn adapter(&self) -> DebugAdapterName {
 991        self.adapter.clone()
 992    }
 993
 994    pub fn label(&self) -> SharedString {
 995        self.label.clone()
 996    }
 997
 998    pub fn is_terminated(&self) -> bool {
 999        self.is_session_terminated
1000    }
1001
1002    pub fn console_output(&mut self, cx: &mut Context<Self>) -> mpsc::UnboundedSender<String> {
1003        let (tx, mut rx) = mpsc::unbounded();
1004
1005        cx.spawn(async move |this, cx| {
1006            while let Some(output) = rx.next().await {
1007                this.update(cx, |this, cx| {
1008                    let event = dap::OutputEvent {
1009                        category: None,
1010                        output,
1011                        group: None,
1012                        variables_reference: None,
1013                        source: None,
1014                        line: None,
1015                        column: None,
1016                        data: None,
1017                        location_reference: None,
1018                    };
1019                    this.push_output(event, cx);
1020                })?;
1021            }
1022            anyhow::Ok(())
1023        })
1024        .detach();
1025
1026        return tx;
1027    }
1028
1029    pub fn is_started(&self) -> bool {
1030        match &self.mode {
1031            Mode::Building => false,
1032            Mode::Running(running) => running.is_started,
1033        }
1034    }
1035
1036    pub fn is_building(&self) -> bool {
1037        matches!(self.mode, Mode::Building)
1038    }
1039
1040    pub fn as_running_mut(&mut self) -> Option<&mut RunningMode> {
1041        match &mut self.mode {
1042            Mode::Running(local_mode) => Some(local_mode),
1043            Mode::Building => None,
1044        }
1045    }
1046
1047    pub fn as_running(&self) -> Option<&RunningMode> {
1048        match &self.mode {
1049            Mode::Running(local_mode) => Some(local_mode),
1050            Mode::Building => None,
1051        }
1052    }
1053
1054    fn handle_start_debugging_request(
1055        &mut self,
1056        request: dap::messages::Request,
1057        cx: &mut Context<Self>,
1058    ) -> Task<Result<()>> {
1059        let request_seq = request.seq;
1060
1061        let launch_request: Option<Result<StartDebuggingRequestArguments, _>> = request
1062            .arguments
1063            .as_ref()
1064            .map(|value| serde_json::from_value(value.clone()));
1065
1066        let mut success = true;
1067        if let Some(Ok(request)) = launch_request {
1068            cx.emit(SessionStateEvent::SpawnChildSession { request });
1069        } else {
1070            log::error!(
1071                "Failed to parse launch request arguments: {:?}",
1072                request.arguments
1073            );
1074            success = false;
1075        }
1076
1077        cx.spawn(async move |this, cx| {
1078            this.update(cx, |this, cx| {
1079                this.respond_to_client(
1080                    request_seq,
1081                    success,
1082                    StartDebugging::COMMAND.to_string(),
1083                    None,
1084                    cx,
1085                )
1086            })?
1087            .await
1088        })
1089    }
1090
1091    fn handle_run_in_terminal_request(
1092        &mut self,
1093        request: dap::messages::Request,
1094        cx: &mut Context<Self>,
1095    ) -> Task<Result<()>> {
1096        let request_args = match serde_json::from_value::<RunInTerminalRequestArguments>(
1097            request.arguments.unwrap_or_default(),
1098        ) {
1099            Ok(args) => args,
1100            Err(error) => {
1101                return cx.spawn(async move |session, cx| {
1102                    let error = serde_json::to_value(dap::ErrorResponse {
1103                        error: Some(dap::Message {
1104                            id: request.seq,
1105                            format: error.to_string(),
1106                            variables: None,
1107                            send_telemetry: None,
1108                            show_user: None,
1109                            url: None,
1110                            url_label: None,
1111                        }),
1112                    })
1113                    .ok();
1114
1115                    session
1116                        .update(cx, |this, cx| {
1117                            this.respond_to_client(
1118                                request.seq,
1119                                false,
1120                                StartDebugging::COMMAND.to_string(),
1121                                error,
1122                                cx,
1123                            )
1124                        })?
1125                        .await?;
1126
1127                    Err(anyhow!("Failed to parse RunInTerminalRequestArguments"))
1128                });
1129            }
1130        };
1131
1132        let seq = request.seq;
1133
1134        let (tx, mut rx) = mpsc::channel::<Result<u32>>(1);
1135        cx.emit(SessionEvent::RunInTerminal {
1136            request: request_args,
1137            sender: tx,
1138        });
1139        cx.notify();
1140
1141        cx.spawn(async move |session, cx| {
1142            let result = util::maybe!(async move {
1143                rx.next().await.ok_or_else(|| {
1144                    anyhow!("failed to receive response from spawn terminal".to_string())
1145                })?
1146            })
1147            .await;
1148            let (success, body) = match result {
1149                Ok(pid) => (
1150                    true,
1151                    serde_json::to_value(dap::RunInTerminalResponse {
1152                        process_id: None,
1153                        shell_process_id: Some(pid as u64),
1154                    })
1155                    .ok(),
1156                ),
1157                Err(error) => (
1158                    false,
1159                    serde_json::to_value(dap::ErrorResponse {
1160                        error: Some(dap::Message {
1161                            id: seq,
1162                            format: error.to_string(),
1163                            variables: None,
1164                            send_telemetry: None,
1165                            show_user: None,
1166                            url: None,
1167                            url_label: None,
1168                        }),
1169                    })
1170                    .ok(),
1171                ),
1172            };
1173
1174            session
1175                .update(cx, |session, cx| {
1176                    session.respond_to_client(
1177                        seq,
1178                        success,
1179                        RunInTerminal::COMMAND.to_string(),
1180                        body,
1181                        cx,
1182                    )
1183                })?
1184                .await
1185        })
1186    }
1187
1188    pub(super) fn request_initialize(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
1189        let adapter_id = self.adapter().to_string();
1190        let request = Initialize { adapter_id };
1191
1192        let Mode::Running(running) = &self.mode else {
1193            return Task::ready(Err(anyhow!(
1194                "Cannot send initialize request, task still building"
1195            )));
1196        };
1197        let mut response = running.request(request.clone());
1198
1199        cx.spawn(async move |this, cx| {
1200            loop {
1201                let capabilities = response.await;
1202                match capabilities {
1203                    Err(e) => {
1204                        let Ok(Some(reconnect)) = this.update(cx, |this, cx| {
1205                            this.as_running()
1206                                .and_then(|running| running.reconnect_for_ssh(&mut cx.to_async()))
1207                        }) else {
1208                            return Err(e);
1209                        };
1210                        log::info!("Failed to connect to debug adapter: {}, retrying...", e);
1211                        reconnect.await?;
1212
1213                        let Ok(Some(r)) = this.update(cx, |this, _| {
1214                            this.as_running()
1215                                .map(|running| running.request(request.clone()))
1216                        }) else {
1217                            return Err(e);
1218                        };
1219                        response = r
1220                    }
1221                    Ok(capabilities) => {
1222                        this.update(cx, |session, cx| {
1223                            session.capabilities = capabilities;
1224                            let filters = session
1225                                .capabilities
1226                                .exception_breakpoint_filters
1227                                .clone()
1228                                .unwrap_or_default();
1229                            for filter in filters {
1230                                let default = filter.default.unwrap_or_default();
1231                                session
1232                                    .exception_breakpoints
1233                                    .entry(filter.filter.clone())
1234                                    .or_insert_with(|| (filter, default));
1235                            }
1236                            cx.emit(SessionEvent::CapabilitiesLoaded);
1237                        })?;
1238                        return Ok(());
1239                    }
1240                }
1241            }
1242        })
1243    }
1244
1245    pub(super) fn initialize_sequence(
1246        &mut self,
1247        initialize_rx: oneshot::Receiver<()>,
1248        dap_store: WeakEntity<DapStore>,
1249        cx: &mut Context<Self>,
1250    ) -> Task<Result<()>> {
1251        match &self.mode {
1252            Mode::Running(local_mode) => {
1253                local_mode.initialize_sequence(&self.capabilities, initialize_rx, dap_store, cx)
1254            }
1255            Mode::Building => Task::ready(Err(anyhow!("cannot initialize, still building"))),
1256        }
1257    }
1258
1259    pub fn run_to_position(
1260        &mut self,
1261        breakpoint: SourceBreakpoint,
1262        active_thread_id: ThreadId,
1263        cx: &mut Context<Self>,
1264    ) {
1265        match &mut self.mode {
1266            Mode::Running(local_mode) => {
1267                if !matches!(
1268                    self.thread_states.thread_state(active_thread_id),
1269                    Some(ThreadStatus::Stopped)
1270                ) {
1271                    return;
1272                };
1273                let path = breakpoint.path.clone();
1274                local_mode.tmp_breakpoint = Some(breakpoint);
1275                let task = local_mode.send_breakpoints_from_path(
1276                    path,
1277                    BreakpointUpdatedReason::Toggled,
1278                    &self.breakpoint_store,
1279                    cx,
1280                );
1281
1282                cx.spawn(async move |this, cx| {
1283                    task.await;
1284                    this.update(cx, |this, cx| {
1285                        this.continue_thread(active_thread_id, cx);
1286                    })
1287                })
1288                .detach();
1289            }
1290            Mode::Building => {}
1291        }
1292    }
1293
1294    pub fn has_new_output(&self, last_update: OutputToken) -> bool {
1295        self.output_token.0.checked_sub(last_update.0).unwrap_or(0) != 0
1296    }
1297
1298    pub fn output(
1299        &self,
1300        since: OutputToken,
1301    ) -> (impl Iterator<Item = &dap::OutputEvent>, OutputToken) {
1302        if self.output_token.0 == 0 {
1303            return (self.output.range(0..0), OutputToken(0));
1304        };
1305
1306        let events_since = self.output_token.0.checked_sub(since.0).unwrap_or(0);
1307
1308        let clamped_events_since = events_since.clamp(0, self.output.len());
1309        (
1310            self.output
1311                .range(self.output.len() - clamped_events_since..),
1312            self.output_token,
1313        )
1314    }
1315
1316    pub fn respond_to_client(
1317        &self,
1318        request_seq: u64,
1319        success: bool,
1320        command: String,
1321        body: Option<serde_json::Value>,
1322        cx: &mut Context<Self>,
1323    ) -> Task<Result<()>> {
1324        let Some(local_session) = self.as_running() else {
1325            unreachable!("Cannot respond to remote client");
1326        };
1327        let client = local_session.client.clone();
1328
1329        cx.background_spawn(async move {
1330            client
1331                .send_message(Message::Response(Response {
1332                    body,
1333                    success,
1334                    command,
1335                    seq: request_seq + 1,
1336                    request_seq,
1337                    message: None,
1338                }))
1339                .await
1340        })
1341    }
1342
1343    fn handle_stopped_event(&mut self, event: StoppedEvent, cx: &mut Context<Self>) {
1344        self.mode.stopped();
1345        // todo(debugger): Find a clean way to get around the clone
1346        let breakpoint_store = self.breakpoint_store.clone();
1347        if let Some((local, path)) = self.as_running_mut().and_then(|local| {
1348            let breakpoint = local.tmp_breakpoint.take()?;
1349            let path = breakpoint.path.clone();
1350            Some((local, path))
1351        }) {
1352            local
1353                .send_breakpoints_from_path(
1354                    path,
1355                    BreakpointUpdatedReason::Toggled,
1356                    &breakpoint_store,
1357                    cx,
1358                )
1359                .detach();
1360        };
1361
1362        if event.all_threads_stopped.unwrap_or_default() || event.thread_id.is_none() {
1363            self.thread_states.stop_all_threads();
1364            self.invalidate_command_type::<StackTraceCommand>();
1365        }
1366
1367        // Event if we stopped all threads we still need to insert the thread_id
1368        // to our own data
1369        if let Some(thread_id) = event.thread_id {
1370            self.thread_states.stop_thread(ThreadId(thread_id));
1371
1372            self.invalidate_state(
1373                &StackTraceCommand {
1374                    thread_id,
1375                    start_frame: None,
1376                    levels: None,
1377                }
1378                .into(),
1379            );
1380        }
1381
1382        self.invalidate_generic();
1383        self.threads.clear();
1384        self.variables.clear();
1385        cx.emit(SessionEvent::Stopped(
1386            event
1387                .thread_id
1388                .map(Into::into)
1389                .filter(|_| !event.preserve_focus_hint.unwrap_or(false)),
1390        ));
1391        cx.emit(SessionEvent::InvalidateInlineValue);
1392        cx.notify();
1393    }
1394
1395    pub(crate) fn handle_dap_event(&mut self, event: Box<Events>, cx: &mut Context<Self>) {
1396        match *event {
1397            Events::Initialized(_) => {
1398                debug_assert!(
1399                    false,
1400                    "Initialized event should have been handled in LocalMode"
1401                );
1402            }
1403            Events::Stopped(event) => self.handle_stopped_event(event, cx),
1404            Events::Continued(event) => {
1405                if event.all_threads_continued.unwrap_or_default() {
1406                    self.thread_states.continue_all_threads();
1407                    self.breakpoint_store.update(cx, |store, cx| {
1408                        store.remove_active_position(Some(self.session_id()), cx)
1409                    });
1410                } else {
1411                    self.thread_states
1412                        .continue_thread(ThreadId(event.thread_id));
1413                }
1414                // todo(debugger): We should be able to get away with only invalidating generic if all threads were continued
1415                self.invalidate_generic();
1416            }
1417            Events::Exited(_event) => {
1418                self.clear_active_debug_line(cx);
1419            }
1420            Events::Terminated(_) => {
1421                self.shutdown(cx).detach();
1422            }
1423            Events::Thread(event) => {
1424                let thread_id = ThreadId(event.thread_id);
1425
1426                match event.reason {
1427                    dap::ThreadEventReason::Started => {
1428                        self.thread_states.continue_thread(thread_id);
1429                    }
1430                    dap::ThreadEventReason::Exited => {
1431                        self.thread_states.exit_thread(thread_id);
1432                    }
1433                    reason => {
1434                        log::error!("Unhandled thread event reason {:?}", reason);
1435                    }
1436                }
1437                self.invalidate_state(&ThreadsCommand.into());
1438                cx.notify();
1439            }
1440            Events::Output(event) => {
1441                if event
1442                    .category
1443                    .as_ref()
1444                    .is_some_and(|category| *category == OutputEventCategory::Telemetry)
1445                {
1446                    return;
1447                }
1448
1449                self.push_output(event, cx);
1450                cx.notify();
1451            }
1452            Events::Breakpoint(event) => self.breakpoint_store.update(cx, |store, _| {
1453                store.update_session_breakpoint(self.session_id(), event.reason, event.breakpoint);
1454            }),
1455            Events::Module(event) => {
1456                match event.reason {
1457                    dap::ModuleEventReason::New => {
1458                        self.modules.push(event.module);
1459                    }
1460                    dap::ModuleEventReason::Changed => {
1461                        if let Some(module) = self
1462                            .modules
1463                            .iter_mut()
1464                            .find(|other| event.module.id == other.id)
1465                        {
1466                            *module = event.module;
1467                        }
1468                    }
1469                    dap::ModuleEventReason::Removed => {
1470                        self.modules.retain(|other| event.module.id != other.id);
1471                    }
1472                }
1473
1474                // todo(debugger): We should only send the invalidate command to downstream clients.
1475                // self.invalidate_state(&ModulesCommand.into());
1476            }
1477            Events::LoadedSource(_) => {
1478                self.invalidate_state(&LoadedSourcesCommand.into());
1479            }
1480            Events::Capabilities(event) => {
1481                self.capabilities = self.capabilities.merge(event.capabilities);
1482                cx.notify();
1483            }
1484            Events::Memory(_) => {}
1485            Events::Process(_) => {}
1486            Events::ProgressEnd(_) => {}
1487            Events::ProgressStart(_) => {}
1488            Events::ProgressUpdate(_) => {}
1489            Events::Invalidated(_) => {}
1490            Events::Other(_) => {}
1491        }
1492    }
1493
1494    /// Ensure that there's a request in flight for the given command, and if not, send it. Use this to run requests that are idempotent.
1495    fn fetch<T: DapCommand + PartialEq + Eq + Hash>(
1496        &mut self,
1497        request: T,
1498        process_result: impl FnOnce(&mut Self, Result<T::Response>, &mut Context<Self>) + 'static,
1499        cx: &mut Context<Self>,
1500    ) {
1501        const {
1502            assert!(
1503                T::CACHEABLE,
1504                "Only requests marked as cacheable should invoke `fetch`"
1505            );
1506        }
1507
1508        if !self.thread_states.any_stopped_thread()
1509            && request.type_id() != TypeId::of::<ThreadsCommand>()
1510            || self.is_session_terminated
1511        {
1512            return;
1513        }
1514
1515        let request_map = self
1516            .requests
1517            .entry(std::any::TypeId::of::<T>())
1518            .or_default();
1519
1520        if let Entry::Vacant(vacant) = request_map.entry(request.into()) {
1521            let command = vacant.key().0.clone().as_any_arc().downcast::<T>().unwrap();
1522
1523            let task = Self::request_inner::<Arc<T>>(
1524                &self.capabilities,
1525                &self.mode,
1526                command,
1527                |this, result, cx| {
1528                    process_result(this, result, cx);
1529                    None
1530                },
1531                cx,
1532            );
1533            let task = cx
1534                .background_executor()
1535                .spawn(async move {
1536                    let _ = task.await?;
1537                    Some(())
1538                })
1539                .shared();
1540
1541            vacant.insert(task);
1542            cx.notify();
1543        }
1544    }
1545
1546    fn request_inner<T: DapCommand + PartialEq + Eq + Hash>(
1547        capabilities: &Capabilities,
1548        mode: &Mode,
1549        request: T,
1550        process_result: impl FnOnce(
1551            &mut Self,
1552            Result<T::Response>,
1553            &mut Context<Self>,
1554        ) -> Option<T::Response>
1555        + 'static,
1556        cx: &mut Context<Self>,
1557    ) -> Task<Option<T::Response>> {
1558        if !T::is_supported(&capabilities) {
1559            log::warn!(
1560                "Attempted to send a DAP request that isn't supported: {:?}",
1561                request
1562            );
1563            let error = Err(anyhow::Error::msg(
1564                "Couldn't complete request because it's not supported",
1565            ));
1566            return cx.spawn(async move |this, cx| {
1567                this.update(cx, |this, cx| process_result(this, error, cx))
1568                    .ok()
1569                    .flatten()
1570            });
1571        }
1572
1573        let request = mode.request_dap(request);
1574        cx.spawn(async move |this, cx| {
1575            let result = request.await;
1576            this.update(cx, |this, cx| process_result(this, result, cx))
1577                .ok()
1578                .flatten()
1579        })
1580    }
1581
1582    fn request<T: DapCommand + PartialEq + Eq + Hash>(
1583        &self,
1584        request: T,
1585        process_result: impl FnOnce(
1586            &mut Self,
1587            Result<T::Response>,
1588            &mut Context<Self>,
1589        ) -> Option<T::Response>
1590        + 'static,
1591        cx: &mut Context<Self>,
1592    ) -> Task<Option<T::Response>> {
1593        Self::request_inner(&self.capabilities, &self.mode, request, process_result, cx)
1594    }
1595
1596    fn invalidate_command_type<Command: DapCommand>(&mut self) {
1597        self.requests.remove(&std::any::TypeId::of::<Command>());
1598    }
1599
1600    fn invalidate_generic(&mut self) {
1601        self.invalidate_command_type::<ModulesCommand>();
1602        self.invalidate_command_type::<LoadedSourcesCommand>();
1603        self.invalidate_command_type::<ThreadsCommand>();
1604    }
1605
1606    fn invalidate_state(&mut self, key: &RequestSlot) {
1607        self.requests
1608            .entry((&*key.0 as &dyn Any).type_id())
1609            .and_modify(|request_map| {
1610                request_map.remove(&key);
1611            });
1612    }
1613
1614    fn push_output(&mut self, event: OutputEvent, cx: &mut Context<Self>) {
1615        self.output.push_back(event);
1616        self.output_token.0 += 1;
1617        cx.emit(SessionEvent::ConsoleOutput);
1618    }
1619
1620    pub fn any_stopped_thread(&self) -> bool {
1621        self.thread_states.any_stopped_thread()
1622    }
1623
1624    pub fn thread_status(&self, thread_id: ThreadId) -> ThreadStatus {
1625        self.thread_states.thread_status(thread_id)
1626    }
1627
1628    pub fn threads(&mut self, cx: &mut Context<Self>) -> Vec<(dap::Thread, ThreadStatus)> {
1629        self.fetch(
1630            dap_command::ThreadsCommand,
1631            |this, result, cx| {
1632                let Some(result) = result.log_err() else {
1633                    return;
1634                };
1635
1636                this.threads = result
1637                    .into_iter()
1638                    .map(|thread| (ThreadId(thread.id), Thread::from(thread.clone())))
1639                    .collect();
1640
1641                this.invalidate_command_type::<StackTraceCommand>();
1642                cx.emit(SessionEvent::Threads);
1643                cx.notify();
1644            },
1645            cx,
1646        );
1647
1648        self.threads
1649            .values()
1650            .map(|thread| {
1651                (
1652                    thread.dap.clone(),
1653                    self.thread_states.thread_status(ThreadId(thread.dap.id)),
1654                )
1655            })
1656            .collect()
1657    }
1658
1659    pub fn modules(&mut self, cx: &mut Context<Self>) -> &[Module] {
1660        self.fetch(
1661            dap_command::ModulesCommand,
1662            |this, result, cx| {
1663                let Some(result) = result.log_err() else {
1664                    return;
1665                };
1666
1667                this.modules = result;
1668                cx.emit(SessionEvent::Modules);
1669                cx.notify();
1670            },
1671            cx,
1672        );
1673
1674        &self.modules
1675    }
1676
1677    pub fn ignore_breakpoints(&self) -> bool {
1678        self.ignore_breakpoints
1679    }
1680
1681    pub fn toggle_ignore_breakpoints(
1682        &mut self,
1683        cx: &mut App,
1684    ) -> Task<HashMap<Arc<Path>, anyhow::Error>> {
1685        self.set_ignore_breakpoints(!self.ignore_breakpoints, cx)
1686    }
1687
1688    pub(crate) fn set_ignore_breakpoints(
1689        &mut self,
1690        ignore: bool,
1691        cx: &mut App,
1692    ) -> Task<HashMap<Arc<Path>, anyhow::Error>> {
1693        if self.ignore_breakpoints == ignore {
1694            return Task::ready(HashMap::default());
1695        }
1696
1697        self.ignore_breakpoints = ignore;
1698
1699        if let Some(local) = self.as_running() {
1700            local.send_source_breakpoints(ignore, &self.breakpoint_store, cx)
1701        } else {
1702            // todo(debugger): We need to propagate this change to downstream sessions and send a message to upstream sessions
1703            unimplemented!()
1704        }
1705    }
1706
1707    pub fn exception_breakpoints(
1708        &self,
1709    ) -> impl Iterator<Item = &(ExceptionBreakpointsFilter, IsEnabled)> {
1710        self.exception_breakpoints.values()
1711    }
1712
1713    pub fn toggle_exception_breakpoint(&mut self, id: &str, cx: &App) {
1714        if let Some((_, is_enabled)) = self.exception_breakpoints.get_mut(id) {
1715            *is_enabled = !*is_enabled;
1716            self.send_exception_breakpoints(cx);
1717        }
1718    }
1719
1720    fn send_exception_breakpoints(&mut self, cx: &App) {
1721        if let Some(local) = self.as_running() {
1722            let exception_filters = self
1723                .exception_breakpoints
1724                .values()
1725                .filter_map(|(filter, is_enabled)| is_enabled.then(|| filter.clone()))
1726                .collect();
1727
1728            let supports_exception_filters = self
1729                .capabilities
1730                .supports_exception_filter_options
1731                .unwrap_or_default();
1732            local
1733                .send_exception_breakpoints(exception_filters, supports_exception_filters)
1734                .detach_and_log_err(cx);
1735        } else {
1736            debug_assert!(false, "Not implemented");
1737        }
1738    }
1739
1740    pub fn breakpoints_enabled(&self) -> bool {
1741        self.ignore_breakpoints
1742    }
1743
1744    pub fn loaded_sources(&mut self, cx: &mut Context<Self>) -> &[Source] {
1745        self.fetch(
1746            dap_command::LoadedSourcesCommand,
1747            |this, result, cx| {
1748                let Some(result) = result.log_err() else {
1749                    return;
1750                };
1751                this.loaded_sources = result;
1752                cx.emit(SessionEvent::LoadedSources);
1753                cx.notify();
1754            },
1755            cx,
1756        );
1757
1758        &self.loaded_sources
1759    }
1760
1761    fn fallback_to_manual_restart(
1762        &mut self,
1763        res: Result<()>,
1764        cx: &mut Context<Self>,
1765    ) -> Option<()> {
1766        if res.log_err().is_none() {
1767            cx.emit(SessionStateEvent::Restart);
1768            return None;
1769        }
1770        Some(())
1771    }
1772
1773    fn empty_response(&mut self, res: Result<()>, _cx: &mut Context<Self>) -> Option<()> {
1774        res.log_err()?;
1775        Some(())
1776    }
1777
1778    fn on_step_response<T: DapCommand + PartialEq + Eq + Hash>(
1779        thread_id: ThreadId,
1780    ) -> impl FnOnce(&mut Self, Result<T::Response>, &mut Context<Self>) -> Option<T::Response> + 'static
1781    {
1782        move |this, response, cx| match response.log_err() {
1783            Some(response) => {
1784                this.breakpoint_store.update(cx, |store, cx| {
1785                    store.remove_active_position(Some(this.session_id()), cx)
1786                });
1787                Some(response)
1788            }
1789            None => {
1790                this.thread_states.stop_thread(thread_id);
1791                cx.notify();
1792                None
1793            }
1794        }
1795    }
1796
1797    fn clear_active_debug_line_response(
1798        &mut self,
1799        response: Result<()>,
1800        cx: &mut Context<Session>,
1801    ) -> Option<()> {
1802        response.log_err()?;
1803        self.clear_active_debug_line(cx);
1804        Some(())
1805    }
1806
1807    fn clear_active_debug_line(&mut self, cx: &mut Context<Session>) {
1808        self.breakpoint_store.update(cx, |store, cx| {
1809            store.remove_active_position(Some(self.id), cx)
1810        });
1811    }
1812
1813    pub fn pause_thread(&mut self, thread_id: ThreadId, cx: &mut Context<Self>) {
1814        self.request(
1815            PauseCommand {
1816                thread_id: thread_id.0,
1817            },
1818            Self::empty_response,
1819            cx,
1820        )
1821        .detach();
1822    }
1823
1824    pub fn restart_stack_frame(&mut self, stack_frame_id: u64, cx: &mut Context<Self>) {
1825        self.request(
1826            RestartStackFrameCommand { stack_frame_id },
1827            Self::empty_response,
1828            cx,
1829        )
1830        .detach();
1831    }
1832
1833    pub fn restart(&mut self, args: Option<Value>, cx: &mut Context<Self>) {
1834        if self.capabilities.supports_restart_request.unwrap_or(false) && !self.is_terminated() {
1835            self.request(
1836                RestartCommand {
1837                    raw: args.unwrap_or(Value::Null),
1838                },
1839                Self::fallback_to_manual_restart,
1840                cx,
1841            )
1842            .detach();
1843        } else {
1844            cx.emit(SessionStateEvent::Restart);
1845        }
1846    }
1847
1848    pub fn shutdown(&mut self, cx: &mut Context<Self>) -> Task<()> {
1849        if self.is_session_terminated {
1850            return Task::ready(());
1851        }
1852
1853        self.is_session_terminated = true;
1854        self.thread_states.exit_all_threads();
1855        cx.notify();
1856
1857        let task = if self
1858            .capabilities
1859            .supports_terminate_request
1860            .unwrap_or_default()
1861        {
1862            self.request(
1863                TerminateCommand {
1864                    restart: Some(false),
1865                },
1866                Self::clear_active_debug_line_response,
1867                cx,
1868            )
1869        } else {
1870            self.request(
1871                DisconnectCommand {
1872                    restart: Some(false),
1873                    terminate_debuggee: Some(true),
1874                    suspend_debuggee: Some(false),
1875                },
1876                Self::clear_active_debug_line_response,
1877                cx,
1878            )
1879        };
1880
1881        cx.emit(SessionStateEvent::Shutdown);
1882
1883        cx.spawn(async move |_, _| {
1884            task.await;
1885        })
1886    }
1887
1888    pub fn completions(
1889        &mut self,
1890        query: CompletionsQuery,
1891        cx: &mut Context<Self>,
1892    ) -> Task<Result<Vec<dap::CompletionItem>>> {
1893        let task = self.request(query, |_, result, _| result.log_err(), cx);
1894
1895        cx.background_executor().spawn(async move {
1896            anyhow::Ok(
1897                task.await
1898                    .map(|response| response.targets)
1899                    .context("failed to fetch completions")?,
1900            )
1901        })
1902    }
1903
1904    pub fn continue_thread(&mut self, thread_id: ThreadId, cx: &mut Context<Self>) {
1905        self.thread_states.continue_thread(thread_id);
1906        self.request(
1907            ContinueCommand {
1908                args: ContinueArguments {
1909                    thread_id: thread_id.0,
1910                    single_thread: Some(true),
1911                },
1912            },
1913            Self::on_step_response::<ContinueCommand>(thread_id),
1914            cx,
1915        )
1916        .detach();
1917    }
1918
1919    pub fn adapter_client(&self) -> Option<Arc<DebugAdapterClient>> {
1920        match self.mode {
1921            Mode::Running(ref local) => Some(local.client.clone()),
1922            Mode::Building => None,
1923        }
1924    }
1925
1926    pub fn has_ever_stopped(&self) -> bool {
1927        self.mode.has_ever_stopped()
1928    }
1929    pub fn step_over(
1930        &mut self,
1931        thread_id: ThreadId,
1932        granularity: SteppingGranularity,
1933        cx: &mut Context<Self>,
1934    ) {
1935        let supports_single_thread_execution_requests =
1936            self.capabilities.supports_single_thread_execution_requests;
1937        let supports_stepping_granularity = self
1938            .capabilities
1939            .supports_stepping_granularity
1940            .unwrap_or_default();
1941
1942        let command = NextCommand {
1943            inner: StepCommand {
1944                thread_id: thread_id.0,
1945                granularity: supports_stepping_granularity.then(|| granularity),
1946                single_thread: supports_single_thread_execution_requests,
1947            },
1948        };
1949
1950        self.thread_states.process_step(thread_id);
1951        self.request(
1952            command,
1953            Self::on_step_response::<NextCommand>(thread_id),
1954            cx,
1955        )
1956        .detach();
1957    }
1958
1959    pub fn step_in(
1960        &mut self,
1961        thread_id: ThreadId,
1962        granularity: SteppingGranularity,
1963        cx: &mut Context<Self>,
1964    ) {
1965        let supports_single_thread_execution_requests =
1966            self.capabilities.supports_single_thread_execution_requests;
1967        let supports_stepping_granularity = self
1968            .capabilities
1969            .supports_stepping_granularity
1970            .unwrap_or_default();
1971
1972        let command = StepInCommand {
1973            inner: StepCommand {
1974                thread_id: thread_id.0,
1975                granularity: supports_stepping_granularity.then(|| granularity),
1976                single_thread: supports_single_thread_execution_requests,
1977            },
1978        };
1979
1980        self.thread_states.process_step(thread_id);
1981        self.request(
1982            command,
1983            Self::on_step_response::<StepInCommand>(thread_id),
1984            cx,
1985        )
1986        .detach();
1987    }
1988
1989    pub fn step_out(
1990        &mut self,
1991        thread_id: ThreadId,
1992        granularity: SteppingGranularity,
1993        cx: &mut Context<Self>,
1994    ) {
1995        let supports_single_thread_execution_requests =
1996            self.capabilities.supports_single_thread_execution_requests;
1997        let supports_stepping_granularity = self
1998            .capabilities
1999            .supports_stepping_granularity
2000            .unwrap_or_default();
2001
2002        let command = StepOutCommand {
2003            inner: StepCommand {
2004                thread_id: thread_id.0,
2005                granularity: supports_stepping_granularity.then(|| granularity),
2006                single_thread: supports_single_thread_execution_requests,
2007            },
2008        };
2009
2010        self.thread_states.process_step(thread_id);
2011        self.request(
2012            command,
2013            Self::on_step_response::<StepOutCommand>(thread_id),
2014            cx,
2015        )
2016        .detach();
2017    }
2018
2019    pub fn step_back(
2020        &mut self,
2021        thread_id: ThreadId,
2022        granularity: SteppingGranularity,
2023        cx: &mut Context<Self>,
2024    ) {
2025        let supports_single_thread_execution_requests =
2026            self.capabilities.supports_single_thread_execution_requests;
2027        let supports_stepping_granularity = self
2028            .capabilities
2029            .supports_stepping_granularity
2030            .unwrap_or_default();
2031
2032        let command = StepBackCommand {
2033            inner: StepCommand {
2034                thread_id: thread_id.0,
2035                granularity: supports_stepping_granularity.then(|| granularity),
2036                single_thread: supports_single_thread_execution_requests,
2037            },
2038        };
2039
2040        self.thread_states.process_step(thread_id);
2041
2042        self.request(
2043            command,
2044            Self::on_step_response::<StepBackCommand>(thread_id),
2045            cx,
2046        )
2047        .detach();
2048    }
2049
2050    pub fn stack_frames(
2051        &mut self,
2052        thread_id: ThreadId,
2053        cx: &mut Context<Self>,
2054    ) -> Result<Vec<StackFrame>> {
2055        if self.thread_states.thread_status(thread_id) == ThreadStatus::Stopped
2056            && self.requests.contains_key(&ThreadsCommand.type_id())
2057            && self.threads.contains_key(&thread_id)
2058        // ^ todo(debugger): We need a better way to check that we're not querying stale data
2059        // We could still be using an old thread id and have sent a new thread's request
2060        // This isn't the biggest concern right now because it hasn't caused any issues outside of tests
2061        // But it very well could cause a minor bug in the future that is hard to track down
2062        {
2063            self.fetch(
2064                super::dap_command::StackTraceCommand {
2065                    thread_id: thread_id.0,
2066                    start_frame: None,
2067                    levels: None,
2068                },
2069                move |this, stack_frames, cx| {
2070                    let entry =
2071                        this.threads
2072                            .entry(thread_id)
2073                            .and_modify(|thread| match &stack_frames {
2074                                Ok(stack_frames) => {
2075                                    thread.stack_frames = stack_frames
2076                                        .iter()
2077                                        .cloned()
2078                                        .map(StackFrame::from)
2079                                        .collect();
2080                                    thread.stack_frames_error = None;
2081                                }
2082                                Err(error) => {
2083                                    thread.stack_frames.clear();
2084                                    thread.stack_frames_error = Some(error.cloned());
2085                                }
2086                            });
2087                    debug_assert!(
2088                        matches!(entry, indexmap::map::Entry::Occupied(_)),
2089                        "Sent request for thread_id that doesn't exist"
2090                    );
2091                    if let Ok(stack_frames) = stack_frames {
2092                        this.stack_frames.extend(
2093                            stack_frames
2094                                .into_iter()
2095                                .filter(|frame| {
2096                                    // Workaround for JavaScript debug adapter sending out "fake" stack frames for delineating await points. This is fine,
2097                                    // except that they always use an id of 0 for it, which collides with other (valid) stack frames.
2098                                    !(frame.id == 0
2099                                        && frame.line == 0
2100                                        && frame.column == 0
2101                                        && frame.presentation_hint
2102                                            == Some(StackFramePresentationHint::Label))
2103                                })
2104                                .map(|frame| (frame.id, StackFrame::from(frame))),
2105                        );
2106                    }
2107
2108                    this.invalidate_command_type::<ScopesCommand>();
2109                    this.invalidate_command_type::<VariablesCommand>();
2110
2111                    cx.emit(SessionEvent::StackTrace);
2112                },
2113                cx,
2114            );
2115        }
2116
2117        match self.threads.get(&thread_id) {
2118            Some(thread) => {
2119                if let Some(error) = &thread.stack_frames_error {
2120                    Err(error.cloned())
2121                } else {
2122                    Ok(thread.stack_frames.clone())
2123                }
2124            }
2125            None => Ok(Vec::new()),
2126        }
2127    }
2128
2129    pub fn scopes(&mut self, stack_frame_id: u64, cx: &mut Context<Self>) -> &[dap::Scope] {
2130        if self.requests.contains_key(&TypeId::of::<ThreadsCommand>())
2131            && self
2132                .requests
2133                .contains_key(&TypeId::of::<StackTraceCommand>())
2134        {
2135            self.fetch(
2136                ScopesCommand { stack_frame_id },
2137                move |this, scopes, cx| {
2138                    let Some(scopes) = scopes.log_err() else {
2139                        return
2140                    };
2141
2142                    for scope in scopes.iter() {
2143                        this.variables(scope.variables_reference, cx);
2144                    }
2145
2146                    let entry = this
2147                        .stack_frames
2148                        .entry(stack_frame_id)
2149                        .and_modify(|stack_frame| {
2150                            stack_frame.scopes = scopes;
2151                        });
2152
2153                    cx.emit(SessionEvent::Variables);
2154
2155                    debug_assert!(
2156                        matches!(entry, indexmap::map::Entry::Occupied(_)),
2157                        "Sent scopes request for stack_frame_id that doesn't exist or hasn't been fetched"
2158                    );
2159                },
2160                cx,
2161            );
2162        }
2163
2164        self.stack_frames
2165            .get(&stack_frame_id)
2166            .map(|frame| frame.scopes.as_slice())
2167            .unwrap_or_default()
2168    }
2169
2170    pub fn variables_by_stack_frame_id(
2171        &self,
2172        stack_frame_id: StackFrameId,
2173        globals: bool,
2174        locals: bool,
2175    ) -> Vec<dap::Variable> {
2176        let Some(stack_frame) = self.stack_frames.get(&stack_frame_id) else {
2177            return Vec::new();
2178        };
2179
2180        stack_frame
2181            .scopes
2182            .iter()
2183            .filter(|scope| {
2184                (scope.name.to_lowercase().contains("local") && locals)
2185                    || (scope.name.to_lowercase().contains("global") && globals)
2186            })
2187            .filter_map(|scope| self.variables.get(&scope.variables_reference))
2188            .flatten()
2189            .cloned()
2190            .collect()
2191    }
2192
2193    pub fn watchers(&self) -> &HashMap<SharedString, Watcher> {
2194        &self.watchers
2195    }
2196
2197    pub fn add_watcher(
2198        &mut self,
2199        expression: SharedString,
2200        frame_id: u64,
2201        cx: &mut Context<Self>,
2202    ) -> Task<Result<()>> {
2203        let request = self.mode.request_dap(EvaluateCommand {
2204            expression: expression.to_string(),
2205            context: Some(EvaluateArgumentsContext::Watch),
2206            frame_id: Some(frame_id),
2207            source: None,
2208        });
2209
2210        cx.spawn(async move |this, cx| {
2211            let response = request.await?;
2212
2213            this.update(cx, |session, cx| {
2214                session.watchers.insert(
2215                    expression.clone(),
2216                    Watcher {
2217                        expression,
2218                        value: response.result.into(),
2219                        variables_reference: response.variables_reference,
2220                        presentation_hint: response.presentation_hint,
2221                    },
2222                );
2223                cx.emit(SessionEvent::Watchers);
2224            })
2225        })
2226    }
2227
2228    pub fn refresh_watchers(&mut self, frame_id: u64, cx: &mut Context<Self>) {
2229        let watches = self.watchers.clone();
2230        for (_, watch) in watches.into_iter() {
2231            self.add_watcher(watch.expression.clone(), frame_id, cx)
2232                .detach();
2233        }
2234    }
2235
2236    pub fn remove_watcher(&mut self, expression: SharedString) {
2237        self.watchers.remove(&expression);
2238    }
2239
2240    pub fn variables(
2241        &mut self,
2242        variables_reference: VariableReference,
2243        cx: &mut Context<Self>,
2244    ) -> Vec<dap::Variable> {
2245        let command = VariablesCommand {
2246            variables_reference,
2247            filter: None,
2248            start: None,
2249            count: None,
2250            format: None,
2251        };
2252
2253        self.fetch(
2254            command,
2255            move |this, variables, cx| {
2256                let Some(variables) = variables.log_err() else {
2257                    return;
2258                };
2259
2260                this.variables.insert(variables_reference, variables);
2261
2262                cx.emit(SessionEvent::Variables);
2263                cx.emit(SessionEvent::InvalidateInlineValue);
2264            },
2265            cx,
2266        );
2267
2268        self.variables
2269            .get(&variables_reference)
2270            .cloned()
2271            .unwrap_or_default()
2272    }
2273
2274    pub fn set_variable_value(
2275        &mut self,
2276        stack_frame_id: u64,
2277        variables_reference: u64,
2278        name: String,
2279        value: String,
2280        cx: &mut Context<Self>,
2281    ) {
2282        if self.capabilities.supports_set_variable.unwrap_or_default() {
2283            self.request(
2284                SetVariableValueCommand {
2285                    name,
2286                    value,
2287                    variables_reference,
2288                },
2289                move |this, response, cx| {
2290                    let response = response.log_err()?;
2291                    this.invalidate_command_type::<VariablesCommand>();
2292                    this.refresh_watchers(stack_frame_id, cx);
2293                    cx.emit(SessionEvent::Variables);
2294                    Some(response)
2295                },
2296                cx,
2297            )
2298            .detach();
2299        }
2300    }
2301
2302    pub fn evaluate(
2303        &mut self,
2304        expression: String,
2305        context: Option<EvaluateArgumentsContext>,
2306        frame_id: Option<u64>,
2307        source: Option<Source>,
2308        cx: &mut Context<Self>,
2309    ) -> Task<()> {
2310        let event = dap::OutputEvent {
2311            category: None,
2312            output: format!("> {expression}"),
2313            group: None,
2314            variables_reference: None,
2315            source: None,
2316            line: None,
2317            column: None,
2318            data: None,
2319            location_reference: None,
2320        };
2321        self.push_output(event, cx);
2322        let request = self.mode.request_dap(EvaluateCommand {
2323            expression,
2324            context,
2325            frame_id,
2326            source,
2327        });
2328        cx.spawn(async move |this, cx| {
2329            let response = request.await;
2330            this.update(cx, |this, cx| {
2331                match response {
2332                    Ok(response) => {
2333                        let event = dap::OutputEvent {
2334                            category: None,
2335                            output: format!("< {}", &response.result),
2336                            group: None,
2337                            variables_reference: Some(response.variables_reference),
2338                            source: None,
2339                            line: None,
2340                            column: None,
2341                            data: None,
2342                            location_reference: None,
2343                        };
2344                        this.push_output(event, cx);
2345                    }
2346                    Err(e) => {
2347                        let event = dap::OutputEvent {
2348                            category: None,
2349                            output: format!("{}", e),
2350                            group: None,
2351                            variables_reference: None,
2352                            source: None,
2353                            line: None,
2354                            column: None,
2355                            data: None,
2356                            location_reference: None,
2357                        };
2358                        this.push_output(event, cx);
2359                    }
2360                };
2361                cx.notify();
2362            })
2363            .ok();
2364        })
2365    }
2366
2367    pub fn location(
2368        &mut self,
2369        reference: u64,
2370        cx: &mut Context<Self>,
2371    ) -> Option<dap::LocationsResponse> {
2372        self.fetch(
2373            LocationsCommand { reference },
2374            move |this, response, _| {
2375                let Some(response) = response.log_err() else {
2376                    return;
2377                };
2378                this.locations.insert(reference, response);
2379            },
2380            cx,
2381        );
2382        self.locations.get(&reference).cloned()
2383    }
2384
2385    pub fn is_attached(&self) -> bool {
2386        let Mode::Running(local_mode) = &self.mode else {
2387            return false;
2388        };
2389        local_mode.binary.request_args.request == StartDebuggingRequestArgumentsRequest::Attach
2390    }
2391
2392    pub fn disconnect_client(&mut self, cx: &mut Context<Self>) {
2393        let command = DisconnectCommand {
2394            restart: Some(false),
2395            terminate_debuggee: Some(false),
2396            suspend_debuggee: Some(false),
2397        };
2398
2399        self.request(command, Self::empty_response, cx).detach()
2400    }
2401
2402    pub fn terminate_threads(&mut self, thread_ids: Option<Vec<ThreadId>>, cx: &mut Context<Self>) {
2403        if self
2404            .capabilities
2405            .supports_terminate_threads_request
2406            .unwrap_or_default()
2407        {
2408            self.request(
2409                TerminateThreadsCommand {
2410                    thread_ids: thread_ids.map(|ids| ids.into_iter().map(|id| id.0).collect()),
2411                },
2412                Self::clear_active_debug_line_response,
2413                cx,
2414            )
2415            .detach();
2416        } else {
2417            self.shutdown(cx).detach();
2418        }
2419    }
2420
2421    pub fn thread_state(&self, thread_id: ThreadId) -> Option<ThreadStatus> {
2422        self.thread_states.thread_state(thread_id)
2423    }
2424}