session.rs

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