project.rs

   1pub mod agent_registry_store;
   2pub mod agent_server_store;
   3pub mod buffer_store;
   4pub mod color_extractor;
   5pub mod connection_manager;
   6pub mod context_server_store;
   7pub mod debounced_delay;
   8pub mod debugger;
   9pub mod git_store;
  10pub mod image_store;
  11pub mod lsp_command;
  12pub mod lsp_store;
  13pub mod manifest_tree;
  14pub mod prettier_store;
  15pub mod project_search;
  16pub mod project_settings;
  17pub mod search;
  18pub mod task_inventory;
  19pub mod task_store;
  20pub mod telemetry_snapshot;
  21pub mod terminals;
  22pub mod toolchain_store;
  23pub mod trusted_worktrees;
  24pub mod worktree_store;
  25
  26mod environment;
  27use buffer_diff::BufferDiff;
  28use context_server_store::ContextServerStore;
  29pub use environment::ProjectEnvironmentEvent;
  30use git::repository::get_git_committer;
  31use git_store::{Repository, RepositoryId};
  32pub mod search_history;
  33pub mod yarn;
  34
  35use dap::inline_value::{InlineValueLocation, VariableLookupKind, VariableScope};
  36use itertools::Either;
  37
  38use crate::{
  39    git_store::GitStore,
  40    lsp_store::{SymbolLocation, log_store::LogKind},
  41    project_search::SearchResultsHandle,
  42    trusted_worktrees::{PathTrust, RemoteHostLocation, TrustedWorktrees},
  43    worktree_store::WorktreeIdCounter,
  44};
  45pub use agent_registry_store::{AgentRegistryStore, RegistryAgent};
  46pub use agent_server_store::{
  47    AgentServerStore, AgentServersUpdated, ExternalAgentServerName, ExternalAgentSource,
  48};
  49pub use git_store::{
  50    ConflictRegion, ConflictSet, ConflictSetSnapshot, ConflictSetUpdate,
  51    git_traversal::{ChildEntriesGitIter, GitEntry, GitEntryRef, GitTraversal},
  52};
  53pub use manifest_tree::ManifestTree;
  54pub use project_search::{Search, SearchResults};
  55
  56use anyhow::{Context as _, Result, anyhow};
  57use buffer_store::{BufferStore, BufferStoreEvent};
  58use client::{
  59    Client, Collaborator, PendingEntitySubscription, ProjectId, TypedEnvelope, UserStore, proto,
  60};
  61use clock::ReplicaId;
  62
  63use dap::client::DebugAdapterClient;
  64
  65use collections::{BTreeSet, HashMap, HashSet, IndexSet};
  66use debounced_delay::DebouncedDelay;
  67pub use debugger::breakpoint_store::BreakpointWithPosition;
  68use debugger::{
  69    breakpoint_store::{ActiveStackFrame, BreakpointStore},
  70    dap_store::{DapStore, DapStoreEvent},
  71    session::Session,
  72};
  73
  74pub use environment::ProjectEnvironment;
  75
  76use futures::{
  77    StreamExt,
  78    channel::mpsc::{self, UnboundedReceiver},
  79    future::try_join_all,
  80};
  81pub use image_store::{ImageItem, ImageStore};
  82use image_store::{ImageItemEvent, ImageStoreEvent};
  83
  84use ::git::{blame::Blame, status::FileStatus};
  85use gpui::{
  86    App, AppContext, AsyncApp, BorrowAppContext, Context, Entity, EventEmitter, Hsla, SharedString,
  87    Task, WeakEntity, Window,
  88};
  89use language::{
  90    Buffer, BufferEvent, Capability, CodeLabel, CursorShape, DiskState, Language, LanguageName,
  91    LanguageRegistry, PointUtf16, ToOffset, ToPointUtf16, Toolchain, ToolchainMetadata,
  92    ToolchainScope, Transaction, Unclipped, language_settings::InlayHintKind,
  93    proto::split_operations,
  94};
  95use lsp::{
  96    CodeActionKind, CompletionContext, CompletionItemKind, DocumentHighlightKind, InsertTextMode,
  97    LanguageServerBinary, LanguageServerId, LanguageServerName, LanguageServerSelector,
  98    MessageActionItem,
  99};
 100use lsp_command::*;
 101use lsp_store::{CompletionDocumentation, LspFormatTarget, OpenLspBufferHandle};
 102pub use manifest_tree::ManifestProvidersStore;
 103use node_runtime::NodeRuntime;
 104use parking_lot::Mutex;
 105pub use prettier_store::PrettierStore;
 106use project_settings::{ProjectSettings, SettingsObserver, SettingsObserverEvent};
 107#[cfg(target_os = "windows")]
 108use remote::wsl_path_to_windows_path;
 109use remote::{RemoteClient, RemoteConnectionOptions};
 110use rpc::{
 111    AnyProtoClient, ErrorCode,
 112    proto::{LanguageServerPromptResponse, REMOTE_SERVER_PROJECT_ID},
 113};
 114use search::{SearchInputKind, SearchQuery, SearchResult};
 115use search_history::SearchHistory;
 116use settings::{InvalidSettingsError, RegisterSetting, Settings, SettingsLocation, SettingsStore};
 117use snippet::Snippet;
 118pub use snippet_provider;
 119use snippet_provider::SnippetProvider;
 120use std::{
 121    borrow::Cow,
 122    collections::BTreeMap,
 123    ffi::OsString,
 124    ops::{Not as _, Range},
 125    path::{Path, PathBuf},
 126    pin::pin,
 127    str::{self, FromStr},
 128    sync::Arc,
 129    time::Duration,
 130};
 131
 132use task_store::TaskStore;
 133use terminals::Terminals;
 134use text::{Anchor, BufferId, OffsetRangeExt, Point, Rope};
 135use toolchain_store::EmptyToolchainStore;
 136use util::{
 137    ResultExt as _, maybe,
 138    paths::{PathStyle, SanitizedPath, is_absolute},
 139    rel_path::RelPath,
 140};
 141use worktree::{CreatedEntry, Snapshot, Traversal};
 142pub use worktree::{
 143    Entry, EntryKind, FS_WATCH_LATENCY, File, LocalWorktree, PathChange, ProjectEntryId,
 144    UpdatedEntriesSet, UpdatedGitRepositoriesSet, Worktree, WorktreeId, WorktreeSettings,
 145};
 146use worktree_store::{WorktreeStore, WorktreeStoreEvent};
 147
 148pub use fs::*;
 149pub use language::Location;
 150#[cfg(any(test, feature = "test-support"))]
 151pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
 152pub use task_inventory::{
 153    BasicContextProvider, ContextProviderWithTasks, DebugScenarioContext, Inventory, TaskContexts,
 154    TaskSourceKind,
 155};
 156
 157pub use buffer_store::ProjectTransaction;
 158pub use lsp_store::{
 159    DiagnosticSummary, InvalidationStrategy, LanguageServerLogType, LanguageServerProgress,
 160    LanguageServerPromptRequest, LanguageServerStatus, LanguageServerToQuery, LspStore,
 161    LspStoreEvent, ProgressToken, SERVER_PROGRESS_THROTTLE_TIMEOUT,
 162};
 163pub use toolchain_store::{ToolchainStore, Toolchains};
 164const MAX_PROJECT_SEARCH_HISTORY_SIZE: usize = 500;
 165
 166#[derive(Clone, Copy, Debug)]
 167pub struct LocalProjectFlags {
 168    pub init_worktree_trust: bool,
 169    pub watch_global_configs: bool,
 170}
 171
 172impl Default for LocalProjectFlags {
 173    fn default() -> Self {
 174        Self {
 175            init_worktree_trust: true,
 176            watch_global_configs: true,
 177        }
 178    }
 179}
 180
 181pub trait ProjectItem: 'static {
 182    fn try_open(
 183        project: &Entity<Project>,
 184        path: &ProjectPath,
 185        cx: &mut App,
 186    ) -> Option<Task<Result<Entity<Self>>>>
 187    where
 188        Self: Sized;
 189    fn entry_id(&self, cx: &App) -> Option<ProjectEntryId>;
 190    fn project_path(&self, cx: &App) -> Option<ProjectPath>;
 191    fn is_dirty(&self) -> bool;
 192}
 193
 194#[derive(Clone)]
 195pub enum OpenedBufferEvent {
 196    Disconnected,
 197    Ok(BufferId),
 198    Err(BufferId, Arc<anyhow::Error>),
 199}
 200
 201/// Semantics-aware entity that is relevant to one or more [`Worktree`] with the files.
 202/// `Project` is responsible for tasks, LSP and collab queries, synchronizing worktree states accordingly.
 203/// Maps [`Worktree`] entries with its own logic using [`ProjectEntryId`] and [`ProjectPath`] structs.
 204///
 205/// Can be either local (for the project opened on the same host) or remote.(for collab projects, browsed by multiple remote users).
 206pub struct Project {
 207    active_entry: Option<ProjectEntryId>,
 208    buffer_ordered_messages_tx: mpsc::UnboundedSender<BufferOrderedMessage>,
 209    languages: Arc<LanguageRegistry>,
 210    dap_store: Entity<DapStore>,
 211    agent_server_store: Entity<AgentServerStore>,
 212
 213    breakpoint_store: Entity<BreakpointStore>,
 214    collab_client: Arc<client::Client>,
 215    join_project_response_message_id: u32,
 216    task_store: Entity<TaskStore>,
 217    user_store: Entity<UserStore>,
 218    fs: Arc<dyn Fs>,
 219    remote_client: Option<Entity<RemoteClient>>,
 220    // todo lw explain the client_state x remote_client matrix, its super confusing
 221    client_state: ProjectClientState,
 222    git_store: Entity<GitStore>,
 223    collaborators: HashMap<proto::PeerId, Collaborator>,
 224    client_subscriptions: Vec<client::Subscription>,
 225    worktree_store: Entity<WorktreeStore>,
 226    buffer_store: Entity<BufferStore>,
 227    context_server_store: Entity<ContextServerStore>,
 228    image_store: Entity<ImageStore>,
 229    lsp_store: Entity<LspStore>,
 230    _subscriptions: Vec<gpui::Subscription>,
 231    buffers_needing_diff: HashSet<WeakEntity<Buffer>>,
 232    git_diff_debouncer: DebouncedDelay<Self>,
 233    remotely_created_models: Arc<Mutex<RemotelyCreatedModels>>,
 234    terminals: Terminals,
 235    node: Option<NodeRuntime>,
 236    search_history: SearchHistory,
 237    search_included_history: SearchHistory,
 238    search_excluded_history: SearchHistory,
 239    snippets: Entity<SnippetProvider>,
 240    environment: Entity<ProjectEnvironment>,
 241    settings_observer: Entity<SettingsObserver>,
 242    toolchain_store: Option<Entity<ToolchainStore>>,
 243    agent_location: Option<AgentLocation>,
 244    downloading_files: Arc<Mutex<HashMap<(WorktreeId, String), DownloadingFile>>>,
 245}
 246
 247struct DownloadingFile {
 248    destination_path: PathBuf,
 249    chunks: Vec<u8>,
 250    total_size: u64,
 251    file_id: Option<u64>, // Set when we receive the State message
 252}
 253
 254#[derive(Clone, Debug, PartialEq, Eq)]
 255pub struct AgentLocation {
 256    pub buffer: WeakEntity<Buffer>,
 257    pub position: Anchor,
 258}
 259
 260#[derive(Default)]
 261struct RemotelyCreatedModels {
 262    worktrees: Vec<Entity<Worktree>>,
 263    buffers: Vec<Entity<Buffer>>,
 264    retain_count: usize,
 265}
 266
 267struct RemotelyCreatedModelGuard {
 268    remote_models: std::sync::Weak<Mutex<RemotelyCreatedModels>>,
 269}
 270
 271impl Drop for RemotelyCreatedModelGuard {
 272    fn drop(&mut self) {
 273        if let Some(remote_models) = self.remote_models.upgrade() {
 274            let mut remote_models = remote_models.lock();
 275            assert!(
 276                remote_models.retain_count > 0,
 277                "RemotelyCreatedModelGuard dropped too many times"
 278            );
 279            remote_models.retain_count -= 1;
 280            if remote_models.retain_count == 0 {
 281                remote_models.buffers.clear();
 282                remote_models.worktrees.clear();
 283            }
 284        }
 285    }
 286}
 287/// Message ordered with respect to buffer operations
 288#[derive(Debug)]
 289enum BufferOrderedMessage {
 290    Operation {
 291        buffer_id: BufferId,
 292        operation: proto::Operation,
 293    },
 294    LanguageServerUpdate {
 295        language_server_id: LanguageServerId,
 296        message: proto::update_language_server::Variant,
 297        name: Option<LanguageServerName>,
 298    },
 299    Resync,
 300}
 301
 302#[derive(Debug)]
 303enum ProjectClientState {
 304    /// Single-player mode.
 305    Local,
 306    /// Multi-player mode but still a local project.
 307    Shared { remote_id: u64 },
 308    /// Multi-player mode but working on a remote project.
 309    Remote {
 310        sharing_has_stopped: bool,
 311        capability: Capability,
 312        remote_id: u64,
 313        replica_id: ReplicaId,
 314    },
 315}
 316
 317/// A link to display in a toast notification, useful to point to documentation.
 318#[derive(PartialEq, Debug, Clone)]
 319pub struct ToastLink {
 320    pub label: &'static str,
 321    pub url: &'static str,
 322}
 323
 324#[derive(Clone, Debug, PartialEq)]
 325pub enum Event {
 326    LanguageServerAdded(LanguageServerId, LanguageServerName, Option<WorktreeId>),
 327    LanguageServerRemoved(LanguageServerId),
 328    LanguageServerLog(LanguageServerId, LanguageServerLogType, String),
 329    // [`lsp::notification::DidOpenTextDocument`] was sent to this server using the buffer data.
 330    // Zed's buffer-related data is updated accordingly.
 331    LanguageServerBufferRegistered {
 332        server_id: LanguageServerId,
 333        buffer_id: BufferId,
 334        buffer_abs_path: PathBuf,
 335        name: Option<LanguageServerName>,
 336    },
 337    ToggleLspLogs {
 338        server_id: LanguageServerId,
 339        enabled: bool,
 340        toggled_log_kind: LogKind,
 341    },
 342    Toast {
 343        notification_id: SharedString,
 344        message: String,
 345        /// Optional link to display as a button in the toast.
 346        link: Option<ToastLink>,
 347    },
 348    HideToast {
 349        notification_id: SharedString,
 350    },
 351    LanguageServerPrompt(LanguageServerPromptRequest),
 352    LanguageNotFound(Entity<Buffer>),
 353    ActiveEntryChanged(Option<ProjectEntryId>),
 354    ActivateProjectPanel,
 355    WorktreeAdded(WorktreeId),
 356    WorktreeOrderChanged,
 357    WorktreeRemoved(WorktreeId),
 358    WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
 359    DiskBasedDiagnosticsStarted {
 360        language_server_id: LanguageServerId,
 361    },
 362    DiskBasedDiagnosticsFinished {
 363        language_server_id: LanguageServerId,
 364    },
 365    DiagnosticsUpdated {
 366        paths: Vec<ProjectPath>,
 367        language_server_id: LanguageServerId,
 368    },
 369    RemoteIdChanged(Option<u64>),
 370    DisconnectedFromHost,
 371    DisconnectedFromRemote {
 372        server_not_running: bool,
 373    },
 374    Closed,
 375    DeletedEntry(WorktreeId, ProjectEntryId),
 376    CollaboratorUpdated {
 377        old_peer_id: proto::PeerId,
 378        new_peer_id: proto::PeerId,
 379    },
 380    CollaboratorJoined(proto::PeerId),
 381    CollaboratorLeft(proto::PeerId),
 382    HostReshared,
 383    Reshared,
 384    Rejoined,
 385    RefreshInlayHints {
 386        server_id: LanguageServerId,
 387        request_id: Option<usize>,
 388    },
 389    RefreshSemanticTokens {
 390        server_id: LanguageServerId,
 391        request_id: Option<usize>,
 392    },
 393    RefreshCodeLens,
 394    RevealInProjectPanel(ProjectEntryId),
 395    SnippetEdit(BufferId, Vec<(lsp::Range, Snippet)>),
 396    ExpandedAllForEntry(WorktreeId, ProjectEntryId),
 397    EntryRenamed(ProjectTransaction, ProjectPath, PathBuf),
 398    WorkspaceEditApplied(ProjectTransaction),
 399    AgentLocationChanged,
 400    BufferEdited,
 401}
 402
 403pub struct AgentLocationChanged;
 404
 405pub enum DebugAdapterClientState {
 406    Starting(Task<Option<Arc<DebugAdapterClient>>>),
 407    Running(Arc<DebugAdapterClient>),
 408}
 409
 410#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
 411pub struct ProjectPath {
 412    pub worktree_id: WorktreeId,
 413    pub path: Arc<RelPath>,
 414}
 415
 416impl ProjectPath {
 417    pub fn from_file(value: &dyn language::File, cx: &App) -> Self {
 418        ProjectPath {
 419            worktree_id: value.worktree_id(cx),
 420            path: value.path().clone(),
 421        }
 422    }
 423
 424    pub fn from_proto(p: proto::ProjectPath) -> Option<Self> {
 425        Some(Self {
 426            worktree_id: WorktreeId::from_proto(p.worktree_id),
 427            path: RelPath::from_proto(&p.path).log_err()?,
 428        })
 429    }
 430
 431    pub fn to_proto(&self) -> proto::ProjectPath {
 432        proto::ProjectPath {
 433            worktree_id: self.worktree_id.to_proto(),
 434            path: self.path.as_ref().to_proto(),
 435        }
 436    }
 437
 438    pub fn root_path(worktree_id: WorktreeId) -> Self {
 439        Self {
 440            worktree_id,
 441            path: RelPath::empty().into(),
 442        }
 443    }
 444
 445    pub fn starts_with(&self, other: &ProjectPath) -> bool {
 446        self.worktree_id == other.worktree_id && self.path.starts_with(&other.path)
 447    }
 448}
 449
 450#[derive(Debug, Default)]
 451pub enum PrepareRenameResponse {
 452    Success(Range<Anchor>),
 453    OnlyUnpreparedRenameSupported,
 454    #[default]
 455    InvalidPosition,
 456}
 457
 458#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
 459pub enum InlayId {
 460    EditPrediction(usize),
 461    DebuggerValue(usize),
 462    // LSP
 463    Hint(usize),
 464    Color(usize),
 465    ReplResult(usize),
 466}
 467
 468impl InlayId {
 469    pub fn id(&self) -> usize {
 470        match self {
 471            Self::EditPrediction(id) => *id,
 472            Self::DebuggerValue(id) => *id,
 473            Self::Hint(id) => *id,
 474            Self::Color(id) => *id,
 475            Self::ReplResult(id) => *id,
 476        }
 477    }
 478}
 479
 480#[derive(Debug, Clone, PartialEq, Eq)]
 481pub struct InlayHint {
 482    pub position: language::Anchor,
 483    pub label: InlayHintLabel,
 484    pub kind: Option<InlayHintKind>,
 485    pub padding_left: bool,
 486    pub padding_right: bool,
 487    pub tooltip: Option<InlayHintTooltip>,
 488    pub resolve_state: ResolveState,
 489}
 490
 491/// The user's intent behind a given completion confirmation.
 492#[derive(PartialEq, Eq, Hash, Debug, Clone, Copy)]
 493pub enum CompletionIntent {
 494    /// The user intends to 'commit' this result, if possible.
 495    /// Completion confirmations should run side effects.
 496    ///
 497    /// For LSP completions, will respect the setting `completions.lsp_insert_mode`.
 498    Complete,
 499    /// Similar to [Self::Complete], but behaves like `lsp_insert_mode` is set to `insert`.
 500    CompleteWithInsert,
 501    /// Similar to [Self::Complete], but behaves like `lsp_insert_mode` is set to `replace`.
 502    CompleteWithReplace,
 503    /// The user intends to continue 'composing' this completion.
 504    /// Completion confirmations should not run side effects and
 505    /// let the user continue composing their action.
 506    Compose,
 507}
 508
 509impl CompletionIntent {
 510    pub fn is_complete(&self) -> bool {
 511        self == &Self::Complete
 512    }
 513
 514    pub fn is_compose(&self) -> bool {
 515        self == &Self::Compose
 516    }
 517}
 518
 519/// Similar to `CoreCompletion`, but with extra metadata attached.
 520#[derive(Clone)]
 521pub struct Completion {
 522    /// The range of text that will be replaced by this completion.
 523    pub replace_range: Range<Anchor>,
 524    /// The new text that will be inserted.
 525    pub new_text: String,
 526    /// A label for this completion that is shown in the menu.
 527    pub label: CodeLabel,
 528    /// The documentation for this completion.
 529    pub documentation: Option<CompletionDocumentation>,
 530    /// Completion data source which it was constructed from.
 531    pub source: CompletionSource,
 532    /// A path to an icon for this completion that is shown in the menu.
 533    pub icon_path: Option<SharedString>,
 534    /// Text starting here and ending at the cursor will be used as the query for filtering this completion.
 535    ///
 536    /// If None, the start of the surrounding word is used.
 537    pub match_start: Option<text::Anchor>,
 538    /// Key used for de-duplicating snippets. If None, always considered unique.
 539    pub snippet_deduplication_key: Option<(usize, usize)>,
 540    /// Whether to adjust indentation (the default) or not.
 541    pub insert_text_mode: Option<InsertTextMode>,
 542    /// An optional callback to invoke when this completion is confirmed.
 543    /// Returns whether new completions should be retriggered after the current one.
 544    /// If `true` is returned, the editor will show a new completion menu after this completion is confirmed.
 545    /// if no confirmation is provided or `false` is returned, the completion will be committed.
 546    pub confirm: Option<Arc<dyn Send + Sync + Fn(CompletionIntent, &mut Window, &mut App) -> bool>>,
 547}
 548
 549#[derive(Debug, Clone)]
 550pub enum CompletionSource {
 551    Lsp {
 552        /// The alternate `insert` range, if provided by the LSP server.
 553        insert_range: Option<Range<Anchor>>,
 554        /// The id of the language server that produced this completion.
 555        server_id: LanguageServerId,
 556        /// The raw completion provided by the language server.
 557        lsp_completion: Box<lsp::CompletionItem>,
 558        /// A set of defaults for this completion item.
 559        lsp_defaults: Option<Arc<lsp::CompletionListItemDefaults>>,
 560        /// Whether this completion has been resolved, to ensure it happens once per completion.
 561        resolved: bool,
 562    },
 563    Dap {
 564        /// The sort text for this completion.
 565        sort_text: String,
 566    },
 567    Custom,
 568    BufferWord {
 569        word_range: Range<Anchor>,
 570        resolved: bool,
 571    },
 572}
 573
 574impl CompletionSource {
 575    pub fn server_id(&self) -> Option<LanguageServerId> {
 576        if let CompletionSource::Lsp { server_id, .. } = self {
 577            Some(*server_id)
 578        } else {
 579            None
 580        }
 581    }
 582
 583    pub fn lsp_completion(&self, apply_defaults: bool) -> Option<Cow<'_, lsp::CompletionItem>> {
 584        if let Self::Lsp {
 585            lsp_completion,
 586            lsp_defaults,
 587            ..
 588        } = self
 589        {
 590            if apply_defaults && let Some(lsp_defaults) = lsp_defaults {
 591                let mut completion_with_defaults = *lsp_completion.clone();
 592                let default_commit_characters = lsp_defaults.commit_characters.as_ref();
 593                let default_edit_range = lsp_defaults.edit_range.as_ref();
 594                let default_insert_text_format = lsp_defaults.insert_text_format.as_ref();
 595                let default_insert_text_mode = lsp_defaults.insert_text_mode.as_ref();
 596
 597                if default_commit_characters.is_some()
 598                    || default_edit_range.is_some()
 599                    || default_insert_text_format.is_some()
 600                    || default_insert_text_mode.is_some()
 601                {
 602                    if completion_with_defaults.commit_characters.is_none()
 603                        && default_commit_characters.is_some()
 604                    {
 605                        completion_with_defaults.commit_characters =
 606                            default_commit_characters.cloned()
 607                    }
 608                    if completion_with_defaults.text_edit.is_none() {
 609                        match default_edit_range {
 610                            Some(lsp::CompletionListItemDefaultsEditRange::Range(range)) => {
 611                                completion_with_defaults.text_edit =
 612                                    Some(lsp::CompletionTextEdit::Edit(lsp::TextEdit {
 613                                        range: *range,
 614                                        new_text: completion_with_defaults.label.clone(),
 615                                    }))
 616                            }
 617                            Some(lsp::CompletionListItemDefaultsEditRange::InsertAndReplace {
 618                                insert,
 619                                replace,
 620                            }) => {
 621                                completion_with_defaults.text_edit =
 622                                    Some(lsp::CompletionTextEdit::InsertAndReplace(
 623                                        lsp::InsertReplaceEdit {
 624                                            new_text: completion_with_defaults.label.clone(),
 625                                            insert: *insert,
 626                                            replace: *replace,
 627                                        },
 628                                    ))
 629                            }
 630                            None => {}
 631                        }
 632                    }
 633                    if completion_with_defaults.insert_text_format.is_none()
 634                        && default_insert_text_format.is_some()
 635                    {
 636                        completion_with_defaults.insert_text_format =
 637                            default_insert_text_format.cloned()
 638                    }
 639                    if completion_with_defaults.insert_text_mode.is_none()
 640                        && default_insert_text_mode.is_some()
 641                    {
 642                        completion_with_defaults.insert_text_mode =
 643                            default_insert_text_mode.cloned()
 644                    }
 645                }
 646                return Some(Cow::Owned(completion_with_defaults));
 647            }
 648            Some(Cow::Borrowed(lsp_completion))
 649        } else {
 650            None
 651        }
 652    }
 653}
 654
 655impl std::fmt::Debug for Completion {
 656    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 657        f.debug_struct("Completion")
 658            .field("replace_range", &self.replace_range)
 659            .field("new_text", &self.new_text)
 660            .field("label", &self.label)
 661            .field("documentation", &self.documentation)
 662            .field("source", &self.source)
 663            .finish()
 664    }
 665}
 666
 667/// Response from a source of completions.
 668pub struct CompletionResponse {
 669    pub completions: Vec<Completion>,
 670    pub display_options: CompletionDisplayOptions,
 671    /// When false, indicates that the list is complete and does not need to be re-queried if it
 672    /// can be filtered instead.
 673    pub is_incomplete: bool,
 674}
 675
 676#[derive(Default)]
 677pub struct CompletionDisplayOptions {
 678    pub dynamic_width: bool,
 679}
 680
 681impl CompletionDisplayOptions {
 682    pub fn merge(&mut self, other: &CompletionDisplayOptions) {
 683        self.dynamic_width = self.dynamic_width && other.dynamic_width;
 684    }
 685}
 686
 687/// Response from language server completion request.
 688#[derive(Clone, Debug, Default)]
 689pub(crate) struct CoreCompletionResponse {
 690    pub completions: Vec<CoreCompletion>,
 691    /// When false, indicates that the list is complete and does not need to be re-queried if it
 692    /// can be filtered instead.
 693    pub is_incomplete: bool,
 694}
 695
 696/// A generic completion that can come from different sources.
 697#[derive(Clone, Debug)]
 698pub(crate) struct CoreCompletion {
 699    replace_range: Range<Anchor>,
 700    new_text: String,
 701    source: CompletionSource,
 702}
 703
 704/// A code action provided by a language server.
 705#[derive(Clone, Debug, PartialEq)]
 706pub struct CodeAction {
 707    /// The id of the language server that produced this code action.
 708    pub server_id: LanguageServerId,
 709    /// The range of the buffer where this code action is applicable.
 710    pub range: Range<Anchor>,
 711    /// The raw code action provided by the language server.
 712    /// Can be either an action or a command.
 713    pub lsp_action: LspAction,
 714    /// Whether the action needs to be resolved using the language server.
 715    pub resolved: bool,
 716}
 717
 718/// An action sent back by a language server.
 719#[derive(Clone, Debug, PartialEq)]
 720pub enum LspAction {
 721    /// An action with the full data, may have a command or may not.
 722    /// May require resolving.
 723    Action(Box<lsp::CodeAction>),
 724    /// A command data to run as an action.
 725    Command(lsp::Command),
 726    /// A code lens data to run as an action.
 727    CodeLens(lsp::CodeLens),
 728}
 729
 730impl LspAction {
 731    pub fn title(&self) -> &str {
 732        match self {
 733            Self::Action(action) => &action.title,
 734            Self::Command(command) => &command.title,
 735            Self::CodeLens(lens) => lens
 736                .command
 737                .as_ref()
 738                .map(|command| command.title.as_str())
 739                .unwrap_or("Unknown command"),
 740        }
 741    }
 742
 743    pub fn action_kind(&self) -> Option<lsp::CodeActionKind> {
 744        match self {
 745            Self::Action(action) => action.kind.clone(),
 746            Self::Command(_) => Some(lsp::CodeActionKind::new("command")),
 747            Self::CodeLens(_) => Some(lsp::CodeActionKind::new("code lens")),
 748        }
 749    }
 750
 751    fn edit(&self) -> Option<&lsp::WorkspaceEdit> {
 752        match self {
 753            Self::Action(action) => action.edit.as_ref(),
 754            Self::Command(_) => None,
 755            Self::CodeLens(_) => None,
 756        }
 757    }
 758
 759    fn command(&self) -> Option<&lsp::Command> {
 760        match self {
 761            Self::Action(action) => action.command.as_ref(),
 762            Self::Command(command) => Some(command),
 763            Self::CodeLens(lens) => lens.command.as_ref(),
 764        }
 765    }
 766}
 767
 768#[derive(Debug, Clone, PartialEq, Eq)]
 769pub enum ResolveState {
 770    Resolved,
 771    CanResolve(LanguageServerId, Option<lsp::LSPAny>),
 772    Resolving,
 773}
 774impl InlayHint {
 775    pub fn text(&self) -> Rope {
 776        match &self.label {
 777            InlayHintLabel::String(s) => Rope::from(s),
 778            InlayHintLabel::LabelParts(parts) => parts.iter().map(|part| &*part.value).collect(),
 779        }
 780    }
 781}
 782
 783#[derive(Debug, Clone, PartialEq, Eq)]
 784pub enum InlayHintLabel {
 785    String(String),
 786    LabelParts(Vec<InlayHintLabelPart>),
 787}
 788
 789#[derive(Debug, Clone, PartialEq, Eq)]
 790pub struct InlayHintLabelPart {
 791    pub value: String,
 792    pub tooltip: Option<InlayHintLabelPartTooltip>,
 793    pub location: Option<(LanguageServerId, lsp::Location)>,
 794}
 795
 796#[derive(Debug, Clone, PartialEq, Eq)]
 797pub enum InlayHintTooltip {
 798    String(String),
 799    MarkupContent(MarkupContent),
 800}
 801
 802#[derive(Debug, Clone, PartialEq, Eq)]
 803pub enum InlayHintLabelPartTooltip {
 804    String(String),
 805    MarkupContent(MarkupContent),
 806}
 807
 808#[derive(Debug, Clone, PartialEq, Eq)]
 809pub struct MarkupContent {
 810    pub kind: HoverBlockKind,
 811    pub value: String,
 812}
 813
 814#[derive(Debug, Clone, PartialEq)]
 815pub struct LocationLink {
 816    pub origin: Option<Location>,
 817    pub target: Location,
 818}
 819
 820#[derive(Debug)]
 821pub struct DocumentHighlight {
 822    pub range: Range<language::Anchor>,
 823    pub kind: DocumentHighlightKind,
 824}
 825
 826#[derive(Clone, Debug)]
 827pub struct Symbol {
 828    pub language_server_name: LanguageServerName,
 829    pub source_worktree_id: WorktreeId,
 830    pub source_language_server_id: LanguageServerId,
 831    pub path: SymbolLocation,
 832    pub label: CodeLabel,
 833    pub name: String,
 834    pub kind: lsp::SymbolKind,
 835    pub range: Range<Unclipped<PointUtf16>>,
 836    pub container_name: Option<String>,
 837}
 838
 839#[derive(Clone, Debug)]
 840pub struct DocumentSymbol {
 841    pub name: String,
 842    pub kind: lsp::SymbolKind,
 843    pub range: Range<Unclipped<PointUtf16>>,
 844    pub selection_range: Range<Unclipped<PointUtf16>>,
 845    pub children: Vec<DocumentSymbol>,
 846}
 847
 848#[derive(Clone, Debug, PartialEq)]
 849pub struct HoverBlock {
 850    pub text: String,
 851    pub kind: HoverBlockKind,
 852}
 853
 854#[derive(Clone, Debug, PartialEq, Eq)]
 855pub enum HoverBlockKind {
 856    PlainText,
 857    Markdown,
 858    Code { language: String },
 859}
 860
 861#[derive(Debug, Clone)]
 862pub struct Hover {
 863    pub contents: Vec<HoverBlock>,
 864    pub range: Option<Range<language::Anchor>>,
 865    pub language: Option<Arc<Language>>,
 866}
 867
 868impl Hover {
 869    pub fn is_empty(&self) -> bool {
 870        self.contents.iter().all(|block| block.text.is_empty())
 871    }
 872}
 873
 874enum EntitySubscription {
 875    Project(PendingEntitySubscription<Project>),
 876    BufferStore(PendingEntitySubscription<BufferStore>),
 877    GitStore(PendingEntitySubscription<GitStore>),
 878    WorktreeStore(PendingEntitySubscription<WorktreeStore>),
 879    LspStore(PendingEntitySubscription<LspStore>),
 880    SettingsObserver(PendingEntitySubscription<SettingsObserver>),
 881    DapStore(PendingEntitySubscription<DapStore>),
 882    BreakpointStore(PendingEntitySubscription<BreakpointStore>),
 883}
 884
 885#[derive(Debug, Clone)]
 886pub struct DirectoryItem {
 887    pub path: PathBuf,
 888    pub is_dir: bool,
 889}
 890
 891#[derive(Clone, Debug, PartialEq)]
 892pub struct DocumentColor {
 893    pub lsp_range: lsp::Range,
 894    pub color: lsp::Color,
 895    pub resolved: bool,
 896    pub color_presentations: Vec<ColorPresentation>,
 897}
 898
 899impl Eq for DocumentColor {}
 900
 901impl std::hash::Hash for DocumentColor {
 902    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
 903        self.lsp_range.hash(state);
 904        self.color.red.to_bits().hash(state);
 905        self.color.green.to_bits().hash(state);
 906        self.color.blue.to_bits().hash(state);
 907        self.color.alpha.to_bits().hash(state);
 908        self.resolved.hash(state);
 909        self.color_presentations.hash(state);
 910    }
 911}
 912
 913#[derive(Clone, Debug, PartialEq, Eq)]
 914pub struct ColorPresentation {
 915    pub label: SharedString,
 916    pub text_edit: Option<lsp::TextEdit>,
 917    pub additional_text_edits: Vec<lsp::TextEdit>,
 918}
 919
 920impl std::hash::Hash for ColorPresentation {
 921    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
 922        self.label.hash(state);
 923        if let Some(ref edit) = self.text_edit {
 924            edit.range.hash(state);
 925            edit.new_text.hash(state);
 926        }
 927        self.additional_text_edits.len().hash(state);
 928        for edit in &self.additional_text_edits {
 929            edit.range.hash(state);
 930            edit.new_text.hash(state);
 931        }
 932    }
 933}
 934
 935#[derive(Clone)]
 936pub enum DirectoryLister {
 937    Project(Entity<Project>),
 938    Local(Entity<Project>, Arc<dyn Fs>),
 939}
 940
 941impl std::fmt::Debug for DirectoryLister {
 942    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 943        match self {
 944            DirectoryLister::Project(project) => {
 945                write!(f, "DirectoryLister::Project({project:?})")
 946            }
 947            DirectoryLister::Local(project, _) => {
 948                write!(f, "DirectoryLister::Local({project:?})")
 949            }
 950        }
 951    }
 952}
 953
 954impl DirectoryLister {
 955    pub fn is_local(&self, cx: &App) -> bool {
 956        match self {
 957            DirectoryLister::Local(..) => true,
 958            DirectoryLister::Project(project) => project.read(cx).is_local(),
 959        }
 960    }
 961
 962    pub fn resolve_tilde<'a>(&self, path: &'a String, cx: &App) -> Cow<'a, str> {
 963        if self.is_local(cx) {
 964            shellexpand::tilde(path)
 965        } else {
 966            Cow::from(path)
 967        }
 968    }
 969
 970    pub fn default_query(&self, cx: &mut App) -> String {
 971        let project = match self {
 972            DirectoryLister::Project(project) => project,
 973            DirectoryLister::Local(project, _) => project,
 974        }
 975        .read(cx);
 976        let path_style = project.path_style(cx);
 977        project
 978            .visible_worktrees(cx)
 979            .next()
 980            .map(|worktree| worktree.read(cx).abs_path().to_string_lossy().into_owned())
 981            .or_else(|| std::env::home_dir().map(|dir| dir.to_string_lossy().into_owned()))
 982            .map(|mut s| {
 983                s.push_str(path_style.primary_separator());
 984                s
 985            })
 986            .unwrap_or_else(|| {
 987                if path_style.is_windows() {
 988                    "C:\\"
 989                } else {
 990                    "~/"
 991                }
 992                .to_string()
 993            })
 994    }
 995
 996    pub fn list_directory(&self, path: String, cx: &mut App) -> Task<Result<Vec<DirectoryItem>>> {
 997        match self {
 998            DirectoryLister::Project(project) => {
 999                project.update(cx, |project, cx| project.list_directory(path, cx))
1000            }
1001            DirectoryLister::Local(_, fs) => {
1002                let fs = fs.clone();
1003                cx.background_spawn(async move {
1004                    let mut results = vec![];
1005                    let expanded = shellexpand::tilde(&path);
1006                    let query = Path::new(expanded.as_ref());
1007                    let mut response = fs.read_dir(query).await?;
1008                    while let Some(path) = response.next().await {
1009                        let path = path?;
1010                        if let Some(file_name) = path.file_name() {
1011                            results.push(DirectoryItem {
1012                                path: PathBuf::from(file_name.to_os_string()),
1013                                is_dir: fs.is_dir(&path).await,
1014                            });
1015                        }
1016                    }
1017                    Ok(results)
1018                })
1019            }
1020        }
1021    }
1022
1023    pub fn path_style(&self, cx: &App) -> PathStyle {
1024        match self {
1025            Self::Local(project, ..) | Self::Project(project, ..) => {
1026                project.read(cx).path_style(cx)
1027            }
1028        }
1029    }
1030}
1031
1032#[cfg(feature = "test-support")]
1033pub const DEFAULT_COMPLETION_CONTEXT: CompletionContext = CompletionContext {
1034    trigger_kind: lsp::CompletionTriggerKind::INVOKED,
1035    trigger_character: None,
1036};
1037
1038/// An LSP diagnostics associated with a certain language server.
1039#[derive(Clone, Debug, Default)]
1040pub enum LspPullDiagnostics {
1041    #[default]
1042    Default,
1043    Response {
1044        /// The id of the language server that produced diagnostics.
1045        server_id: LanguageServerId,
1046        /// URI of the resource,
1047        uri: lsp::Uri,
1048        /// The ID provided by the dynamic registration that produced diagnostics.
1049        registration_id: Option<SharedString>,
1050        /// The diagnostics produced by this language server.
1051        diagnostics: PulledDiagnostics,
1052    },
1053}
1054
1055#[derive(Clone, Debug)]
1056pub enum PulledDiagnostics {
1057    Unchanged {
1058        /// An ID the current pulled batch for this file.
1059        /// If given, can be used to query workspace diagnostics partially.
1060        result_id: SharedString,
1061    },
1062    Changed {
1063        result_id: Option<SharedString>,
1064        diagnostics: Vec<lsp::Diagnostic>,
1065    },
1066}
1067
1068/// Whether to disable all AI features in Zed.
1069///
1070/// Default: false
1071#[derive(Copy, Clone, Debug, RegisterSetting)]
1072pub struct DisableAiSettings {
1073    pub disable_ai: bool,
1074}
1075
1076impl settings::Settings for DisableAiSettings {
1077    fn from_settings(content: &settings::SettingsContent) -> Self {
1078        Self {
1079            disable_ai: content.disable_ai.unwrap().0,
1080        }
1081    }
1082}
1083
1084impl Project {
1085    pub fn init(client: &Arc<Client>, cx: &mut App) {
1086        connection_manager::init(client.clone(), cx);
1087
1088        let client: AnyProtoClient = client.clone().into();
1089        client.add_entity_message_handler(Self::handle_add_collaborator);
1090        client.add_entity_message_handler(Self::handle_update_project_collaborator);
1091        client.add_entity_message_handler(Self::handle_remove_collaborator);
1092        client.add_entity_message_handler(Self::handle_update_project);
1093        client.add_entity_message_handler(Self::handle_unshare_project);
1094        client.add_entity_request_handler(Self::handle_update_buffer);
1095        client.add_entity_message_handler(Self::handle_update_worktree);
1096        client.add_entity_request_handler(Self::handle_synchronize_buffers);
1097
1098        client.add_entity_request_handler(Self::handle_search_candidate_buffers);
1099        client.add_entity_request_handler(Self::handle_open_buffer_by_id);
1100        client.add_entity_request_handler(Self::handle_open_buffer_by_path);
1101        client.add_entity_request_handler(Self::handle_open_new_buffer);
1102        client.add_entity_message_handler(Self::handle_create_buffer_for_peer);
1103        client.add_entity_message_handler(Self::handle_toggle_lsp_logs);
1104        client.add_entity_message_handler(Self::handle_create_image_for_peer);
1105        client.add_entity_request_handler(Self::handle_find_search_candidates_chunk);
1106        client.add_entity_message_handler(Self::handle_find_search_candidates_cancel);
1107        client.add_entity_message_handler(Self::handle_create_file_for_peer);
1108
1109        WorktreeStore::init(&client);
1110        BufferStore::init(&client);
1111        LspStore::init(&client);
1112        GitStore::init(&client);
1113        SettingsObserver::init(&client);
1114        TaskStore::init(Some(&client));
1115        ToolchainStore::init(&client);
1116        DapStore::init(&client, cx);
1117        BreakpointStore::init(&client);
1118        context_server_store::init(cx);
1119    }
1120
1121    pub fn local(
1122        client: Arc<Client>,
1123        node: NodeRuntime,
1124        user_store: Entity<UserStore>,
1125        languages: Arc<LanguageRegistry>,
1126        fs: Arc<dyn Fs>,
1127        env: Option<HashMap<String, String>>,
1128        flags: LocalProjectFlags,
1129        cx: &mut App,
1130    ) -> Entity<Self> {
1131        cx.new(|cx: &mut Context<Self>| {
1132            let (tx, rx) = mpsc::unbounded();
1133            cx.spawn(async move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx).await)
1134                .detach();
1135            let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
1136            let worktree_store =
1137                cx.new(|cx| WorktreeStore::local(false, fs.clone(), WorktreeIdCounter::get(cx)));
1138            if flags.init_worktree_trust {
1139                trusted_worktrees::track_worktree_trust(
1140                    worktree_store.clone(),
1141                    None,
1142                    None,
1143                    None,
1144                    cx,
1145                );
1146            }
1147            cx.subscribe(&worktree_store, Self::on_worktree_store_event)
1148                .detach();
1149
1150            let weak_self = cx.weak_entity();
1151            let context_server_store = cx.new(|cx| {
1152                ContextServerStore::local(
1153                    worktree_store.clone(),
1154                    Some(weak_self.clone()),
1155                    false,
1156                    cx,
1157                )
1158            });
1159
1160            let environment = cx.new(|cx| {
1161                ProjectEnvironment::new(env, worktree_store.downgrade(), None, false, cx)
1162            });
1163            let manifest_tree = ManifestTree::new(worktree_store.clone(), cx);
1164            let toolchain_store = cx.new(|cx| {
1165                ToolchainStore::local(
1166                    languages.clone(),
1167                    worktree_store.clone(),
1168                    environment.clone(),
1169                    manifest_tree.clone(),
1170                    fs.clone(),
1171                    cx,
1172                )
1173            });
1174
1175            let buffer_store = cx.new(|cx| BufferStore::local(worktree_store.clone(), cx));
1176            cx.subscribe(&buffer_store, Self::on_buffer_store_event)
1177                .detach();
1178
1179            let breakpoint_store =
1180                cx.new(|_| BreakpointStore::local(worktree_store.clone(), buffer_store.clone()));
1181
1182            let dap_store = cx.new(|cx| {
1183                DapStore::new_local(
1184                    client.http_client(),
1185                    node.clone(),
1186                    fs.clone(),
1187                    environment.clone(),
1188                    toolchain_store.read(cx).as_language_toolchain_store(),
1189                    worktree_store.clone(),
1190                    breakpoint_store.clone(),
1191                    false,
1192                    cx,
1193                )
1194            });
1195            cx.subscribe(&dap_store, Self::on_dap_store_event).detach();
1196
1197            let image_store = cx.new(|cx| ImageStore::local(worktree_store.clone(), cx));
1198            cx.subscribe(&image_store, Self::on_image_store_event)
1199                .detach();
1200
1201            let prettier_store = cx.new(|cx| {
1202                PrettierStore::new(
1203                    node.clone(),
1204                    fs.clone(),
1205                    languages.clone(),
1206                    worktree_store.clone(),
1207                    cx,
1208                )
1209            });
1210
1211            let task_store = cx.new(|cx| {
1212                TaskStore::local(
1213                    buffer_store.downgrade(),
1214                    worktree_store.clone(),
1215                    toolchain_store.read(cx).as_language_toolchain_store(),
1216                    environment.clone(),
1217                    cx,
1218                )
1219            });
1220
1221            let settings_observer = cx.new(|cx| {
1222                SettingsObserver::new_local(
1223                    fs.clone(),
1224                    worktree_store.clone(),
1225                    task_store.clone(),
1226                    flags.watch_global_configs,
1227                    cx,
1228                )
1229            });
1230            cx.subscribe(&settings_observer, Self::on_settings_observer_event)
1231                .detach();
1232
1233            let lsp_store = cx.new(|cx| {
1234                LspStore::new_local(
1235                    buffer_store.clone(),
1236                    worktree_store.clone(),
1237                    prettier_store.clone(),
1238                    toolchain_store
1239                        .read(cx)
1240                        .as_local_store()
1241                        .expect("Toolchain store to be local")
1242                        .clone(),
1243                    environment.clone(),
1244                    manifest_tree,
1245                    languages.clone(),
1246                    client.http_client(),
1247                    fs.clone(),
1248                    cx,
1249                )
1250            });
1251
1252            let git_store = cx.new(|cx| {
1253                GitStore::local(
1254                    &worktree_store,
1255                    buffer_store.clone(),
1256                    environment.clone(),
1257                    fs.clone(),
1258                    cx,
1259                )
1260            });
1261
1262            let agent_server_store = cx.new(|cx| {
1263                AgentServerStore::local(
1264                    node.clone(),
1265                    fs.clone(),
1266                    environment.clone(),
1267                    client.http_client(),
1268                    cx,
1269                )
1270            });
1271
1272            cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
1273
1274            Self {
1275                buffer_ordered_messages_tx: tx,
1276                collaborators: Default::default(),
1277                worktree_store,
1278                buffer_store,
1279                image_store,
1280                lsp_store,
1281                context_server_store,
1282                join_project_response_message_id: 0,
1283                client_state: ProjectClientState::Local,
1284                git_store,
1285                client_subscriptions: Vec::new(),
1286                _subscriptions: vec![cx.on_release(Self::release)],
1287                active_entry: None,
1288                snippets,
1289                languages,
1290                collab_client: client,
1291                task_store,
1292                user_store,
1293                settings_observer,
1294                fs,
1295                remote_client: None,
1296                breakpoint_store,
1297                dap_store,
1298                agent_server_store,
1299
1300                buffers_needing_diff: Default::default(),
1301                git_diff_debouncer: DebouncedDelay::new(),
1302                terminals: Terminals {
1303                    local_handles: Vec::new(),
1304                },
1305                node: Some(node),
1306                search_history: Self::new_search_history(),
1307                environment,
1308                remotely_created_models: Default::default(),
1309
1310                search_included_history: Self::new_search_history(),
1311                search_excluded_history: Self::new_search_history(),
1312
1313                toolchain_store: Some(toolchain_store),
1314
1315                agent_location: None,
1316                downloading_files: Default::default(),
1317            }
1318        })
1319    }
1320
1321    pub fn remote(
1322        remote: Entity<RemoteClient>,
1323        client: Arc<Client>,
1324        node: NodeRuntime,
1325        user_store: Entity<UserStore>,
1326        languages: Arc<LanguageRegistry>,
1327        fs: Arc<dyn Fs>,
1328        init_worktree_trust: bool,
1329        cx: &mut App,
1330    ) -> Entity<Self> {
1331        cx.new(|cx: &mut Context<Self>| {
1332            let (tx, rx) = mpsc::unbounded();
1333            cx.spawn(async move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx).await)
1334                .detach();
1335            let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
1336
1337            let (remote_proto, path_style, connection_options) =
1338                remote.read_with(cx, |remote, _| {
1339                    (
1340                        remote.proto_client(),
1341                        remote.path_style(),
1342                        remote.connection_options(),
1343                    )
1344                });
1345            let worktree_store = cx.new(|cx| {
1346                WorktreeStore::remote(
1347                    false,
1348                    remote_proto.clone(),
1349                    REMOTE_SERVER_PROJECT_ID,
1350                    path_style,
1351                    WorktreeIdCounter::get(cx),
1352                )
1353            });
1354
1355            cx.subscribe(&worktree_store, Self::on_worktree_store_event)
1356                .detach();
1357            if init_worktree_trust {
1358                trusted_worktrees::track_worktree_trust(
1359                    worktree_store.clone(),
1360                    Some(RemoteHostLocation::from(connection_options)),
1361                    None,
1362                    Some((remote_proto.clone(), ProjectId(REMOTE_SERVER_PROJECT_ID))),
1363                    cx,
1364                );
1365            }
1366
1367            let weak_self = cx.weak_entity();
1368
1369            let buffer_store = cx.new(|cx| {
1370                BufferStore::remote(
1371                    worktree_store.clone(),
1372                    remote.read(cx).proto_client(),
1373                    REMOTE_SERVER_PROJECT_ID,
1374                    cx,
1375                )
1376            });
1377            let image_store = cx.new(|cx| {
1378                ImageStore::remote(
1379                    worktree_store.clone(),
1380                    remote.read(cx).proto_client(),
1381                    REMOTE_SERVER_PROJECT_ID,
1382                    cx,
1383                )
1384            });
1385            cx.subscribe(&buffer_store, Self::on_buffer_store_event)
1386                .detach();
1387            let toolchain_store = cx.new(|cx| {
1388                ToolchainStore::remote(
1389                    REMOTE_SERVER_PROJECT_ID,
1390                    worktree_store.clone(),
1391                    remote.read(cx).proto_client(),
1392                    cx,
1393                )
1394            });
1395
1396            let task_store = cx.new(|cx| {
1397                TaskStore::remote(
1398                    buffer_store.downgrade(),
1399                    worktree_store.clone(),
1400                    toolchain_store.read(cx).as_language_toolchain_store(),
1401                    remote.read(cx).proto_client(),
1402                    REMOTE_SERVER_PROJECT_ID,
1403                    cx,
1404                )
1405            });
1406
1407            let settings_observer = cx.new(|cx| {
1408                SettingsObserver::new_remote(
1409                    fs.clone(),
1410                    worktree_store.clone(),
1411                    task_store.clone(),
1412                    Some(remote_proto.clone()),
1413                    false,
1414                    cx,
1415                )
1416            });
1417            cx.subscribe(&settings_observer, Self::on_settings_observer_event)
1418                .detach();
1419
1420            let context_server_store = cx.new(|cx| {
1421                ContextServerStore::remote(
1422                    rpc::proto::REMOTE_SERVER_PROJECT_ID,
1423                    remote.clone(),
1424                    worktree_store.clone(),
1425                    Some(weak_self.clone()),
1426                    cx,
1427                )
1428            });
1429
1430            let environment = cx.new(|cx| {
1431                ProjectEnvironment::new(
1432                    None,
1433                    worktree_store.downgrade(),
1434                    Some(remote.downgrade()),
1435                    false,
1436                    cx,
1437                )
1438            });
1439
1440            let lsp_store = cx.new(|cx| {
1441                LspStore::new_remote(
1442                    buffer_store.clone(),
1443                    worktree_store.clone(),
1444                    languages.clone(),
1445                    remote_proto.clone(),
1446                    REMOTE_SERVER_PROJECT_ID,
1447                    cx,
1448                )
1449            });
1450            cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
1451
1452            let breakpoint_store = cx.new(|_| {
1453                BreakpointStore::remote(
1454                    REMOTE_SERVER_PROJECT_ID,
1455                    remote_proto.clone(),
1456                    buffer_store.clone(),
1457                    worktree_store.clone(),
1458                )
1459            });
1460
1461            let dap_store = cx.new(|cx| {
1462                DapStore::new_remote(
1463                    REMOTE_SERVER_PROJECT_ID,
1464                    remote.clone(),
1465                    breakpoint_store.clone(),
1466                    worktree_store.clone(),
1467                    node.clone(),
1468                    client.http_client(),
1469                    fs.clone(),
1470                    cx,
1471                )
1472            });
1473
1474            let git_store = cx.new(|cx| {
1475                GitStore::remote(
1476                    &worktree_store,
1477                    buffer_store.clone(),
1478                    remote_proto.clone(),
1479                    REMOTE_SERVER_PROJECT_ID,
1480                    cx,
1481                )
1482            });
1483
1484            let agent_server_store =
1485                cx.new(|_| AgentServerStore::remote(REMOTE_SERVER_PROJECT_ID, remote.clone()));
1486
1487            cx.subscribe(&remote, Self::on_remote_client_event).detach();
1488
1489            let this = Self {
1490                buffer_ordered_messages_tx: tx,
1491                collaborators: Default::default(),
1492                worktree_store,
1493                buffer_store,
1494                image_store,
1495                lsp_store,
1496                context_server_store,
1497                breakpoint_store,
1498                dap_store,
1499                join_project_response_message_id: 0,
1500                client_state: ProjectClientState::Local,
1501                git_store,
1502                agent_server_store,
1503                client_subscriptions: Vec::new(),
1504                _subscriptions: vec![
1505                    cx.on_release(Self::release),
1506                    cx.on_app_quit(|this, cx| {
1507                        let shutdown = this.remote_client.take().and_then(|client| {
1508                            client.update(cx, |client, cx| {
1509                                client.shutdown_processes(
1510                                    Some(proto::ShutdownRemoteServer {}),
1511                                    cx.background_executor().clone(),
1512                                )
1513                            })
1514                        });
1515
1516                        cx.background_executor().spawn(async move {
1517                            if let Some(shutdown) = shutdown {
1518                                shutdown.await;
1519                            }
1520                        })
1521                    }),
1522                ],
1523                active_entry: None,
1524                snippets,
1525                languages,
1526                collab_client: client,
1527                task_store,
1528                user_store,
1529                settings_observer,
1530                fs,
1531                remote_client: Some(remote.clone()),
1532                buffers_needing_diff: Default::default(),
1533                git_diff_debouncer: DebouncedDelay::new(),
1534                terminals: Terminals {
1535                    local_handles: Vec::new(),
1536                },
1537                node: Some(node),
1538                search_history: Self::new_search_history(),
1539                environment,
1540                remotely_created_models: Default::default(),
1541
1542                search_included_history: Self::new_search_history(),
1543                search_excluded_history: Self::new_search_history(),
1544
1545                toolchain_store: Some(toolchain_store),
1546                agent_location: None,
1547                downloading_files: Default::default(),
1548            };
1549
1550            // remote server -> local machine handlers
1551            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &cx.entity());
1552            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.buffer_store);
1553            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.worktree_store);
1554            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.lsp_store);
1555            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.dap_store);
1556            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.breakpoint_store);
1557            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.settings_observer);
1558            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.git_store);
1559            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.agent_server_store);
1560
1561            remote_proto.add_entity_message_handler(Self::handle_create_buffer_for_peer);
1562            remote_proto.add_entity_message_handler(Self::handle_create_image_for_peer);
1563            remote_proto.add_entity_message_handler(Self::handle_create_file_for_peer);
1564            remote_proto.add_entity_message_handler(Self::handle_update_worktree);
1565            remote_proto.add_entity_message_handler(Self::handle_update_project);
1566            remote_proto.add_entity_message_handler(Self::handle_toast);
1567            remote_proto.add_entity_request_handler(Self::handle_language_server_prompt_request);
1568            remote_proto.add_entity_message_handler(Self::handle_hide_toast);
1569            remote_proto.add_entity_request_handler(Self::handle_update_buffer_from_remote_server);
1570            remote_proto.add_entity_request_handler(Self::handle_trust_worktrees);
1571            remote_proto.add_entity_request_handler(Self::handle_restrict_worktrees);
1572            remote_proto.add_entity_request_handler(Self::handle_find_search_candidates_chunk);
1573
1574            remote_proto.add_entity_message_handler(Self::handle_find_search_candidates_cancel);
1575            BufferStore::init(&remote_proto);
1576            WorktreeStore::init_remote(&remote_proto);
1577            LspStore::init(&remote_proto);
1578            SettingsObserver::init(&remote_proto);
1579            TaskStore::init(Some(&remote_proto));
1580            ToolchainStore::init(&remote_proto);
1581            DapStore::init(&remote_proto, cx);
1582            BreakpointStore::init(&remote_proto);
1583            GitStore::init(&remote_proto);
1584            AgentServerStore::init_remote(&remote_proto);
1585
1586            this
1587        })
1588    }
1589
1590    pub async fn in_room(
1591        remote_id: u64,
1592        client: Arc<Client>,
1593        user_store: Entity<UserStore>,
1594        languages: Arc<LanguageRegistry>,
1595        fs: Arc<dyn Fs>,
1596        cx: AsyncApp,
1597    ) -> Result<Entity<Self>> {
1598        client.connect(true, &cx).await.into_response()?;
1599
1600        let subscriptions = [
1601            EntitySubscription::Project(client.subscribe_to_entity::<Self>(remote_id)?),
1602            EntitySubscription::BufferStore(client.subscribe_to_entity::<BufferStore>(remote_id)?),
1603            EntitySubscription::GitStore(client.subscribe_to_entity::<GitStore>(remote_id)?),
1604            EntitySubscription::WorktreeStore(
1605                client.subscribe_to_entity::<WorktreeStore>(remote_id)?,
1606            ),
1607            EntitySubscription::LspStore(client.subscribe_to_entity::<LspStore>(remote_id)?),
1608            EntitySubscription::SettingsObserver(
1609                client.subscribe_to_entity::<SettingsObserver>(remote_id)?,
1610            ),
1611            EntitySubscription::DapStore(client.subscribe_to_entity::<DapStore>(remote_id)?),
1612            EntitySubscription::BreakpointStore(
1613                client.subscribe_to_entity::<BreakpointStore>(remote_id)?,
1614            ),
1615        ];
1616        let committer = get_git_committer(&cx).await;
1617        let response = client
1618            .request_envelope(proto::JoinProject {
1619                project_id: remote_id,
1620                committer_email: committer.email,
1621                committer_name: committer.name,
1622            })
1623            .await?;
1624        Self::from_join_project_response(
1625            response,
1626            subscriptions,
1627            client,
1628            false,
1629            user_store,
1630            languages,
1631            fs,
1632            cx,
1633        )
1634        .await
1635    }
1636
1637    async fn from_join_project_response(
1638        response: TypedEnvelope<proto::JoinProjectResponse>,
1639        subscriptions: [EntitySubscription; 8],
1640        client: Arc<Client>,
1641        run_tasks: bool,
1642        user_store: Entity<UserStore>,
1643        languages: Arc<LanguageRegistry>,
1644        fs: Arc<dyn Fs>,
1645        mut cx: AsyncApp,
1646    ) -> Result<Entity<Self>> {
1647        let remote_id = response.payload.project_id;
1648        let role = response.payload.role();
1649
1650        let path_style = if response.payload.windows_paths {
1651            PathStyle::Windows
1652        } else {
1653            PathStyle::Posix
1654        };
1655
1656        let worktree_store = cx.new(|cx| {
1657            WorktreeStore::remote(
1658                true,
1659                client.clone().into(),
1660                response.payload.project_id,
1661                path_style,
1662                WorktreeIdCounter::get(cx),
1663            )
1664        });
1665        let buffer_store = cx.new(|cx| {
1666            BufferStore::remote(worktree_store.clone(), client.clone().into(), remote_id, cx)
1667        });
1668        let image_store = cx.new(|cx| {
1669            ImageStore::remote(worktree_store.clone(), client.clone().into(), remote_id, cx)
1670        });
1671
1672        let environment =
1673            cx.new(|cx| ProjectEnvironment::new(None, worktree_store.downgrade(), None, true, cx));
1674        let breakpoint_store = cx.new(|_| {
1675            BreakpointStore::remote(
1676                remote_id,
1677                client.clone().into(),
1678                buffer_store.clone(),
1679                worktree_store.clone(),
1680            )
1681        });
1682        let dap_store = cx.new(|cx| {
1683            DapStore::new_collab(
1684                remote_id,
1685                client.clone().into(),
1686                breakpoint_store.clone(),
1687                worktree_store.clone(),
1688                fs.clone(),
1689                cx,
1690            )
1691        });
1692
1693        let lsp_store = cx.new(|cx| {
1694            LspStore::new_remote(
1695                buffer_store.clone(),
1696                worktree_store.clone(),
1697                languages.clone(),
1698                client.clone().into(),
1699                remote_id,
1700                cx,
1701            )
1702        });
1703
1704        let task_store = cx.new(|cx| {
1705            if run_tasks {
1706                TaskStore::remote(
1707                    buffer_store.downgrade(),
1708                    worktree_store.clone(),
1709                    Arc::new(EmptyToolchainStore),
1710                    client.clone().into(),
1711                    remote_id,
1712                    cx,
1713                )
1714            } else {
1715                TaskStore::Noop
1716            }
1717        });
1718
1719        let settings_observer = cx.new(|cx| {
1720            SettingsObserver::new_remote(
1721                fs.clone(),
1722                worktree_store.clone(),
1723                task_store.clone(),
1724                None,
1725                true,
1726                cx,
1727            )
1728        });
1729
1730        let git_store = cx.new(|cx| {
1731            GitStore::remote(
1732                // In this remote case we pass None for the environment
1733                &worktree_store,
1734                buffer_store.clone(),
1735                client.clone().into(),
1736                remote_id,
1737                cx,
1738            )
1739        });
1740
1741        let agent_server_store = cx.new(|_cx| AgentServerStore::collab());
1742        let replica_id = ReplicaId::new(response.payload.replica_id as u16);
1743
1744        let project = cx.new(|cx| {
1745            let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
1746
1747            let weak_self = cx.weak_entity();
1748            let context_server_store = cx.new(|cx| {
1749                ContextServerStore::local(worktree_store.clone(), Some(weak_self), false, cx)
1750            });
1751
1752            let mut worktrees = Vec::new();
1753            for worktree in response.payload.worktrees {
1754                let worktree = Worktree::remote(
1755                    remote_id,
1756                    replica_id,
1757                    worktree,
1758                    client.clone().into(),
1759                    path_style,
1760                    cx,
1761                );
1762                worktrees.push(worktree);
1763            }
1764
1765            let (tx, rx) = mpsc::unbounded();
1766            cx.spawn(async move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx).await)
1767                .detach();
1768
1769            cx.subscribe(&worktree_store, Self::on_worktree_store_event)
1770                .detach();
1771
1772            cx.subscribe(&buffer_store, Self::on_buffer_store_event)
1773                .detach();
1774            cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
1775            cx.subscribe(&settings_observer, Self::on_settings_observer_event)
1776                .detach();
1777
1778            cx.subscribe(&dap_store, Self::on_dap_store_event).detach();
1779
1780            let mut project = Self {
1781                buffer_ordered_messages_tx: tx,
1782                buffer_store: buffer_store.clone(),
1783                image_store,
1784                worktree_store: worktree_store.clone(),
1785                lsp_store: lsp_store.clone(),
1786                context_server_store,
1787                active_entry: None,
1788                collaborators: Default::default(),
1789                join_project_response_message_id: response.message_id,
1790                languages,
1791                user_store: user_store.clone(),
1792                task_store,
1793                snippets,
1794                fs,
1795                remote_client: None,
1796                settings_observer: settings_observer.clone(),
1797                client_subscriptions: Default::default(),
1798                _subscriptions: vec![cx.on_release(Self::release)],
1799                collab_client: client.clone(),
1800                client_state: ProjectClientState::Remote {
1801                    sharing_has_stopped: false,
1802                    capability: Capability::ReadWrite,
1803                    remote_id,
1804                    replica_id,
1805                },
1806                breakpoint_store: breakpoint_store.clone(),
1807                dap_store: dap_store.clone(),
1808                git_store: git_store.clone(),
1809                agent_server_store,
1810                buffers_needing_diff: Default::default(),
1811                git_diff_debouncer: DebouncedDelay::new(),
1812                terminals: Terminals {
1813                    local_handles: Vec::new(),
1814                },
1815                node: None,
1816                search_history: Self::new_search_history(),
1817                search_included_history: Self::new_search_history(),
1818                search_excluded_history: Self::new_search_history(),
1819                environment,
1820                remotely_created_models: Arc::new(Mutex::new(RemotelyCreatedModels::default())),
1821                toolchain_store: None,
1822                agent_location: None,
1823                downloading_files: Default::default(),
1824            };
1825            project.set_role(role, cx);
1826            for worktree in worktrees {
1827                project.add_worktree(&worktree, cx);
1828            }
1829            project
1830        });
1831
1832        let weak_project = project.downgrade();
1833        lsp_store.update(&mut cx, |lsp_store, cx| {
1834            lsp_store.set_language_server_statuses_from_proto(
1835                weak_project,
1836                response.payload.language_servers,
1837                response.payload.language_server_capabilities,
1838                cx,
1839            );
1840        });
1841
1842        let subscriptions = subscriptions
1843            .into_iter()
1844            .map(|s| match s {
1845                EntitySubscription::BufferStore(subscription) => {
1846                    subscription.set_entity(&buffer_store, &cx)
1847                }
1848                EntitySubscription::WorktreeStore(subscription) => {
1849                    subscription.set_entity(&worktree_store, &cx)
1850                }
1851                EntitySubscription::GitStore(subscription) => {
1852                    subscription.set_entity(&git_store, &cx)
1853                }
1854                EntitySubscription::SettingsObserver(subscription) => {
1855                    subscription.set_entity(&settings_observer, &cx)
1856                }
1857                EntitySubscription::Project(subscription) => subscription.set_entity(&project, &cx),
1858                EntitySubscription::LspStore(subscription) => {
1859                    subscription.set_entity(&lsp_store, &cx)
1860                }
1861                EntitySubscription::DapStore(subscription) => {
1862                    subscription.set_entity(&dap_store, &cx)
1863                }
1864                EntitySubscription::BreakpointStore(subscription) => {
1865                    subscription.set_entity(&breakpoint_store, &cx)
1866                }
1867            })
1868            .collect::<Vec<_>>();
1869
1870        let user_ids = response
1871            .payload
1872            .collaborators
1873            .iter()
1874            .map(|peer| peer.user_id)
1875            .collect();
1876        user_store
1877            .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))
1878            .await?;
1879
1880        project.update(&mut cx, |this, cx| {
1881            this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
1882            this.client_subscriptions.extend(subscriptions);
1883            anyhow::Ok(())
1884        })?;
1885
1886        Ok(project)
1887    }
1888
1889    fn new_search_history() -> SearchHistory {
1890        SearchHistory::new(
1891            Some(MAX_PROJECT_SEARCH_HISTORY_SIZE),
1892            search_history::QueryInsertionBehavior::AlwaysInsert,
1893        )
1894    }
1895
1896    fn release(&mut self, cx: &mut App) {
1897        if let Some(client) = self.remote_client.take() {
1898            let shutdown = client.update(cx, |client, cx| {
1899                client.shutdown_processes(
1900                    Some(proto::ShutdownRemoteServer {}),
1901                    cx.background_executor().clone(),
1902                )
1903            });
1904
1905            cx.background_spawn(async move {
1906                if let Some(shutdown) = shutdown {
1907                    shutdown.await;
1908                }
1909            })
1910            .detach()
1911        }
1912
1913        match &self.client_state {
1914            ProjectClientState::Local => {}
1915            ProjectClientState::Shared { .. } => {
1916                let _ = self.unshare_internal(cx);
1917            }
1918            ProjectClientState::Remote { remote_id, .. } => {
1919                let _ = self.collab_client.send(proto::LeaveProject {
1920                    project_id: *remote_id,
1921                });
1922                self.disconnected_from_host_internal(cx);
1923            }
1924        }
1925    }
1926
1927    #[cfg(feature = "test-support")]
1928    pub async fn example(
1929        root_paths: impl IntoIterator<Item = &Path>,
1930        cx: &mut AsyncApp,
1931    ) -> Entity<Project> {
1932        use clock::FakeSystemClock;
1933
1934        let fs = Arc::new(RealFs::new(None, cx.background_executor().clone()));
1935        let languages = LanguageRegistry::test(cx.background_executor().clone());
1936        let clock = Arc::new(FakeSystemClock::new());
1937        let http_client = http_client::FakeHttpClient::with_404_response();
1938        let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
1939        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1940        let project = cx.update(|cx| {
1941            Project::local(
1942                client,
1943                node_runtime::NodeRuntime::unavailable(),
1944                user_store,
1945                Arc::new(languages),
1946                fs,
1947                None,
1948                LocalProjectFlags {
1949                    init_worktree_trust: false,
1950                    ..Default::default()
1951                },
1952                cx,
1953            )
1954        });
1955        for path in root_paths {
1956            let (tree, _): (Entity<Worktree>, _) = project
1957                .update(cx, |project, cx| {
1958                    project.find_or_create_worktree(path, true, cx)
1959                })
1960                .await
1961                .unwrap();
1962            tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1963                .await;
1964        }
1965        project
1966    }
1967
1968    #[cfg(feature = "test-support")]
1969    pub async fn test(
1970        fs: Arc<dyn Fs>,
1971        root_paths: impl IntoIterator<Item = &Path>,
1972        cx: &mut gpui::TestAppContext,
1973    ) -> Entity<Project> {
1974        Self::test_project(fs, root_paths, false, cx).await
1975    }
1976
1977    #[cfg(feature = "test-support")]
1978    pub async fn test_with_worktree_trust(
1979        fs: Arc<dyn Fs>,
1980        root_paths: impl IntoIterator<Item = &Path>,
1981        cx: &mut gpui::TestAppContext,
1982    ) -> Entity<Project> {
1983        Self::test_project(fs, root_paths, true, cx).await
1984    }
1985
1986    #[cfg(feature = "test-support")]
1987    async fn test_project(
1988        fs: Arc<dyn Fs>,
1989        root_paths: impl IntoIterator<Item = &Path>,
1990        init_worktree_trust: bool,
1991        cx: &mut gpui::TestAppContext,
1992    ) -> Entity<Project> {
1993        use clock::FakeSystemClock;
1994
1995        let languages = LanguageRegistry::test(cx.executor());
1996        let clock = Arc::new(FakeSystemClock::new());
1997        let http_client = http_client::FakeHttpClient::with_404_response();
1998        let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
1999        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
2000        let project = cx.update(|cx| {
2001            Project::local(
2002                client,
2003                node_runtime::NodeRuntime::unavailable(),
2004                user_store,
2005                Arc::new(languages),
2006                fs,
2007                None,
2008                LocalProjectFlags {
2009                    init_worktree_trust,
2010                    ..Default::default()
2011                },
2012                cx,
2013            )
2014        });
2015        for path in root_paths {
2016            let (tree, _) = project
2017                .update(cx, |project, cx| {
2018                    project.find_or_create_worktree(path, true, cx)
2019                })
2020                .await
2021                .unwrap();
2022
2023            tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
2024                .await;
2025        }
2026        project
2027    }
2028
2029    #[inline]
2030    pub fn dap_store(&self) -> Entity<DapStore> {
2031        self.dap_store.clone()
2032    }
2033
2034    #[inline]
2035    pub fn breakpoint_store(&self) -> Entity<BreakpointStore> {
2036        self.breakpoint_store.clone()
2037    }
2038
2039    pub fn active_debug_session(&self, cx: &App) -> Option<(Entity<Session>, ActiveStackFrame)> {
2040        let active_position = self.breakpoint_store.read(cx).active_position()?;
2041        let session = self
2042            .dap_store
2043            .read(cx)
2044            .session_by_id(active_position.session_id)?;
2045        Some((session, active_position.clone()))
2046    }
2047
2048    #[inline]
2049    pub fn lsp_store(&self) -> Entity<LspStore> {
2050        self.lsp_store.clone()
2051    }
2052
2053    #[inline]
2054    pub fn worktree_store(&self) -> Entity<WorktreeStore> {
2055        self.worktree_store.clone()
2056    }
2057
2058    #[inline]
2059    pub fn context_server_store(&self) -> Entity<ContextServerStore> {
2060        self.context_server_store.clone()
2061    }
2062
2063    #[inline]
2064    pub fn buffer_for_id(&self, remote_id: BufferId, cx: &App) -> Option<Entity<Buffer>> {
2065        self.buffer_store.read(cx).get(remote_id)
2066    }
2067
2068    #[inline]
2069    pub fn languages(&self) -> &Arc<LanguageRegistry> {
2070        &self.languages
2071    }
2072
2073    #[inline]
2074    pub fn client(&self) -> Arc<Client> {
2075        self.collab_client.clone()
2076    }
2077
2078    #[inline]
2079    pub fn remote_client(&self) -> Option<Entity<RemoteClient>> {
2080        self.remote_client.clone()
2081    }
2082
2083    #[inline]
2084    pub fn user_store(&self) -> Entity<UserStore> {
2085        self.user_store.clone()
2086    }
2087
2088    #[inline]
2089    pub fn node_runtime(&self) -> Option<&NodeRuntime> {
2090        self.node.as_ref()
2091    }
2092
2093    #[inline]
2094    pub fn opened_buffers(&self, cx: &App) -> Vec<Entity<Buffer>> {
2095        self.buffer_store.read(cx).buffers().collect()
2096    }
2097
2098    #[inline]
2099    pub fn environment(&self) -> &Entity<ProjectEnvironment> {
2100        &self.environment
2101    }
2102
2103    #[inline]
2104    pub fn cli_environment(&self, cx: &App) -> Option<HashMap<String, String>> {
2105        self.environment.read(cx).get_cli_environment()
2106    }
2107
2108    #[inline]
2109    pub fn peek_environment_error<'a>(&'a self, cx: &'a App) -> Option<&'a String> {
2110        self.environment.read(cx).peek_environment_error()
2111    }
2112
2113    #[inline]
2114    pub fn pop_environment_error(&mut self, cx: &mut Context<Self>) {
2115        self.environment.update(cx, |environment, _| {
2116            environment.pop_environment_error();
2117        });
2118    }
2119
2120    #[cfg(feature = "test-support")]
2121    #[inline]
2122    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &App) -> bool {
2123        self.buffer_store
2124            .read(cx)
2125            .get_by_path(&path.into())
2126            .is_some()
2127    }
2128
2129    #[inline]
2130    pub fn fs(&self) -> &Arc<dyn Fs> {
2131        &self.fs
2132    }
2133
2134    #[inline]
2135    pub fn remote_id(&self) -> Option<u64> {
2136        match self.client_state {
2137            ProjectClientState::Local => None,
2138            ProjectClientState::Shared { remote_id, .. }
2139            | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
2140        }
2141    }
2142
2143    #[inline]
2144    pub fn supports_terminal(&self, _cx: &App) -> bool {
2145        if self.is_local() {
2146            return true;
2147        }
2148        if self.is_via_remote_server() {
2149            return true;
2150        }
2151
2152        false
2153    }
2154
2155    #[inline]
2156    pub fn remote_connection_state(&self, cx: &App) -> Option<remote::ConnectionState> {
2157        self.remote_client
2158            .as_ref()
2159            .map(|remote| remote.read(cx).connection_state())
2160    }
2161
2162    #[inline]
2163    pub fn remote_connection_options(&self, cx: &App) -> Option<RemoteConnectionOptions> {
2164        self.remote_client
2165            .as_ref()
2166            .map(|remote| remote.read(cx).connection_options())
2167    }
2168
2169    /// Reveals the given path in the system file manager.
2170    ///
2171    /// On Windows with a WSL remote connection, this converts the POSIX path
2172    /// to a Windows UNC path before revealing.
2173    pub fn reveal_path(&self, path: &Path, cx: &mut Context<Self>) {
2174        #[cfg(target_os = "windows")]
2175        if let Some(RemoteConnectionOptions::Wsl(wsl_options)) = self.remote_connection_options(cx)
2176        {
2177            let path = path.to_path_buf();
2178            cx.spawn(async move |_, cx| {
2179                wsl_path_to_windows_path(&wsl_options, &path)
2180                    .await
2181                    .map(|windows_path| cx.update(|cx| cx.reveal_path(&windows_path)))
2182            })
2183            .detach_and_log_err(cx);
2184            return;
2185        }
2186
2187        cx.reveal_path(path);
2188    }
2189
2190    #[inline]
2191    pub fn replica_id(&self) -> ReplicaId {
2192        match self.client_state {
2193            ProjectClientState::Remote { replica_id, .. } => replica_id,
2194            _ => {
2195                if self.remote_client.is_some() {
2196                    ReplicaId::REMOTE_SERVER
2197                } else {
2198                    ReplicaId::LOCAL
2199                }
2200            }
2201        }
2202    }
2203
2204    #[inline]
2205    pub fn task_store(&self) -> &Entity<TaskStore> {
2206        &self.task_store
2207    }
2208
2209    #[inline]
2210    pub fn snippets(&self) -> &Entity<SnippetProvider> {
2211        &self.snippets
2212    }
2213
2214    #[inline]
2215    pub fn search_history(&self, kind: SearchInputKind) -> &SearchHistory {
2216        match kind {
2217            SearchInputKind::Query => &self.search_history,
2218            SearchInputKind::Include => &self.search_included_history,
2219            SearchInputKind::Exclude => &self.search_excluded_history,
2220        }
2221    }
2222
2223    #[inline]
2224    pub fn search_history_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistory {
2225        match kind {
2226            SearchInputKind::Query => &mut self.search_history,
2227            SearchInputKind::Include => &mut self.search_included_history,
2228            SearchInputKind::Exclude => &mut self.search_excluded_history,
2229        }
2230    }
2231
2232    #[inline]
2233    pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
2234        &self.collaborators
2235    }
2236
2237    #[inline]
2238    pub fn host(&self) -> Option<&Collaborator> {
2239        self.collaborators.values().find(|c| c.is_host)
2240    }
2241
2242    #[inline]
2243    pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool, cx: &mut App) {
2244        self.worktree_store.update(cx, |store, _| {
2245            store.set_worktrees_reordered(worktrees_reordered);
2246        });
2247    }
2248
2249    /// Collect all worktrees, including ones that don't appear in the project panel
2250    #[inline]
2251    pub fn worktrees<'a>(
2252        &self,
2253        cx: &'a App,
2254    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
2255        self.worktree_store.read(cx).worktrees()
2256    }
2257
2258    /// Collect all user-visible worktrees, the ones that appear in the project panel.
2259    #[inline]
2260    pub fn visible_worktrees<'a>(
2261        &'a self,
2262        cx: &'a App,
2263    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
2264        self.worktree_store.read(cx).visible_worktrees(cx)
2265    }
2266
2267    #[inline]
2268    pub fn worktree_for_root_name(&self, root_name: &str, cx: &App) -> Option<Entity<Worktree>> {
2269        self.visible_worktrees(cx)
2270            .find(|tree| tree.read(cx).root_name() == root_name)
2271    }
2272
2273    #[inline]
2274    pub fn worktree_root_names<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = &'a str> {
2275        self.visible_worktrees(cx)
2276            .map(|tree| tree.read(cx).root_name().as_unix_str())
2277    }
2278
2279    #[inline]
2280    pub fn worktree_for_id(&self, id: WorktreeId, cx: &App) -> Option<Entity<Worktree>> {
2281        self.worktree_store.read(cx).worktree_for_id(id, cx)
2282    }
2283
2284    pub fn worktree_for_entry(
2285        &self,
2286        entry_id: ProjectEntryId,
2287        cx: &App,
2288    ) -> Option<Entity<Worktree>> {
2289        self.worktree_store
2290            .read(cx)
2291            .worktree_for_entry(entry_id, cx)
2292    }
2293
2294    #[inline]
2295    pub fn worktree_id_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<WorktreeId> {
2296        self.worktree_for_entry(entry_id, cx)
2297            .map(|worktree| worktree.read(cx).id())
2298    }
2299
2300    /// Checks if the entry is the root of a worktree.
2301    #[inline]
2302    pub fn entry_is_worktree_root(&self, entry_id: ProjectEntryId, cx: &App) -> bool {
2303        self.worktree_for_entry(entry_id, cx)
2304            .map(|worktree| {
2305                worktree
2306                    .read(cx)
2307                    .root_entry()
2308                    .is_some_and(|e| e.id == entry_id)
2309            })
2310            .unwrap_or(false)
2311    }
2312
2313    #[inline]
2314    pub fn project_path_git_status(
2315        &self,
2316        project_path: &ProjectPath,
2317        cx: &App,
2318    ) -> Option<FileStatus> {
2319        self.git_store
2320            .read(cx)
2321            .project_path_git_status(project_path, cx)
2322    }
2323
2324    #[inline]
2325    pub fn visibility_for_paths(
2326        &self,
2327        paths: &[PathBuf],
2328        metadatas: &[Metadata],
2329        exclude_sub_dirs: bool,
2330        cx: &App,
2331    ) -> Option<bool> {
2332        paths
2333            .iter()
2334            .zip(metadatas)
2335            .map(|(path, metadata)| self.visibility_for_path(path, metadata, exclude_sub_dirs, cx))
2336            .max()
2337            .flatten()
2338    }
2339
2340    pub fn visibility_for_path(
2341        &self,
2342        path: &Path,
2343        metadata: &Metadata,
2344        exclude_sub_dirs: bool,
2345        cx: &App,
2346    ) -> Option<bool> {
2347        let path = SanitizedPath::new(path).as_path();
2348        self.worktrees(cx)
2349            .filter_map(|worktree| {
2350                let worktree = worktree.read(cx);
2351                let abs_path = worktree.as_local()?.abs_path();
2352                let contains = path == abs_path.as_ref()
2353                    || (path.starts_with(abs_path) && (!exclude_sub_dirs || !metadata.is_dir));
2354                contains.then(|| worktree.is_visible())
2355            })
2356            .max()
2357    }
2358
2359    pub fn create_entry(
2360        &mut self,
2361        project_path: impl Into<ProjectPath>,
2362        is_directory: bool,
2363        cx: &mut Context<Self>,
2364    ) -> Task<Result<CreatedEntry>> {
2365        let project_path = project_path.into();
2366        let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
2367            return Task::ready(Err(anyhow!(format!(
2368                "No worktree for path {project_path:?}"
2369            ))));
2370        };
2371        worktree.update(cx, |worktree, cx| {
2372            worktree.create_entry(project_path.path, is_directory, None, cx)
2373        })
2374    }
2375
2376    #[inline]
2377    pub fn copy_entry(
2378        &mut self,
2379        entry_id: ProjectEntryId,
2380        new_project_path: ProjectPath,
2381        cx: &mut Context<Self>,
2382    ) -> Task<Result<Option<Entry>>> {
2383        self.worktree_store.update(cx, |worktree_store, cx| {
2384            worktree_store.copy_entry(entry_id, new_project_path, cx)
2385        })
2386    }
2387
2388    /// Renames the project entry with given `entry_id`.
2389    ///
2390    /// `new_path` is a relative path to worktree root.
2391    /// If root entry is renamed then its new root name is used instead.
2392    pub fn rename_entry(
2393        &mut self,
2394        entry_id: ProjectEntryId,
2395        new_path: ProjectPath,
2396        cx: &mut Context<Self>,
2397    ) -> Task<Result<CreatedEntry>> {
2398        let worktree_store = self.worktree_store.clone();
2399        let Some((worktree, old_path, is_dir)) = worktree_store
2400            .read(cx)
2401            .worktree_and_entry_for_id(entry_id, cx)
2402            .map(|(worktree, entry)| (worktree, entry.path.clone(), entry.is_dir()))
2403        else {
2404            return Task::ready(Err(anyhow!(format!("No worktree for entry {entry_id:?}"))));
2405        };
2406
2407        let worktree_id = worktree.read(cx).id();
2408        let is_root_entry = self.entry_is_worktree_root(entry_id, cx);
2409
2410        let lsp_store = self.lsp_store().downgrade();
2411        cx.spawn(async move |project, cx| {
2412            let (old_abs_path, new_abs_path) = {
2413                let root_path = worktree.read_with(cx, |this, _| this.abs_path());
2414                let new_abs_path = if is_root_entry {
2415                    root_path
2416                        .parent()
2417                        .unwrap()
2418                        .join(new_path.path.as_std_path())
2419                } else {
2420                    root_path.join(&new_path.path.as_std_path())
2421                };
2422                (root_path.join(old_path.as_std_path()), new_abs_path)
2423            };
2424            let transaction = LspStore::will_rename_entry(
2425                lsp_store.clone(),
2426                worktree_id,
2427                &old_abs_path,
2428                &new_abs_path,
2429                is_dir,
2430                cx.clone(),
2431            )
2432            .await;
2433
2434            let entry = worktree_store
2435                .update(cx, |worktree_store, cx| {
2436                    worktree_store.rename_entry(entry_id, new_path.clone(), cx)
2437                })
2438                .await?;
2439
2440            project
2441                .update(cx, |_, cx| {
2442                    cx.emit(Event::EntryRenamed(
2443                        transaction,
2444                        new_path.clone(),
2445                        new_abs_path.clone(),
2446                    ));
2447                })
2448                .ok();
2449
2450            lsp_store
2451                .read_with(cx, |this, _| {
2452                    this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
2453                })
2454                .ok();
2455            Ok(entry)
2456        })
2457    }
2458
2459    #[inline]
2460    pub fn delete_file(
2461        &mut self,
2462        path: ProjectPath,
2463        trash: bool,
2464        cx: &mut Context<Self>,
2465    ) -> Option<Task<Result<()>>> {
2466        let entry = self.entry_for_path(&path, cx)?;
2467        self.delete_entry(entry.id, trash, cx)
2468    }
2469
2470    #[inline]
2471    pub fn delete_entry(
2472        &mut self,
2473        entry_id: ProjectEntryId,
2474        trash: bool,
2475        cx: &mut Context<Self>,
2476    ) -> Option<Task<Result<()>>> {
2477        let worktree = self.worktree_for_entry(entry_id, cx)?;
2478        cx.emit(Event::DeletedEntry(worktree.read(cx).id(), entry_id));
2479        worktree.update(cx, |worktree, cx| {
2480            worktree.delete_entry(entry_id, trash, cx)
2481        })
2482    }
2483
2484    #[inline]
2485    pub fn expand_entry(
2486        &mut self,
2487        worktree_id: WorktreeId,
2488        entry_id: ProjectEntryId,
2489        cx: &mut Context<Self>,
2490    ) -> Option<Task<Result<()>>> {
2491        let worktree = self.worktree_for_id(worktree_id, cx)?;
2492        worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
2493    }
2494
2495    pub fn expand_all_for_entry(
2496        &mut self,
2497        worktree_id: WorktreeId,
2498        entry_id: ProjectEntryId,
2499        cx: &mut Context<Self>,
2500    ) -> Option<Task<Result<()>>> {
2501        let worktree = self.worktree_for_id(worktree_id, cx)?;
2502        let task = worktree.update(cx, |worktree, cx| {
2503            worktree.expand_all_for_entry(entry_id, cx)
2504        });
2505        Some(cx.spawn(async move |this, cx| {
2506            task.context("no task")?.await?;
2507            this.update(cx, |_, cx| {
2508                cx.emit(Event::ExpandedAllForEntry(worktree_id, entry_id));
2509            })?;
2510            Ok(())
2511        }))
2512    }
2513
2514    pub fn shared(&mut self, project_id: u64, cx: &mut Context<Self>) -> Result<()> {
2515        anyhow::ensure!(
2516            matches!(self.client_state, ProjectClientState::Local),
2517            "project was already shared"
2518        );
2519
2520        self.client_subscriptions.extend([
2521            self.collab_client
2522                .subscribe_to_entity(project_id)?
2523                .set_entity(&cx.entity(), &cx.to_async()),
2524            self.collab_client
2525                .subscribe_to_entity(project_id)?
2526                .set_entity(&self.worktree_store, &cx.to_async()),
2527            self.collab_client
2528                .subscribe_to_entity(project_id)?
2529                .set_entity(&self.buffer_store, &cx.to_async()),
2530            self.collab_client
2531                .subscribe_to_entity(project_id)?
2532                .set_entity(&self.lsp_store, &cx.to_async()),
2533            self.collab_client
2534                .subscribe_to_entity(project_id)?
2535                .set_entity(&self.settings_observer, &cx.to_async()),
2536            self.collab_client
2537                .subscribe_to_entity(project_id)?
2538                .set_entity(&self.dap_store, &cx.to_async()),
2539            self.collab_client
2540                .subscribe_to_entity(project_id)?
2541                .set_entity(&self.breakpoint_store, &cx.to_async()),
2542            self.collab_client
2543                .subscribe_to_entity(project_id)?
2544                .set_entity(&self.git_store, &cx.to_async()),
2545        ]);
2546
2547        self.buffer_store.update(cx, |buffer_store, cx| {
2548            buffer_store.shared(project_id, self.collab_client.clone().into(), cx)
2549        });
2550        self.worktree_store.update(cx, |worktree_store, cx| {
2551            worktree_store.shared(project_id, self.collab_client.clone().into(), cx);
2552        });
2553        self.lsp_store.update(cx, |lsp_store, cx| {
2554            lsp_store.shared(project_id, self.collab_client.clone().into(), cx)
2555        });
2556        self.breakpoint_store.update(cx, |breakpoint_store, _| {
2557            breakpoint_store.shared(project_id, self.collab_client.clone().into())
2558        });
2559        self.dap_store.update(cx, |dap_store, cx| {
2560            dap_store.shared(project_id, self.collab_client.clone().into(), cx);
2561        });
2562        self.task_store.update(cx, |task_store, cx| {
2563            task_store.shared(project_id, self.collab_client.clone().into(), cx);
2564        });
2565        self.settings_observer.update(cx, |settings_observer, cx| {
2566            settings_observer.shared(project_id, self.collab_client.clone().into(), cx)
2567        });
2568        self.git_store.update(cx, |git_store, cx| {
2569            git_store.shared(project_id, self.collab_client.clone().into(), cx)
2570        });
2571
2572        self.client_state = ProjectClientState::Shared {
2573            remote_id: project_id,
2574        };
2575
2576        cx.emit(Event::RemoteIdChanged(Some(project_id)));
2577        Ok(())
2578    }
2579
2580    pub fn reshared(
2581        &mut self,
2582        message: proto::ResharedProject,
2583        cx: &mut Context<Self>,
2584    ) -> Result<()> {
2585        self.buffer_store
2586            .update(cx, |buffer_store, _| buffer_store.forget_shared_buffers());
2587        self.set_collaborators_from_proto(message.collaborators, cx)?;
2588
2589        self.worktree_store.update(cx, |worktree_store, cx| {
2590            worktree_store.send_project_updates(cx);
2591        });
2592        if let Some(remote_id) = self.remote_id() {
2593            self.git_store.update(cx, |git_store, cx| {
2594                git_store.shared(remote_id, self.collab_client.clone().into(), cx)
2595            });
2596        }
2597        cx.emit(Event::Reshared);
2598        Ok(())
2599    }
2600
2601    pub fn rejoined(
2602        &mut self,
2603        message: proto::RejoinedProject,
2604        message_id: u32,
2605        cx: &mut Context<Self>,
2606    ) -> Result<()> {
2607        cx.update_global::<SettingsStore, _>(|store, cx| {
2608            for worktree_metadata in &message.worktrees {
2609                store
2610                    .clear_local_settings(WorktreeId::from_proto(worktree_metadata.id), cx)
2611                    .log_err();
2612            }
2613        });
2614
2615        self.join_project_response_message_id = message_id;
2616        self.set_worktrees_from_proto(message.worktrees, cx)?;
2617        self.set_collaborators_from_proto(message.collaborators, cx)?;
2618
2619        let project = cx.weak_entity();
2620        self.lsp_store.update(cx, |lsp_store, cx| {
2621            lsp_store.set_language_server_statuses_from_proto(
2622                project,
2623                message.language_servers,
2624                message.language_server_capabilities,
2625                cx,
2626            )
2627        });
2628        self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
2629            .unwrap();
2630        cx.emit(Event::Rejoined);
2631        Ok(())
2632    }
2633
2634    #[inline]
2635    pub fn unshare(&mut self, cx: &mut Context<Self>) -> Result<()> {
2636        self.unshare_internal(cx)?;
2637        cx.emit(Event::RemoteIdChanged(None));
2638        Ok(())
2639    }
2640
2641    fn unshare_internal(&mut self, cx: &mut App) -> Result<()> {
2642        anyhow::ensure!(
2643            !self.is_via_collab(),
2644            "attempted to unshare a remote project"
2645        );
2646
2647        if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
2648            self.client_state = ProjectClientState::Local;
2649            self.collaborators.clear();
2650            self.client_subscriptions.clear();
2651            self.worktree_store.update(cx, |store, cx| {
2652                store.unshared(cx);
2653            });
2654            self.buffer_store.update(cx, |buffer_store, cx| {
2655                buffer_store.forget_shared_buffers();
2656                buffer_store.unshared(cx)
2657            });
2658            self.task_store.update(cx, |task_store, cx| {
2659                task_store.unshared(cx);
2660            });
2661            self.breakpoint_store.update(cx, |breakpoint_store, cx| {
2662                breakpoint_store.unshared(cx);
2663            });
2664            self.dap_store.update(cx, |dap_store, cx| {
2665                dap_store.unshared(cx);
2666            });
2667            self.settings_observer.update(cx, |settings_observer, cx| {
2668                settings_observer.unshared(cx);
2669            });
2670            self.git_store.update(cx, |git_store, cx| {
2671                git_store.unshared(cx);
2672            });
2673
2674            self.collab_client
2675                .send(proto::UnshareProject {
2676                    project_id: remote_id,
2677                })
2678                .ok();
2679            Ok(())
2680        } else {
2681            anyhow::bail!("attempted to unshare an unshared project");
2682        }
2683    }
2684
2685    pub fn disconnected_from_host(&mut self, cx: &mut Context<Self>) {
2686        if self.is_disconnected(cx) {
2687            return;
2688        }
2689        self.disconnected_from_host_internal(cx);
2690        cx.emit(Event::DisconnectedFromHost);
2691    }
2692
2693    pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut Context<Self>) {
2694        let new_capability =
2695            if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
2696                Capability::ReadWrite
2697            } else {
2698                Capability::ReadOnly
2699            };
2700        if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
2701            if *capability == new_capability {
2702                return;
2703            }
2704
2705            *capability = new_capability;
2706            for buffer in self.opened_buffers(cx) {
2707                buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
2708            }
2709        }
2710    }
2711
2712    fn disconnected_from_host_internal(&mut self, cx: &mut App) {
2713        if let ProjectClientState::Remote {
2714            sharing_has_stopped,
2715            ..
2716        } = &mut self.client_state
2717        {
2718            *sharing_has_stopped = true;
2719            self.collaborators.clear();
2720            self.worktree_store.update(cx, |store, cx| {
2721                store.disconnected_from_host(cx);
2722            });
2723            self.buffer_store.update(cx, |buffer_store, cx| {
2724                buffer_store.disconnected_from_host(cx)
2725            });
2726            self.lsp_store
2727                .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
2728        }
2729    }
2730
2731    #[inline]
2732    pub fn close(&mut self, cx: &mut Context<Self>) {
2733        cx.emit(Event::Closed);
2734    }
2735
2736    #[inline]
2737    pub fn is_disconnected(&self, cx: &App) -> bool {
2738        match &self.client_state {
2739            ProjectClientState::Remote {
2740                sharing_has_stopped,
2741                ..
2742            } => *sharing_has_stopped,
2743            ProjectClientState::Local if self.is_via_remote_server() => {
2744                self.remote_client_is_disconnected(cx)
2745            }
2746            _ => false,
2747        }
2748    }
2749
2750    #[inline]
2751    fn remote_client_is_disconnected(&self, cx: &App) -> bool {
2752        self.remote_client
2753            .as_ref()
2754            .map(|remote| remote.read(cx).is_disconnected())
2755            .unwrap_or(false)
2756    }
2757
2758    #[inline]
2759    pub fn capability(&self) -> Capability {
2760        match &self.client_state {
2761            ProjectClientState::Remote { capability, .. } => *capability,
2762            ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
2763        }
2764    }
2765
2766    #[inline]
2767    pub fn is_read_only(&self, cx: &App) -> bool {
2768        self.is_disconnected(cx) || !self.capability().editable()
2769    }
2770
2771    #[inline]
2772    pub fn is_local(&self) -> bool {
2773        match &self.client_state {
2774            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2775                self.remote_client.is_none()
2776            }
2777            ProjectClientState::Remote { .. } => false,
2778        }
2779    }
2780
2781    /// Whether this project is a remote server (not counting collab).
2782    #[inline]
2783    pub fn is_via_remote_server(&self) -> bool {
2784        match &self.client_state {
2785            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2786                self.remote_client.is_some()
2787            }
2788            ProjectClientState::Remote { .. } => false,
2789        }
2790    }
2791
2792    /// Whether this project is from collab (not counting remote servers).
2793    #[inline]
2794    pub fn is_via_collab(&self) -> bool {
2795        match &self.client_state {
2796            ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
2797            ProjectClientState::Remote { .. } => true,
2798        }
2799    }
2800
2801    /// `!self.is_local()`
2802    #[inline]
2803    pub fn is_remote(&self) -> bool {
2804        debug_assert_eq!(
2805            !self.is_local(),
2806            self.is_via_collab() || self.is_via_remote_server()
2807        );
2808        !self.is_local()
2809    }
2810
2811    #[inline]
2812    pub fn is_via_wsl_with_host_interop(&self, cx: &App) -> bool {
2813        match &self.client_state {
2814            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2815                matches!(
2816                    &self.remote_client, Some(remote_client)
2817                    if remote_client.read(cx).has_wsl_interop()
2818                )
2819            }
2820            _ => false,
2821        }
2822    }
2823
2824    pub fn disable_worktree_scanner(&mut self, cx: &mut Context<Self>) {
2825        self.worktree_store.update(cx, |worktree_store, _cx| {
2826            worktree_store.disable_scanner();
2827        });
2828    }
2829
2830    #[inline]
2831    pub fn create_buffer(
2832        &mut self,
2833        language: Option<Arc<Language>>,
2834        project_searchable: bool,
2835        cx: &mut Context<Self>,
2836    ) -> Task<Result<Entity<Buffer>>> {
2837        self.buffer_store.update(cx, |buffer_store, cx| {
2838            buffer_store.create_buffer(language, project_searchable, cx)
2839        })
2840    }
2841
2842    #[inline]
2843    pub fn create_local_buffer(
2844        &mut self,
2845        text: &str,
2846        language: Option<Arc<Language>>,
2847        project_searchable: bool,
2848        cx: &mut Context<Self>,
2849    ) -> Entity<Buffer> {
2850        if self.is_remote() {
2851            panic!("called create_local_buffer on a remote project")
2852        }
2853        self.buffer_store.update(cx, |buffer_store, cx| {
2854            buffer_store.create_local_buffer(text, language, project_searchable, cx)
2855        })
2856    }
2857
2858    pub fn open_path(
2859        &mut self,
2860        path: ProjectPath,
2861        cx: &mut Context<Self>,
2862    ) -> Task<Result<(Option<ProjectEntryId>, Entity<Buffer>)>> {
2863        let task = self.open_buffer(path, cx);
2864        cx.spawn(async move |_project, cx| {
2865            let buffer = task.await?;
2866            let project_entry_id = buffer.read_with(cx, |buffer, _cx| {
2867                File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id())
2868            });
2869
2870            Ok((project_entry_id, buffer))
2871        })
2872    }
2873
2874    pub fn open_local_buffer(
2875        &mut self,
2876        abs_path: impl AsRef<Path>,
2877        cx: &mut Context<Self>,
2878    ) -> Task<Result<Entity<Buffer>>> {
2879        let worktree_task = self.find_or_create_worktree(abs_path.as_ref(), false, cx);
2880        cx.spawn(async move |this, cx| {
2881            let (worktree, relative_path) = worktree_task.await?;
2882            this.update(cx, |this, cx| {
2883                this.open_buffer((worktree.read(cx).id(), relative_path), cx)
2884            })?
2885            .await
2886        })
2887    }
2888
2889    #[cfg(feature = "test-support")]
2890    pub fn open_local_buffer_with_lsp(
2891        &mut self,
2892        abs_path: impl AsRef<Path>,
2893        cx: &mut Context<Self>,
2894    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
2895        if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
2896            self.open_buffer_with_lsp((worktree.read(cx).id(), relative_path), cx)
2897        } else {
2898            Task::ready(Err(anyhow!("no such path")))
2899        }
2900    }
2901
2902    pub fn download_file(
2903        &mut self,
2904        worktree_id: WorktreeId,
2905        path: Arc<RelPath>,
2906        destination_path: PathBuf,
2907        cx: &mut Context<Self>,
2908    ) -> Task<Result<()>> {
2909        log::debug!(
2910            "download_file called: worktree_id={:?}, path={:?}, destination={:?}",
2911            worktree_id,
2912            path,
2913            destination_path
2914        );
2915
2916        let Some(remote_client) = &self.remote_client else {
2917            log::error!("download_file: not a remote project");
2918            return Task::ready(Err(anyhow!("not a remote project")));
2919        };
2920
2921        let proto_client = remote_client.read(cx).proto_client();
2922        // For SSH remote projects, use REMOTE_SERVER_PROJECT_ID instead of remote_id()
2923        // because SSH projects have client_state: Local but still need to communicate with remote server
2924        let project_id = self.remote_id().unwrap_or(REMOTE_SERVER_PROJECT_ID);
2925        let downloading_files = self.downloading_files.clone();
2926        let path_str = path.to_proto();
2927
2928        static NEXT_FILE_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
2929        let file_id = NEXT_FILE_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
2930
2931        // Register BEFORE sending request to avoid race condition
2932        let key = (worktree_id, path_str.clone());
2933        log::debug!(
2934            "download_file: pre-registering download with key={:?}, file_id={}",
2935            key,
2936            file_id
2937        );
2938        downloading_files.lock().insert(
2939            key,
2940            DownloadingFile {
2941                destination_path: destination_path,
2942                chunks: Vec::new(),
2943                total_size: 0,
2944                file_id: Some(file_id),
2945            },
2946        );
2947        log::debug!(
2948            "download_file: sending DownloadFileByPath request, path_str={}",
2949            path_str
2950        );
2951
2952        cx.spawn(async move |_this, _cx| {
2953            log::debug!("download_file: sending request with file_id={}...", file_id);
2954            let response = proto_client
2955                .request(proto::DownloadFileByPath {
2956                    project_id,
2957                    worktree_id: worktree_id.to_proto(),
2958                    path: path_str.clone(),
2959                    file_id,
2960                })
2961                .await?;
2962
2963            log::debug!("download_file: got response, file_id={}", response.file_id);
2964            // The file_id is set from the State message, we just confirm the request succeeded
2965            Ok(())
2966        })
2967    }
2968
2969    #[ztracing::instrument(skip_all)]
2970    pub fn open_buffer(
2971        &mut self,
2972        path: impl Into<ProjectPath>,
2973        cx: &mut App,
2974    ) -> Task<Result<Entity<Buffer>>> {
2975        if self.is_disconnected(cx) {
2976            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2977        }
2978
2979        self.buffer_store.update(cx, |buffer_store, cx| {
2980            buffer_store.open_buffer(path.into(), cx)
2981        })
2982    }
2983
2984    #[cfg(feature = "test-support")]
2985    pub fn open_buffer_with_lsp(
2986        &mut self,
2987        path: impl Into<ProjectPath>,
2988        cx: &mut Context<Self>,
2989    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
2990        let buffer = self.open_buffer(path, cx);
2991        cx.spawn(async move |this, cx| {
2992            let buffer = buffer.await?;
2993            let handle = this.update(cx, |project, cx| {
2994                project.register_buffer_with_language_servers(&buffer, cx)
2995            })?;
2996            Ok((buffer, handle))
2997        })
2998    }
2999
3000    pub fn register_buffer_with_language_servers(
3001        &self,
3002        buffer: &Entity<Buffer>,
3003        cx: &mut App,
3004    ) -> OpenLspBufferHandle {
3005        self.lsp_store.update(cx, |lsp_store, cx| {
3006            lsp_store.register_buffer_with_language_servers(buffer, HashSet::default(), false, cx)
3007        })
3008    }
3009
3010    pub fn open_unstaged_diff(
3011        &mut self,
3012        buffer: Entity<Buffer>,
3013        cx: &mut Context<Self>,
3014    ) -> Task<Result<Entity<BufferDiff>>> {
3015        if self.is_disconnected(cx) {
3016            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
3017        }
3018        self.git_store
3019            .update(cx, |git_store, cx| git_store.open_unstaged_diff(buffer, cx))
3020    }
3021
3022    #[ztracing::instrument(skip_all)]
3023    pub fn open_uncommitted_diff(
3024        &mut self,
3025        buffer: Entity<Buffer>,
3026        cx: &mut Context<Self>,
3027    ) -> Task<Result<Entity<BufferDiff>>> {
3028        if self.is_disconnected(cx) {
3029            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
3030        }
3031        self.git_store.update(cx, |git_store, cx| {
3032            git_store.open_uncommitted_diff(buffer, cx)
3033        })
3034    }
3035
3036    pub fn open_buffer_by_id(
3037        &mut self,
3038        id: BufferId,
3039        cx: &mut Context<Self>,
3040    ) -> Task<Result<Entity<Buffer>>> {
3041        if let Some(buffer) = self.buffer_for_id(id, cx) {
3042            Task::ready(Ok(buffer))
3043        } else if self.is_local() || self.is_via_remote_server() {
3044            Task::ready(Err(anyhow!("buffer {id} does not exist")))
3045        } else if let Some(project_id) = self.remote_id() {
3046            let request = self.collab_client.request(proto::OpenBufferById {
3047                project_id,
3048                id: id.into(),
3049            });
3050            cx.spawn(async move |project, cx| {
3051                let buffer_id = BufferId::new(request.await?.buffer_id)?;
3052                project
3053                    .update(cx, |project, cx| {
3054                        project.buffer_store.update(cx, |buffer_store, cx| {
3055                            buffer_store.wait_for_remote_buffer(buffer_id, cx)
3056                        })
3057                    })?
3058                    .await
3059            })
3060        } else {
3061            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
3062        }
3063    }
3064
3065    pub fn save_buffers(
3066        &self,
3067        buffers: HashSet<Entity<Buffer>>,
3068        cx: &mut Context<Self>,
3069    ) -> Task<Result<()>> {
3070        cx.spawn(async move |this, cx| {
3071            let save_tasks = buffers.into_iter().filter_map(|buffer| {
3072                this.update(cx, |this, cx| this.save_buffer(buffer, cx))
3073                    .ok()
3074            });
3075            try_join_all(save_tasks).await?;
3076            Ok(())
3077        })
3078    }
3079
3080    pub fn save_buffer(&self, buffer: Entity<Buffer>, cx: &mut Context<Self>) -> Task<Result<()>> {
3081        self.buffer_store
3082            .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
3083    }
3084
3085    pub fn save_buffer_as(
3086        &mut self,
3087        buffer: Entity<Buffer>,
3088        path: ProjectPath,
3089        cx: &mut Context<Self>,
3090    ) -> Task<Result<()>> {
3091        self.buffer_store.update(cx, |buffer_store, cx| {
3092            buffer_store.save_buffer_as(buffer.clone(), path, cx)
3093        })
3094    }
3095
3096    pub fn get_open_buffer(&self, path: &ProjectPath, cx: &App) -> Option<Entity<Buffer>> {
3097        self.buffer_store.read(cx).get_by_path(path)
3098    }
3099
3100    fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
3101        {
3102            let mut remotely_created_models = self.remotely_created_models.lock();
3103            if remotely_created_models.retain_count > 0 {
3104                remotely_created_models.buffers.push(buffer.clone())
3105            }
3106        }
3107
3108        self.request_buffer_diff_recalculation(buffer, cx);
3109
3110        cx.subscribe(buffer, |this, buffer, event, cx| {
3111            this.on_buffer_event(buffer, event, cx);
3112        })
3113        .detach();
3114
3115        Ok(())
3116    }
3117
3118    pub fn open_image(
3119        &mut self,
3120        path: impl Into<ProjectPath>,
3121        cx: &mut Context<Self>,
3122    ) -> Task<Result<Entity<ImageItem>>> {
3123        if self.is_disconnected(cx) {
3124            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
3125        }
3126
3127        let open_image_task = self.image_store.update(cx, |image_store, cx| {
3128            image_store.open_image(path.into(), cx)
3129        });
3130
3131        let weak_project = cx.entity().downgrade();
3132        cx.spawn(async move |_, cx| {
3133            let image_item = open_image_task.await?;
3134
3135            // Check if metadata already exists (e.g., for remote images)
3136            let needs_metadata =
3137                cx.read_entity(&image_item, |item, _| item.image_metadata.is_none());
3138
3139            if needs_metadata {
3140                let project = weak_project.upgrade().context("Project dropped")?;
3141                let metadata =
3142                    ImageItem::load_image_metadata(image_item.clone(), project, cx).await?;
3143                image_item.update(cx, |image_item, cx| {
3144                    image_item.image_metadata = Some(metadata);
3145                    cx.emit(ImageItemEvent::MetadataUpdated);
3146                });
3147            }
3148
3149            Ok(image_item)
3150        })
3151    }
3152
3153    async fn send_buffer_ordered_messages(
3154        project: WeakEntity<Self>,
3155        rx: UnboundedReceiver<BufferOrderedMessage>,
3156        cx: &mut AsyncApp,
3157    ) -> Result<()> {
3158        const MAX_BATCH_SIZE: usize = 128;
3159
3160        let mut operations_by_buffer_id = HashMap::default();
3161        async fn flush_operations(
3162            this: &WeakEntity<Project>,
3163            operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
3164            needs_resync_with_host: &mut bool,
3165            is_local: bool,
3166            cx: &mut AsyncApp,
3167        ) -> Result<()> {
3168            for (buffer_id, operations) in operations_by_buffer_id.drain() {
3169                let request = this.read_with(cx, |this, _| {
3170                    let project_id = this.remote_id()?;
3171                    Some(this.collab_client.request(proto::UpdateBuffer {
3172                        buffer_id: buffer_id.into(),
3173                        project_id,
3174                        operations,
3175                    }))
3176                })?;
3177                if let Some(request) = request
3178                    && request.await.is_err()
3179                    && !is_local
3180                {
3181                    *needs_resync_with_host = true;
3182                    break;
3183                }
3184            }
3185            Ok(())
3186        }
3187
3188        let mut needs_resync_with_host = false;
3189        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
3190
3191        while let Some(changes) = changes.next().await {
3192            let is_local = project.read_with(cx, |this, _| this.is_local())?;
3193
3194            for change in changes {
3195                match change {
3196                    BufferOrderedMessage::Operation {
3197                        buffer_id,
3198                        operation,
3199                    } => {
3200                        if needs_resync_with_host {
3201                            continue;
3202                        }
3203
3204                        operations_by_buffer_id
3205                            .entry(buffer_id)
3206                            .or_insert(Vec::new())
3207                            .push(operation);
3208                    }
3209
3210                    BufferOrderedMessage::Resync => {
3211                        operations_by_buffer_id.clear();
3212                        if project
3213                            .update(cx, |this, cx| this.synchronize_remote_buffers(cx))?
3214                            .await
3215                            .is_ok()
3216                        {
3217                            needs_resync_with_host = false;
3218                        }
3219                    }
3220
3221                    BufferOrderedMessage::LanguageServerUpdate {
3222                        language_server_id,
3223                        message,
3224                        name,
3225                    } => {
3226                        flush_operations(
3227                            &project,
3228                            &mut operations_by_buffer_id,
3229                            &mut needs_resync_with_host,
3230                            is_local,
3231                            cx,
3232                        )
3233                        .await?;
3234
3235                        project.read_with(cx, |project, _| {
3236                            if let Some(project_id) = project.remote_id() {
3237                                project
3238                                    .collab_client
3239                                    .send(proto::UpdateLanguageServer {
3240                                        project_id,
3241                                        server_name: name.map(|name| String::from(name.0)),
3242                                        language_server_id: language_server_id.to_proto(),
3243                                        variant: Some(message),
3244                                    })
3245                                    .log_err();
3246                            }
3247                        })?;
3248                    }
3249                }
3250            }
3251
3252            flush_operations(
3253                &project,
3254                &mut operations_by_buffer_id,
3255                &mut needs_resync_with_host,
3256                is_local,
3257                cx,
3258            )
3259            .await?;
3260        }
3261
3262        Ok(())
3263    }
3264
3265    fn on_buffer_store_event(
3266        &mut self,
3267        _: Entity<BufferStore>,
3268        event: &BufferStoreEvent,
3269        cx: &mut Context<Self>,
3270    ) {
3271        match event {
3272            BufferStoreEvent::BufferAdded(buffer) => {
3273                self.register_buffer(buffer, cx).log_err();
3274            }
3275            BufferStoreEvent::BufferDropped(buffer_id) => {
3276                if let Some(ref remote_client) = self.remote_client {
3277                    remote_client
3278                        .read(cx)
3279                        .proto_client()
3280                        .send(proto::CloseBuffer {
3281                            project_id: 0,
3282                            buffer_id: buffer_id.to_proto(),
3283                        })
3284                        .log_err();
3285                }
3286            }
3287            _ => {}
3288        }
3289    }
3290
3291    fn on_image_store_event(
3292        &mut self,
3293        _: Entity<ImageStore>,
3294        event: &ImageStoreEvent,
3295        cx: &mut Context<Self>,
3296    ) {
3297        match event {
3298            ImageStoreEvent::ImageAdded(image) => {
3299                cx.subscribe(image, |this, image, event, cx| {
3300                    this.on_image_event(image, event, cx);
3301                })
3302                .detach();
3303            }
3304        }
3305    }
3306
3307    fn on_dap_store_event(
3308        &mut self,
3309        _: Entity<DapStore>,
3310        event: &DapStoreEvent,
3311        cx: &mut Context<Self>,
3312    ) {
3313        if let DapStoreEvent::Notification(message) = event {
3314            cx.emit(Event::Toast {
3315                notification_id: "dap".into(),
3316                message: message.clone(),
3317                link: None,
3318            });
3319        }
3320    }
3321
3322    fn on_lsp_store_event(
3323        &mut self,
3324        _: Entity<LspStore>,
3325        event: &LspStoreEvent,
3326        cx: &mut Context<Self>,
3327    ) {
3328        match event {
3329            LspStoreEvent::DiagnosticsUpdated { server_id, paths } => {
3330                cx.emit(Event::DiagnosticsUpdated {
3331                    paths: paths.clone(),
3332                    language_server_id: *server_id,
3333                })
3334            }
3335            LspStoreEvent::LanguageServerAdded(server_id, name, worktree_id) => cx.emit(
3336                Event::LanguageServerAdded(*server_id, name.clone(), *worktree_id),
3337            ),
3338            LspStoreEvent::LanguageServerRemoved(server_id) => {
3339                cx.emit(Event::LanguageServerRemoved(*server_id))
3340            }
3341            LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
3342                Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
3343            ),
3344            LspStoreEvent::LanguageDetected {
3345                buffer,
3346                new_language,
3347            } => {
3348                let Some(_) = new_language else {
3349                    cx.emit(Event::LanguageNotFound(buffer.clone()));
3350                    return;
3351                };
3352            }
3353            LspStoreEvent::RefreshInlayHints {
3354                server_id,
3355                request_id,
3356            } => cx.emit(Event::RefreshInlayHints {
3357                server_id: *server_id,
3358                request_id: *request_id,
3359            }),
3360            LspStoreEvent::RefreshSemanticTokens {
3361                server_id,
3362                request_id,
3363            } => cx.emit(Event::RefreshSemanticTokens {
3364                server_id: *server_id,
3365                request_id: *request_id,
3366            }),
3367            LspStoreEvent::RefreshCodeLens => cx.emit(Event::RefreshCodeLens),
3368            LspStoreEvent::LanguageServerPrompt(prompt) => {
3369                cx.emit(Event::LanguageServerPrompt(prompt.clone()))
3370            }
3371            LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
3372                cx.emit(Event::DiskBasedDiagnosticsStarted {
3373                    language_server_id: *language_server_id,
3374                });
3375            }
3376            LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
3377                cx.emit(Event::DiskBasedDiagnosticsFinished {
3378                    language_server_id: *language_server_id,
3379                });
3380            }
3381            LspStoreEvent::LanguageServerUpdate {
3382                language_server_id,
3383                name,
3384                message,
3385            } => {
3386                if self.is_local() {
3387                    self.enqueue_buffer_ordered_message(
3388                        BufferOrderedMessage::LanguageServerUpdate {
3389                            language_server_id: *language_server_id,
3390                            message: message.clone(),
3391                            name: name.clone(),
3392                        },
3393                    )
3394                    .ok();
3395                }
3396
3397                match message {
3398                    proto::update_language_server::Variant::MetadataUpdated(update) => {
3399                        self.lsp_store.update(cx, |lsp_store, _| {
3400                            if let Some(capabilities) = update
3401                                .capabilities
3402                                .as_ref()
3403                                .and_then(|capabilities| serde_json::from_str(capabilities).ok())
3404                            {
3405                                lsp_store
3406                                    .lsp_server_capabilities
3407                                    .insert(*language_server_id, capabilities);
3408                            }
3409
3410                            if let Some(language_server_status) = lsp_store
3411                                .language_server_statuses
3412                                .get_mut(language_server_id)
3413                            {
3414                                if let Some(binary) = &update.binary {
3415                                    language_server_status.binary = Some(LanguageServerBinary {
3416                                        path: PathBuf::from(&binary.path),
3417                                        arguments: binary
3418                                            .arguments
3419                                            .iter()
3420                                            .map(OsString::from)
3421                                            .collect(),
3422                                        env: None,
3423                                    });
3424                                }
3425
3426                                language_server_status.configuration = update
3427                                    .configuration
3428                                    .as_ref()
3429                                    .and_then(|config_str| serde_json::from_str(config_str).ok());
3430
3431                                language_server_status.workspace_folders = update
3432                                    .workspace_folders
3433                                    .iter()
3434                                    .filter_map(|uri_str| lsp::Uri::from_str(uri_str).ok())
3435                                    .collect();
3436                            }
3437                        });
3438                    }
3439                    proto::update_language_server::Variant::RegisteredForBuffer(update) => {
3440                        if let Some(buffer_id) = BufferId::new(update.buffer_id).ok() {
3441                            cx.emit(Event::LanguageServerBufferRegistered {
3442                                buffer_id,
3443                                server_id: *language_server_id,
3444                                buffer_abs_path: PathBuf::from(&update.buffer_abs_path),
3445                                name: name.clone(),
3446                            });
3447                        }
3448                    }
3449                    _ => (),
3450                }
3451            }
3452            LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
3453                notification_id: "lsp".into(),
3454                message: message.clone(),
3455                link: None,
3456            }),
3457            LspStoreEvent::SnippetEdit {
3458                buffer_id,
3459                edits,
3460                most_recent_edit,
3461            } => {
3462                if most_recent_edit.replica_id == self.replica_id() {
3463                    cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
3464                }
3465            }
3466            LspStoreEvent::WorkspaceEditApplied(transaction) => {
3467                cx.emit(Event::WorkspaceEditApplied(transaction.clone()))
3468            }
3469        }
3470    }
3471
3472    fn on_remote_client_event(
3473        &mut self,
3474        _: Entity<RemoteClient>,
3475        event: &remote::RemoteClientEvent,
3476        cx: &mut Context<Self>,
3477    ) {
3478        match event {
3479            &remote::RemoteClientEvent::Disconnected { server_not_running } => {
3480                self.worktree_store.update(cx, |store, cx| {
3481                    store.disconnected_from_host(cx);
3482                });
3483                self.buffer_store.update(cx, |buffer_store, cx| {
3484                    buffer_store.disconnected_from_host(cx)
3485                });
3486                self.lsp_store.update(cx, |lsp_store, _cx| {
3487                    lsp_store.disconnected_from_ssh_remote()
3488                });
3489                cx.emit(Event::DisconnectedFromRemote { server_not_running });
3490            }
3491        }
3492    }
3493
3494    fn on_settings_observer_event(
3495        &mut self,
3496        _: Entity<SettingsObserver>,
3497        event: &SettingsObserverEvent,
3498        cx: &mut Context<Self>,
3499    ) {
3500        match event {
3501            SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
3502                Err(InvalidSettingsError::LocalSettings { message, path }) => {
3503                    let message = format!("Failed to set local settings in {path:?}:\n{message}");
3504                    cx.emit(Event::Toast {
3505                        notification_id: format!("local-settings-{path:?}").into(),
3506                        link: None,
3507                        message,
3508                    });
3509                }
3510                Ok(path) => cx.emit(Event::HideToast {
3511                    notification_id: format!("local-settings-{path:?}").into(),
3512                }),
3513                Err(_) => {}
3514            },
3515            SettingsObserverEvent::LocalTasksUpdated(result) => match result {
3516                Err(InvalidSettingsError::Tasks { message, path }) => {
3517                    let message = format!("Failed to set local tasks in {path:?}:\n{message}");
3518                    cx.emit(Event::Toast {
3519                        notification_id: format!("local-tasks-{path:?}").into(),
3520                        link: Some(ToastLink {
3521                            label: "Open Tasks Documentation",
3522                            url: "https://zed.dev/docs/tasks",
3523                        }),
3524                        message,
3525                    });
3526                }
3527                Ok(path) => cx.emit(Event::HideToast {
3528                    notification_id: format!("local-tasks-{path:?}").into(),
3529                }),
3530                Err(_) => {}
3531            },
3532            SettingsObserverEvent::LocalDebugScenariosUpdated(result) => match result {
3533                Err(InvalidSettingsError::Debug { message, path }) => {
3534                    let message =
3535                        format!("Failed to set local debug scenarios in {path:?}:\n{message}");
3536                    cx.emit(Event::Toast {
3537                        notification_id: format!("local-debug-scenarios-{path:?}").into(),
3538                        link: None,
3539                        message,
3540                    });
3541                }
3542                Ok(path) => cx.emit(Event::HideToast {
3543                    notification_id: format!("local-debug-scenarios-{path:?}").into(),
3544                }),
3545                Err(_) => {}
3546            },
3547        }
3548    }
3549
3550    fn on_worktree_store_event(
3551        &mut self,
3552        _: Entity<WorktreeStore>,
3553        event: &WorktreeStoreEvent,
3554        cx: &mut Context<Self>,
3555    ) {
3556        match event {
3557            WorktreeStoreEvent::WorktreeAdded(worktree) => {
3558                self.on_worktree_added(worktree, cx);
3559                cx.emit(Event::WorktreeAdded(worktree.read(cx).id()));
3560            }
3561            WorktreeStoreEvent::WorktreeRemoved(_, id) => {
3562                cx.emit(Event::WorktreeRemoved(*id));
3563            }
3564            WorktreeStoreEvent::WorktreeReleased(_, id) => {
3565                self.on_worktree_released(*id, cx);
3566            }
3567            WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
3568            WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
3569            WorktreeStoreEvent::WorktreeUpdatedEntries(worktree_id, changes) => {
3570                self.client()
3571                    .telemetry()
3572                    .report_discovered_project_type_events(*worktree_id, changes);
3573                cx.emit(Event::WorktreeUpdatedEntries(*worktree_id, changes.clone()))
3574            }
3575            WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, id) => {
3576                cx.emit(Event::DeletedEntry(*worktree_id, *id))
3577            }
3578            // Listen to the GitStore instead.
3579            WorktreeStoreEvent::WorktreeUpdatedGitRepositories(_, _) => {}
3580        }
3581    }
3582
3583    fn on_worktree_added(&mut self, worktree: &Entity<Worktree>, _: &mut Context<Self>) {
3584        let mut remotely_created_models = self.remotely_created_models.lock();
3585        if remotely_created_models.retain_count > 0 {
3586            remotely_created_models.worktrees.push(worktree.clone())
3587        }
3588    }
3589
3590    fn on_worktree_released(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
3591        if let Some(remote) = &self.remote_client {
3592            remote
3593                .read(cx)
3594                .proto_client()
3595                .send(proto::RemoveWorktree {
3596                    worktree_id: id_to_remove.to_proto(),
3597                })
3598                .log_err();
3599        }
3600    }
3601
3602    fn on_buffer_event(
3603        &mut self,
3604        buffer: Entity<Buffer>,
3605        event: &BufferEvent,
3606        cx: &mut Context<Self>,
3607    ) -> Option<()> {
3608        if matches!(event, BufferEvent::Edited | BufferEvent::Reloaded) {
3609            self.request_buffer_diff_recalculation(&buffer, cx);
3610        }
3611
3612        if matches!(event, BufferEvent::Edited) {
3613            cx.emit(Event::BufferEdited);
3614        }
3615
3616        let buffer_id = buffer.read(cx).remote_id();
3617        match event {
3618            BufferEvent::ReloadNeeded => {
3619                if !self.is_via_collab() {
3620                    self.reload_buffers([buffer.clone()].into_iter().collect(), true, cx)
3621                        .detach_and_log_err(cx);
3622                }
3623            }
3624            BufferEvent::Operation {
3625                operation,
3626                is_local: true,
3627            } => {
3628                let operation = language::proto::serialize_operation(operation);
3629
3630                if let Some(remote) = &self.remote_client {
3631                    remote
3632                        .read(cx)
3633                        .proto_client()
3634                        .send(proto::UpdateBuffer {
3635                            project_id: 0,
3636                            buffer_id: buffer_id.to_proto(),
3637                            operations: vec![operation.clone()],
3638                        })
3639                        .ok();
3640                }
3641
3642                self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
3643                    buffer_id,
3644                    operation,
3645                })
3646                .ok();
3647            }
3648
3649            _ => {}
3650        }
3651
3652        None
3653    }
3654
3655    fn on_image_event(
3656        &mut self,
3657        image: Entity<ImageItem>,
3658        event: &ImageItemEvent,
3659        cx: &mut Context<Self>,
3660    ) -> Option<()> {
3661        // TODO: handle image events from remote
3662        if let ImageItemEvent::ReloadNeeded = event
3663            && !self.is_via_collab()
3664        {
3665            self.reload_images([image].into_iter().collect(), cx)
3666                .detach_and_log_err(cx);
3667        }
3668
3669        None
3670    }
3671
3672    fn request_buffer_diff_recalculation(
3673        &mut self,
3674        buffer: &Entity<Buffer>,
3675        cx: &mut Context<Self>,
3676    ) {
3677        self.buffers_needing_diff.insert(buffer.downgrade());
3678        let first_insertion = self.buffers_needing_diff.len() == 1;
3679        let settings = ProjectSettings::get_global(cx);
3680        let delay = settings.git.gutter_debounce;
3681
3682        if delay == 0 {
3683            if first_insertion {
3684                let this = cx.weak_entity();
3685                cx.defer(move |cx| {
3686                    if let Some(this) = this.upgrade() {
3687                        this.update(cx, |this, cx| {
3688                            this.recalculate_buffer_diffs(cx).detach();
3689                        });
3690                    }
3691                });
3692            }
3693            return;
3694        }
3695
3696        const MIN_DELAY: u64 = 50;
3697        let delay = delay.max(MIN_DELAY);
3698        let duration = Duration::from_millis(delay);
3699
3700        self.git_diff_debouncer
3701            .fire_new(duration, cx, move |this, cx| {
3702                this.recalculate_buffer_diffs(cx)
3703            });
3704    }
3705
3706    fn recalculate_buffer_diffs(&mut self, cx: &mut Context<Self>) -> Task<()> {
3707        cx.spawn(async move |this, cx| {
3708            loop {
3709                let task = this
3710                    .update(cx, |this, cx| {
3711                        let buffers = this
3712                            .buffers_needing_diff
3713                            .drain()
3714                            .filter_map(|buffer| buffer.upgrade())
3715                            .collect::<Vec<_>>();
3716                        if buffers.is_empty() {
3717                            None
3718                        } else {
3719                            Some(this.git_store.update(cx, |git_store, cx| {
3720                                git_store.recalculate_buffer_diffs(buffers, cx)
3721                            }))
3722                        }
3723                    })
3724                    .ok()
3725                    .flatten();
3726
3727                if let Some(task) = task {
3728                    task.await;
3729                } else {
3730                    break;
3731                }
3732            }
3733        })
3734    }
3735
3736    pub fn set_language_for_buffer(
3737        &mut self,
3738        buffer: &Entity<Buffer>,
3739        new_language: Arc<Language>,
3740        cx: &mut Context<Self>,
3741    ) {
3742        self.lsp_store.update(cx, |lsp_store, cx| {
3743            lsp_store.set_language_for_buffer(buffer, new_language, cx)
3744        })
3745    }
3746
3747    pub fn restart_language_servers_for_buffers(
3748        &mut self,
3749        buffers: Vec<Entity<Buffer>>,
3750        only_restart_servers: HashSet<LanguageServerSelector>,
3751        cx: &mut Context<Self>,
3752    ) {
3753        self.lsp_store.update(cx, |lsp_store, cx| {
3754            lsp_store.restart_language_servers_for_buffers(buffers, only_restart_servers, cx)
3755        })
3756    }
3757
3758    pub fn stop_language_servers_for_buffers(
3759        &mut self,
3760        buffers: Vec<Entity<Buffer>>,
3761        also_restart_servers: HashSet<LanguageServerSelector>,
3762        cx: &mut Context<Self>,
3763    ) {
3764        self.lsp_store
3765            .update(cx, |lsp_store, cx| {
3766                lsp_store.stop_language_servers_for_buffers(buffers, also_restart_servers, cx)
3767            })
3768            .detach_and_log_err(cx);
3769    }
3770
3771    pub fn cancel_language_server_work_for_buffers(
3772        &mut self,
3773        buffers: impl IntoIterator<Item = Entity<Buffer>>,
3774        cx: &mut Context<Self>,
3775    ) {
3776        self.lsp_store.update(cx, |lsp_store, cx| {
3777            lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
3778        })
3779    }
3780
3781    pub fn cancel_language_server_work(
3782        &mut self,
3783        server_id: LanguageServerId,
3784        token_to_cancel: Option<ProgressToken>,
3785        cx: &mut Context<Self>,
3786    ) {
3787        self.lsp_store.update(cx, |lsp_store, cx| {
3788            lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
3789        })
3790    }
3791
3792    fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
3793        self.buffer_ordered_messages_tx
3794            .unbounded_send(message)
3795            .map_err(|e| anyhow!(e))
3796    }
3797
3798    pub fn available_toolchains(
3799        &self,
3800        path: ProjectPath,
3801        language_name: LanguageName,
3802        cx: &App,
3803    ) -> Task<Option<Toolchains>> {
3804        if let Some(toolchain_store) = self.toolchain_store.as_ref().map(Entity::downgrade) {
3805            cx.spawn(async move |cx| {
3806                toolchain_store
3807                    .update(cx, |this, cx| this.list_toolchains(path, language_name, cx))
3808                    .ok()?
3809                    .await
3810            })
3811        } else {
3812            Task::ready(None)
3813        }
3814    }
3815
3816    pub async fn toolchain_metadata(
3817        languages: Arc<LanguageRegistry>,
3818        language_name: LanguageName,
3819    ) -> Option<ToolchainMetadata> {
3820        languages
3821            .language_for_name(language_name.as_ref())
3822            .await
3823            .ok()?
3824            .toolchain_lister()
3825            .map(|lister| lister.meta())
3826    }
3827
3828    pub fn add_toolchain(
3829        &self,
3830        toolchain: Toolchain,
3831        scope: ToolchainScope,
3832        cx: &mut Context<Self>,
3833    ) {
3834        maybe!({
3835            self.toolchain_store.as_ref()?.update(cx, |this, cx| {
3836                this.add_toolchain(toolchain, scope, cx);
3837            });
3838            Some(())
3839        });
3840    }
3841
3842    pub fn remove_toolchain(
3843        &self,
3844        toolchain: Toolchain,
3845        scope: ToolchainScope,
3846        cx: &mut Context<Self>,
3847    ) {
3848        maybe!({
3849            self.toolchain_store.as_ref()?.update(cx, |this, cx| {
3850                this.remove_toolchain(toolchain, scope, cx);
3851            });
3852            Some(())
3853        });
3854    }
3855
3856    pub fn user_toolchains(
3857        &self,
3858        cx: &App,
3859    ) -> Option<BTreeMap<ToolchainScope, IndexSet<Toolchain>>> {
3860        Some(self.toolchain_store.as_ref()?.read(cx).user_toolchains())
3861    }
3862
3863    pub fn resolve_toolchain(
3864        &self,
3865        path: PathBuf,
3866        language_name: LanguageName,
3867        cx: &App,
3868    ) -> Task<Result<Toolchain>> {
3869        if let Some(toolchain_store) = self.toolchain_store.as_ref().map(Entity::downgrade) {
3870            cx.spawn(async move |cx| {
3871                toolchain_store
3872                    .update(cx, |this, cx| {
3873                        this.resolve_toolchain(path, language_name, cx)
3874                    })?
3875                    .await
3876            })
3877        } else {
3878            Task::ready(Err(anyhow!("This project does not support toolchains")))
3879        }
3880    }
3881
3882    pub fn toolchain_store(&self) -> Option<Entity<ToolchainStore>> {
3883        self.toolchain_store.clone()
3884    }
3885    pub fn activate_toolchain(
3886        &self,
3887        path: ProjectPath,
3888        toolchain: Toolchain,
3889        cx: &mut App,
3890    ) -> Task<Option<()>> {
3891        let Some(toolchain_store) = self.toolchain_store.clone() else {
3892            return Task::ready(None);
3893        };
3894        toolchain_store.update(cx, |this, cx| this.activate_toolchain(path, toolchain, cx))
3895    }
3896    pub fn active_toolchain(
3897        &self,
3898        path: ProjectPath,
3899        language_name: LanguageName,
3900        cx: &App,
3901    ) -> Task<Option<Toolchain>> {
3902        let Some(toolchain_store) = self.toolchain_store.clone() else {
3903            return Task::ready(None);
3904        };
3905        toolchain_store
3906            .read(cx)
3907            .active_toolchain(path, language_name, cx)
3908    }
3909    pub fn language_server_statuses<'a>(
3910        &'a self,
3911        cx: &'a App,
3912    ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
3913        self.lsp_store.read(cx).language_server_statuses()
3914    }
3915
3916    pub fn last_formatting_failure<'a>(&self, cx: &'a App) -> Option<&'a str> {
3917        self.lsp_store.read(cx).last_formatting_failure()
3918    }
3919
3920    pub fn reset_last_formatting_failure(&self, cx: &mut App) {
3921        self.lsp_store
3922            .update(cx, |store, _| store.reset_last_formatting_failure());
3923    }
3924
3925    pub fn reload_buffers(
3926        &self,
3927        buffers: HashSet<Entity<Buffer>>,
3928        push_to_history: bool,
3929        cx: &mut Context<Self>,
3930    ) -> Task<Result<ProjectTransaction>> {
3931        self.buffer_store.update(cx, |buffer_store, cx| {
3932            buffer_store.reload_buffers(buffers, push_to_history, cx)
3933        })
3934    }
3935
3936    pub fn reload_images(
3937        &self,
3938        images: HashSet<Entity<ImageItem>>,
3939        cx: &mut Context<Self>,
3940    ) -> Task<Result<()>> {
3941        self.image_store
3942            .update(cx, |image_store, cx| image_store.reload_images(images, cx))
3943    }
3944
3945    pub fn format(
3946        &mut self,
3947        buffers: HashSet<Entity<Buffer>>,
3948        target: LspFormatTarget,
3949        push_to_history: bool,
3950        trigger: lsp_store::FormatTrigger,
3951        cx: &mut Context<Project>,
3952    ) -> Task<anyhow::Result<ProjectTransaction>> {
3953        self.lsp_store.update(cx, |lsp_store, cx| {
3954            lsp_store.format(buffers, target, push_to_history, trigger, cx)
3955        })
3956    }
3957
3958    pub fn definitions<T: ToPointUtf16>(
3959        &mut self,
3960        buffer: &Entity<Buffer>,
3961        position: T,
3962        cx: &mut Context<Self>,
3963    ) -> Task<Result<Option<Vec<LocationLink>>>> {
3964        let position = position.to_point_utf16(buffer.read(cx));
3965        let guard = self.retain_remotely_created_models(cx);
3966        let task = self.lsp_store.update(cx, |lsp_store, cx| {
3967            lsp_store.definitions(buffer, position, cx)
3968        });
3969        cx.background_spawn(async move {
3970            let result = task.await;
3971            drop(guard);
3972            result
3973        })
3974    }
3975
3976    pub fn declarations<T: ToPointUtf16>(
3977        &mut self,
3978        buffer: &Entity<Buffer>,
3979        position: T,
3980        cx: &mut Context<Self>,
3981    ) -> Task<Result<Option<Vec<LocationLink>>>> {
3982        let position = position.to_point_utf16(buffer.read(cx));
3983        let guard = self.retain_remotely_created_models(cx);
3984        let task = self.lsp_store.update(cx, |lsp_store, cx| {
3985            lsp_store.declarations(buffer, position, cx)
3986        });
3987        cx.background_spawn(async move {
3988            let result = task.await;
3989            drop(guard);
3990            result
3991        })
3992    }
3993
3994    pub fn type_definitions<T: ToPointUtf16>(
3995        &mut self,
3996        buffer: &Entity<Buffer>,
3997        position: T,
3998        cx: &mut Context<Self>,
3999    ) -> Task<Result<Option<Vec<LocationLink>>>> {
4000        let position = position.to_point_utf16(buffer.read(cx));
4001        let guard = self.retain_remotely_created_models(cx);
4002        let task = self.lsp_store.update(cx, |lsp_store, cx| {
4003            lsp_store.type_definitions(buffer, position, cx)
4004        });
4005        cx.background_spawn(async move {
4006            let result = task.await;
4007            drop(guard);
4008            result
4009        })
4010    }
4011
4012    pub fn implementations<T: ToPointUtf16>(
4013        &mut self,
4014        buffer: &Entity<Buffer>,
4015        position: T,
4016        cx: &mut Context<Self>,
4017    ) -> Task<Result<Option<Vec<LocationLink>>>> {
4018        let position = position.to_point_utf16(buffer.read(cx));
4019        let guard = self.retain_remotely_created_models(cx);
4020        let task = self.lsp_store.update(cx, |lsp_store, cx| {
4021            lsp_store.implementations(buffer, position, cx)
4022        });
4023        cx.background_spawn(async move {
4024            let result = task.await;
4025            drop(guard);
4026            result
4027        })
4028    }
4029
4030    pub fn references<T: ToPointUtf16>(
4031        &mut self,
4032        buffer: &Entity<Buffer>,
4033        position: T,
4034        cx: &mut Context<Self>,
4035    ) -> Task<Result<Option<Vec<Location>>>> {
4036        let position = position.to_point_utf16(buffer.read(cx));
4037        let guard = self.retain_remotely_created_models(cx);
4038        let task = self.lsp_store.update(cx, |lsp_store, cx| {
4039            lsp_store.references(buffer, position, cx)
4040        });
4041        cx.background_spawn(async move {
4042            let result = task.await;
4043            drop(guard);
4044            result
4045        })
4046    }
4047
4048    pub fn document_highlights<T: ToPointUtf16>(
4049        &mut self,
4050        buffer: &Entity<Buffer>,
4051        position: T,
4052        cx: &mut Context<Self>,
4053    ) -> Task<Result<Vec<DocumentHighlight>>> {
4054        let position = position.to_point_utf16(buffer.read(cx));
4055        self.request_lsp(
4056            buffer.clone(),
4057            LanguageServerToQuery::FirstCapable,
4058            GetDocumentHighlights { position },
4059            cx,
4060        )
4061    }
4062
4063    pub fn document_symbols(
4064        &mut self,
4065        buffer: &Entity<Buffer>,
4066        cx: &mut Context<Self>,
4067    ) -> Task<Result<Vec<DocumentSymbol>>> {
4068        self.request_lsp(
4069            buffer.clone(),
4070            LanguageServerToQuery::FirstCapable,
4071            GetDocumentSymbols,
4072            cx,
4073        )
4074    }
4075
4076    pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
4077        self.lsp_store
4078            .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
4079    }
4080
4081    pub fn open_buffer_for_symbol(
4082        &mut self,
4083        symbol: &Symbol,
4084        cx: &mut Context<Self>,
4085    ) -> Task<Result<Entity<Buffer>>> {
4086        self.lsp_store.update(cx, |lsp_store, cx| {
4087            lsp_store.open_buffer_for_symbol(symbol, cx)
4088        })
4089    }
4090
4091    pub fn open_server_settings(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
4092        let guard = self.retain_remotely_created_models(cx);
4093        let Some(remote) = self.remote_client.as_ref() else {
4094            return Task::ready(Err(anyhow!("not an ssh project")));
4095        };
4096
4097        let proto_client = remote.read(cx).proto_client();
4098
4099        cx.spawn(async move |project, cx| {
4100            let buffer = proto_client
4101                .request(proto::OpenServerSettings {
4102                    project_id: REMOTE_SERVER_PROJECT_ID,
4103                })
4104                .await?;
4105
4106            let buffer = project
4107                .update(cx, |project, cx| {
4108                    project.buffer_store.update(cx, |buffer_store, cx| {
4109                        anyhow::Ok(
4110                            buffer_store
4111                                .wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx),
4112                        )
4113                    })
4114                })??
4115                .await;
4116
4117            drop(guard);
4118            buffer
4119        })
4120    }
4121
4122    pub fn open_local_buffer_via_lsp(
4123        &mut self,
4124        abs_path: lsp::Uri,
4125        language_server_id: LanguageServerId,
4126        cx: &mut Context<Self>,
4127    ) -> Task<Result<Entity<Buffer>>> {
4128        self.lsp_store.update(cx, |lsp_store, cx| {
4129            lsp_store.open_local_buffer_via_lsp(abs_path, language_server_id, cx)
4130        })
4131    }
4132
4133    pub fn hover<T: ToPointUtf16>(
4134        &self,
4135        buffer: &Entity<Buffer>,
4136        position: T,
4137        cx: &mut Context<Self>,
4138    ) -> Task<Option<Vec<Hover>>> {
4139        let position = position.to_point_utf16(buffer.read(cx));
4140        self.lsp_store
4141            .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
4142    }
4143
4144    pub fn linked_edits(
4145        &self,
4146        buffer: &Entity<Buffer>,
4147        position: Anchor,
4148        cx: &mut Context<Self>,
4149    ) -> Task<Result<Vec<Range<Anchor>>>> {
4150        self.lsp_store.update(cx, |lsp_store, cx| {
4151            lsp_store.linked_edits(buffer, position, cx)
4152        })
4153    }
4154
4155    pub fn completions<T: ToOffset + ToPointUtf16>(
4156        &self,
4157        buffer: &Entity<Buffer>,
4158        position: T,
4159        context: CompletionContext,
4160        cx: &mut Context<Self>,
4161    ) -> Task<Result<Vec<CompletionResponse>>> {
4162        let position = position.to_point_utf16(buffer.read(cx));
4163        self.lsp_store.update(cx, |lsp_store, cx| {
4164            lsp_store.completions(buffer, position, context, cx)
4165        })
4166    }
4167
4168    pub fn code_actions<T: Clone + ToOffset>(
4169        &mut self,
4170        buffer_handle: &Entity<Buffer>,
4171        range: Range<T>,
4172        kinds: Option<Vec<CodeActionKind>>,
4173        cx: &mut Context<Self>,
4174    ) -> Task<Result<Option<Vec<CodeAction>>>> {
4175        let buffer = buffer_handle.read(cx);
4176        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
4177        self.lsp_store.update(cx, |lsp_store, cx| {
4178            lsp_store.code_actions(buffer_handle, range, kinds, cx)
4179        })
4180    }
4181
4182    pub fn code_lens_actions<T: Clone + ToOffset>(
4183        &mut self,
4184        buffer: &Entity<Buffer>,
4185        range: Range<T>,
4186        cx: &mut Context<Self>,
4187    ) -> Task<Result<Option<Vec<CodeAction>>>> {
4188        let snapshot = buffer.read(cx).snapshot();
4189        let range = range.to_point(&snapshot);
4190        let range_start = snapshot.anchor_before(range.start);
4191        let range_end = if range.start == range.end {
4192            range_start
4193        } else {
4194            snapshot.anchor_after(range.end)
4195        };
4196        let range = range_start..range_end;
4197        let code_lens_actions = self
4198            .lsp_store
4199            .update(cx, |lsp_store, cx| lsp_store.code_lens_actions(buffer, cx));
4200
4201        cx.background_spawn(async move {
4202            let mut code_lens_actions = code_lens_actions
4203                .await
4204                .map_err(|e| anyhow!("code lens fetch failed: {e:#}"))?;
4205            if let Some(code_lens_actions) = &mut code_lens_actions {
4206                code_lens_actions.retain(|code_lens_action| {
4207                    range
4208                        .start
4209                        .cmp(&code_lens_action.range.start, &snapshot)
4210                        .is_ge()
4211                        && range
4212                            .end
4213                            .cmp(&code_lens_action.range.end, &snapshot)
4214                            .is_le()
4215                });
4216            }
4217            Ok(code_lens_actions)
4218        })
4219    }
4220
4221    pub fn apply_code_action(
4222        &self,
4223        buffer_handle: Entity<Buffer>,
4224        action: CodeAction,
4225        push_to_history: bool,
4226        cx: &mut Context<Self>,
4227    ) -> Task<Result<ProjectTransaction>> {
4228        self.lsp_store.update(cx, |lsp_store, cx| {
4229            lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
4230        })
4231    }
4232
4233    pub fn apply_code_action_kind(
4234        &self,
4235        buffers: HashSet<Entity<Buffer>>,
4236        kind: CodeActionKind,
4237        push_to_history: bool,
4238        cx: &mut Context<Self>,
4239    ) -> Task<Result<ProjectTransaction>> {
4240        self.lsp_store.update(cx, |lsp_store, cx| {
4241            lsp_store.apply_code_action_kind(buffers, kind, push_to_history, cx)
4242        })
4243    }
4244
4245    pub fn prepare_rename<T: ToPointUtf16>(
4246        &mut self,
4247        buffer: Entity<Buffer>,
4248        position: T,
4249        cx: &mut Context<Self>,
4250    ) -> Task<Result<PrepareRenameResponse>> {
4251        let position = position.to_point_utf16(buffer.read(cx));
4252        self.request_lsp(
4253            buffer,
4254            LanguageServerToQuery::FirstCapable,
4255            PrepareRename { position },
4256            cx,
4257        )
4258    }
4259
4260    pub fn perform_rename<T: ToPointUtf16>(
4261        &mut self,
4262        buffer: Entity<Buffer>,
4263        position: T,
4264        new_name: String,
4265        cx: &mut Context<Self>,
4266    ) -> Task<Result<ProjectTransaction>> {
4267        let push_to_history = true;
4268        let position = position.to_point_utf16(buffer.read(cx));
4269        self.request_lsp(
4270            buffer,
4271            LanguageServerToQuery::FirstCapable,
4272            PerformRename {
4273                position,
4274                new_name,
4275                push_to_history,
4276            },
4277            cx,
4278        )
4279    }
4280
4281    pub fn on_type_format<T: ToPointUtf16>(
4282        &mut self,
4283        buffer: Entity<Buffer>,
4284        position: T,
4285        trigger: String,
4286        push_to_history: bool,
4287        cx: &mut Context<Self>,
4288    ) -> Task<Result<Option<Transaction>>> {
4289        self.lsp_store.update(cx, |lsp_store, cx| {
4290            lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
4291        })
4292    }
4293
4294    pub fn inline_values(
4295        &mut self,
4296        session: Entity<Session>,
4297        active_stack_frame: ActiveStackFrame,
4298        buffer_handle: Entity<Buffer>,
4299        range: Range<text::Anchor>,
4300        cx: &mut Context<Self>,
4301    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
4302        let snapshot = buffer_handle.read(cx).snapshot();
4303
4304        let captures =
4305            snapshot.debug_variables_query(Anchor::min_for_buffer(snapshot.remote_id())..range.end);
4306
4307        let row = snapshot
4308            .summary_for_anchor::<text::PointUtf16>(&range.end)
4309            .row as usize;
4310
4311        let inline_value_locations = provide_inline_values(captures, &snapshot, row);
4312
4313        let stack_frame_id = active_stack_frame.stack_frame_id;
4314        cx.spawn(async move |this, cx| {
4315            this.update(cx, |project, cx| {
4316                project.dap_store().update(cx, |dap_store, cx| {
4317                    dap_store.resolve_inline_value_locations(
4318                        session,
4319                        stack_frame_id,
4320                        buffer_handle,
4321                        inline_value_locations,
4322                        cx,
4323                    )
4324                })
4325            })?
4326            .await
4327        })
4328    }
4329
4330    fn search_impl(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> SearchResultsHandle {
4331        let client: Option<(AnyProtoClient, _)> = if let Some(ssh_client) = &self.remote_client {
4332            Some((ssh_client.read(cx).proto_client(), 0))
4333        } else if let Some(remote_id) = self.remote_id() {
4334            self.is_local()
4335                .not()
4336                .then(|| (self.collab_client.clone().into(), remote_id))
4337        } else {
4338            None
4339        };
4340        let searcher = if query.is_opened_only() {
4341            project_search::Search::open_buffers_only(
4342                self.buffer_store.clone(),
4343                self.worktree_store.clone(),
4344                project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4345            )
4346        } else {
4347            match client {
4348                Some((client, remote_id)) => project_search::Search::remote(
4349                    self.buffer_store.clone(),
4350                    self.worktree_store.clone(),
4351                    project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4352                    (client, remote_id, self.remotely_created_models.clone()),
4353                ),
4354                None => project_search::Search::local(
4355                    self.fs.clone(),
4356                    self.buffer_store.clone(),
4357                    self.worktree_store.clone(),
4358                    project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4359                    cx,
4360                ),
4361            }
4362        };
4363        searcher.into_handle(query, cx)
4364    }
4365
4366    pub fn search(
4367        &mut self,
4368        query: SearchQuery,
4369        cx: &mut Context<Self>,
4370    ) -> SearchResults<SearchResult> {
4371        self.search_impl(query, cx).results(cx)
4372    }
4373
4374    pub fn request_lsp<R: LspCommand>(
4375        &mut self,
4376        buffer_handle: Entity<Buffer>,
4377        server: LanguageServerToQuery,
4378        request: R,
4379        cx: &mut Context<Self>,
4380    ) -> Task<Result<R::Response>>
4381    where
4382        <R::LspRequest as lsp::request::Request>::Result: Send,
4383        <R::LspRequest as lsp::request::Request>::Params: Send,
4384    {
4385        let guard = self.retain_remotely_created_models(cx);
4386        let task = self.lsp_store.update(cx, |lsp_store, cx| {
4387            lsp_store.request_lsp(buffer_handle, server, request, cx)
4388        });
4389        cx.background_spawn(async move {
4390            let result = task.await;
4391            drop(guard);
4392            result
4393        })
4394    }
4395
4396    /// Move a worktree to a new position in the worktree order.
4397    ///
4398    /// The worktree will moved to the opposite side of the destination worktree.
4399    ///
4400    /// # Example
4401    ///
4402    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
4403    /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
4404    ///
4405    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
4406    /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
4407    ///
4408    /// # Errors
4409    ///
4410    /// An error will be returned if the worktree or destination worktree are not found.
4411    pub fn move_worktree(
4412        &mut self,
4413        source: WorktreeId,
4414        destination: WorktreeId,
4415        cx: &mut Context<Self>,
4416    ) -> Result<()> {
4417        self.worktree_store.update(cx, |worktree_store, cx| {
4418            worktree_store.move_worktree(source, destination, cx)
4419        })
4420    }
4421
4422    /// Attempts to convert the input path to a WSL path if this is a wsl remote project and the input path is a host windows path.
4423    pub fn try_windows_path_to_wsl(
4424        &self,
4425        abs_path: &Path,
4426        cx: &App,
4427    ) -> impl Future<Output = Result<PathBuf>> + use<> {
4428        let fut = if cfg!(windows)
4429            && let (
4430                ProjectClientState::Local | ProjectClientState::Shared { .. },
4431                Some(remote_client),
4432            ) = (&self.client_state, &self.remote_client)
4433            && let RemoteConnectionOptions::Wsl(wsl) = remote_client.read(cx).connection_options()
4434        {
4435            Either::Left(wsl.abs_windows_path_to_wsl_path(abs_path))
4436        } else {
4437            Either::Right(abs_path.to_owned())
4438        };
4439        async move {
4440            match fut {
4441                Either::Left(fut) => fut.await.map(Into::into),
4442                Either::Right(path) => Ok(path),
4443            }
4444        }
4445    }
4446
4447    pub fn find_or_create_worktree(
4448        &mut self,
4449        abs_path: impl AsRef<Path>,
4450        visible: bool,
4451        cx: &mut Context<Self>,
4452    ) -> Task<Result<(Entity<Worktree>, Arc<RelPath>)>> {
4453        self.worktree_store.update(cx, |worktree_store, cx| {
4454            worktree_store.find_or_create_worktree(abs_path, visible, cx)
4455        })
4456    }
4457
4458    pub fn find_worktree(
4459        &self,
4460        abs_path: &Path,
4461        cx: &App,
4462    ) -> Option<(Entity<Worktree>, Arc<RelPath>)> {
4463        self.worktree_store.read(cx).find_worktree(abs_path, cx)
4464    }
4465
4466    pub fn is_shared(&self) -> bool {
4467        match &self.client_state {
4468            ProjectClientState::Shared { .. } => true,
4469            ProjectClientState::Local => false,
4470            ProjectClientState::Remote { .. } => true,
4471        }
4472    }
4473
4474    /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
4475    pub fn resolve_path_in_buffer(
4476        &self,
4477        path: &str,
4478        buffer: &Entity<Buffer>,
4479        cx: &mut Context<Self>,
4480    ) -> Task<Option<ResolvedPath>> {
4481        if util::paths::is_absolute(path, self.path_style(cx)) || path.starts_with("~") {
4482            self.resolve_abs_path(path, cx)
4483        } else {
4484            self.resolve_path_in_worktrees(path, buffer, cx)
4485        }
4486    }
4487
4488    pub fn resolve_abs_file_path(
4489        &self,
4490        path: &str,
4491        cx: &mut Context<Self>,
4492    ) -> Task<Option<ResolvedPath>> {
4493        let resolve_task = self.resolve_abs_path(path, cx);
4494        cx.background_spawn(async move {
4495            let resolved_path = resolve_task.await;
4496            resolved_path.filter(|path| path.is_file())
4497        })
4498    }
4499
4500    pub fn resolve_abs_path(&self, path: &str, cx: &App) -> Task<Option<ResolvedPath>> {
4501        if self.is_local() {
4502            let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
4503            let fs = self.fs.clone();
4504            cx.background_spawn(async move {
4505                let metadata = fs.metadata(&expanded).await.ok().flatten();
4506
4507                metadata.map(|metadata| ResolvedPath::AbsPath {
4508                    path: expanded.to_string_lossy().into_owned(),
4509                    is_dir: metadata.is_dir,
4510                })
4511            })
4512        } else if let Some(ssh_client) = self.remote_client.as_ref() {
4513            let request = ssh_client
4514                .read(cx)
4515                .proto_client()
4516                .request(proto::GetPathMetadata {
4517                    project_id: REMOTE_SERVER_PROJECT_ID,
4518                    path: path.into(),
4519                });
4520            cx.background_spawn(async move {
4521                let response = request.await.log_err()?;
4522                if response.exists {
4523                    Some(ResolvedPath::AbsPath {
4524                        path: response.path,
4525                        is_dir: response.is_dir,
4526                    })
4527                } else {
4528                    None
4529                }
4530            })
4531        } else {
4532            Task::ready(None)
4533        }
4534    }
4535
4536    fn resolve_path_in_worktrees(
4537        &self,
4538        path: &str,
4539        buffer: &Entity<Buffer>,
4540        cx: &mut Context<Self>,
4541    ) -> Task<Option<ResolvedPath>> {
4542        let mut candidates = vec![];
4543        let path_style = self.path_style(cx);
4544        if let Ok(path) = RelPath::new(path.as_ref(), path_style) {
4545            candidates.push(path.into_arc());
4546        }
4547
4548        if let Some(file) = buffer.read(cx).file()
4549            && let Some(dir) = file.path().parent()
4550        {
4551            if let Some(joined) = path_style.join(&*dir.display(path_style), path)
4552                && let Some(joined) = RelPath::new(joined.as_ref(), path_style).ok()
4553            {
4554                candidates.push(joined.into_arc());
4555            }
4556        }
4557
4558        let buffer_worktree_id = buffer.read(cx).file().map(|file| file.worktree_id(cx));
4559        let worktrees_with_ids: Vec<_> = self
4560            .worktrees(cx)
4561            .map(|worktree| {
4562                let id = worktree.read(cx).id();
4563                (worktree, id)
4564            })
4565            .collect();
4566
4567        cx.spawn(async move |_, cx| {
4568            if let Some(buffer_worktree_id) = buffer_worktree_id
4569                && let Some((worktree, _)) = worktrees_with_ids
4570                    .iter()
4571                    .find(|(_, id)| *id == buffer_worktree_id)
4572            {
4573                for candidate in candidates.iter() {
4574                    if let Some(path) = Self::resolve_path_in_worktree(worktree, candidate, cx) {
4575                        return Some(path);
4576                    }
4577                }
4578            }
4579            for (worktree, id) in worktrees_with_ids {
4580                if Some(id) == buffer_worktree_id {
4581                    continue;
4582                }
4583                for candidate in candidates.iter() {
4584                    if let Some(path) = Self::resolve_path_in_worktree(&worktree, candidate, cx) {
4585                        return Some(path);
4586                    }
4587                }
4588            }
4589            None
4590        })
4591    }
4592
4593    fn resolve_path_in_worktree(
4594        worktree: &Entity<Worktree>,
4595        path: &RelPath,
4596        cx: &mut AsyncApp,
4597    ) -> Option<ResolvedPath> {
4598        worktree.read_with(cx, |worktree, _| {
4599            worktree.entry_for_path(path).map(|entry| {
4600                let project_path = ProjectPath {
4601                    worktree_id: worktree.id(),
4602                    path: entry.path.clone(),
4603                };
4604                ResolvedPath::ProjectPath {
4605                    project_path,
4606                    is_dir: entry.is_dir(),
4607                }
4608            })
4609        })
4610    }
4611
4612    pub fn list_directory(
4613        &self,
4614        query: String,
4615        cx: &mut Context<Self>,
4616    ) -> Task<Result<Vec<DirectoryItem>>> {
4617        if self.is_local() {
4618            DirectoryLister::Local(cx.entity(), self.fs.clone()).list_directory(query, cx)
4619        } else if let Some(session) = self.remote_client.as_ref() {
4620            let request = proto::ListRemoteDirectory {
4621                dev_server_id: REMOTE_SERVER_PROJECT_ID,
4622                path: query,
4623                config: Some(proto::ListRemoteDirectoryConfig { is_dir: true }),
4624            };
4625
4626            let response = session.read(cx).proto_client().request(request);
4627            cx.background_spawn(async move {
4628                let proto::ListRemoteDirectoryResponse {
4629                    entries,
4630                    entry_info,
4631                } = response.await?;
4632                Ok(entries
4633                    .into_iter()
4634                    .zip(entry_info)
4635                    .map(|(entry, info)| DirectoryItem {
4636                        path: PathBuf::from(entry),
4637                        is_dir: info.is_dir,
4638                    })
4639                    .collect())
4640            })
4641        } else {
4642            Task::ready(Err(anyhow!("cannot list directory in remote project")))
4643        }
4644    }
4645
4646    pub fn create_worktree(
4647        &mut self,
4648        abs_path: impl AsRef<Path>,
4649        visible: bool,
4650        cx: &mut Context<Self>,
4651    ) -> Task<Result<Entity<Worktree>>> {
4652        self.worktree_store.update(cx, |worktree_store, cx| {
4653            worktree_store.create_worktree(abs_path, visible, cx)
4654        })
4655    }
4656
4657    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
4658        self.worktree_store.update(cx, |worktree_store, cx| {
4659            worktree_store.remove_worktree(id_to_remove, cx);
4660        });
4661    }
4662
4663    fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
4664        self.worktree_store.update(cx, |worktree_store, cx| {
4665            worktree_store.add(worktree, cx);
4666        });
4667    }
4668
4669    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
4670        let new_active_entry = entry.and_then(|project_path| {
4671            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4672            let entry = worktree.read(cx).entry_for_path(&project_path.path)?;
4673            Some(entry.id)
4674        });
4675        if new_active_entry != self.active_entry {
4676            self.active_entry = new_active_entry;
4677            self.lsp_store.update(cx, |lsp_store, _| {
4678                lsp_store.set_active_entry(new_active_entry);
4679            });
4680            cx.emit(Event::ActiveEntryChanged(new_active_entry));
4681        }
4682    }
4683
4684    pub fn language_servers_running_disk_based_diagnostics<'a>(
4685        &'a self,
4686        cx: &'a App,
4687    ) -> impl Iterator<Item = LanguageServerId> + 'a {
4688        self.lsp_store
4689            .read(cx)
4690            .language_servers_running_disk_based_diagnostics()
4691    }
4692
4693    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
4694        self.lsp_store
4695            .read(cx)
4696            .diagnostic_summary(include_ignored, cx)
4697    }
4698
4699    /// Returns a summary of the diagnostics for the provided project path only.
4700    pub fn diagnostic_summary_for_path(&self, path: &ProjectPath, cx: &App) -> DiagnosticSummary {
4701        self.lsp_store
4702            .read(cx)
4703            .diagnostic_summary_for_path(path, cx)
4704    }
4705
4706    pub fn diagnostic_summaries<'a>(
4707        &'a self,
4708        include_ignored: bool,
4709        cx: &'a App,
4710    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4711        self.lsp_store
4712            .read(cx)
4713            .diagnostic_summaries(include_ignored, cx)
4714    }
4715
4716    pub fn active_entry(&self) -> Option<ProjectEntryId> {
4717        self.active_entry
4718    }
4719
4720    pub fn entry_for_path<'a>(&'a self, path: &ProjectPath, cx: &'a App) -> Option<&'a Entry> {
4721        self.worktree_store.read(cx).entry_for_path(path, cx)
4722    }
4723
4724    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
4725        let worktree = self.worktree_for_entry(entry_id, cx)?;
4726        let worktree = worktree.read(cx);
4727        let worktree_id = worktree.id();
4728        let path = worktree.entry_for_id(entry_id)?.path.clone();
4729        Some(ProjectPath { worktree_id, path })
4730    }
4731
4732    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4733        Some(
4734            self.worktree_for_id(project_path.worktree_id, cx)?
4735                .read(cx)
4736                .absolutize(&project_path.path),
4737        )
4738    }
4739
4740    /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
4741    /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
4742    /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
4743    /// the first visible worktree that has an entry for that relative path.
4744    ///
4745    /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
4746    /// root name from paths.
4747    ///
4748    /// # Arguments
4749    ///
4750    /// * `path` - An absolute path, or a full path that starts with a worktree root name, or a
4751    ///   relative path within a visible worktree.
4752    /// * `cx` - A reference to the `AppContext`.
4753    ///
4754    /// # Returns
4755    ///
4756    /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
4757    pub fn find_project_path(&self, path: impl AsRef<Path>, cx: &App) -> Option<ProjectPath> {
4758        let path_style = self.path_style(cx);
4759        let path = path.as_ref();
4760        let worktree_store = self.worktree_store.read(cx);
4761
4762        if is_absolute(&path.to_string_lossy(), path_style) {
4763            for worktree in worktree_store.visible_worktrees(cx) {
4764                let worktree_abs_path = worktree.read(cx).abs_path();
4765
4766                if let Ok(relative_path) = path.strip_prefix(worktree_abs_path)
4767                    && let Ok(path) = RelPath::new(relative_path, path_style)
4768                {
4769                    return Some(ProjectPath {
4770                        worktree_id: worktree.read(cx).id(),
4771                        path: path.into_arc(),
4772                    });
4773                }
4774            }
4775        } else {
4776            for worktree in worktree_store.visible_worktrees(cx) {
4777                let worktree = worktree.read(cx);
4778                if let Ok(rel_path) = RelPath::new(path, path_style) {
4779                    if let Some(entry) = worktree.entry_for_path(&rel_path) {
4780                        return Some(ProjectPath {
4781                            worktree_id: worktree.id(),
4782                            path: entry.path.clone(),
4783                        });
4784                    }
4785                }
4786            }
4787
4788            for worktree in worktree_store.visible_worktrees(cx) {
4789                let worktree_root_name = worktree.read(cx).root_name();
4790                if let Ok(relative_path) = path.strip_prefix(worktree_root_name.as_std_path())
4791                    && let Ok(path) = RelPath::new(relative_path, path_style)
4792                {
4793                    return Some(ProjectPath {
4794                        worktree_id: worktree.read(cx).id(),
4795                        path: path.into_arc(),
4796                    });
4797                }
4798            }
4799        }
4800
4801        None
4802    }
4803
4804    /// If there's only one visible worktree, returns the given worktree-relative path with no prefix.
4805    ///
4806    /// Otherwise, returns the full path for the project path (obtained by prefixing the worktree-relative path with the name of the worktree).
4807    pub fn short_full_path_for_project_path(
4808        &self,
4809        project_path: &ProjectPath,
4810        cx: &App,
4811    ) -> Option<String> {
4812        let path_style = self.path_style(cx);
4813        if self.visible_worktrees(cx).take(2).count() < 2 {
4814            return Some(project_path.path.display(path_style).to_string());
4815        }
4816        self.worktree_for_id(project_path.worktree_id, cx)
4817            .map(|worktree| {
4818                let worktree_name = worktree.read(cx).root_name();
4819                worktree_name
4820                    .join(&project_path.path)
4821                    .display(path_style)
4822                    .to_string()
4823            })
4824    }
4825
4826    pub fn project_path_for_absolute_path(&self, abs_path: &Path, cx: &App) -> Option<ProjectPath> {
4827        self.worktree_store
4828            .read(cx)
4829            .project_path_for_absolute_path(abs_path, cx)
4830    }
4831
4832    pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4833        Some(
4834            self.worktree_for_id(project_path.worktree_id, cx)?
4835                .read(cx)
4836                .abs_path()
4837                .to_path_buf(),
4838        )
4839    }
4840
4841    pub fn blame_buffer(
4842        &self,
4843        buffer: &Entity<Buffer>,
4844        version: Option<clock::Global>,
4845        cx: &mut App,
4846    ) -> Task<Result<Option<Blame>>> {
4847        self.git_store.update(cx, |git_store, cx| {
4848            git_store.blame_buffer(buffer, version, cx)
4849        })
4850    }
4851
4852    pub fn get_permalink_to_line(
4853        &self,
4854        buffer: &Entity<Buffer>,
4855        selection: Range<u32>,
4856        cx: &mut App,
4857    ) -> Task<Result<url::Url>> {
4858        self.git_store.update(cx, |git_store, cx| {
4859            git_store.get_permalink_to_line(buffer, selection, cx)
4860        })
4861    }
4862
4863    // RPC message handlers
4864
4865    async fn handle_unshare_project(
4866        this: Entity<Self>,
4867        _: TypedEnvelope<proto::UnshareProject>,
4868        mut cx: AsyncApp,
4869    ) -> Result<()> {
4870        this.update(&mut cx, |this, cx| {
4871            if this.is_local() || this.is_via_remote_server() {
4872                this.unshare(cx)?;
4873            } else {
4874                this.disconnected_from_host(cx);
4875            }
4876            Ok(())
4877        })
4878    }
4879
4880    async fn handle_add_collaborator(
4881        this: Entity<Self>,
4882        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4883        mut cx: AsyncApp,
4884    ) -> Result<()> {
4885        let collaborator = envelope
4886            .payload
4887            .collaborator
4888            .take()
4889            .context("empty collaborator")?;
4890
4891        let collaborator = Collaborator::from_proto(collaborator)?;
4892        this.update(&mut cx, |this, cx| {
4893            this.buffer_store.update(cx, |buffer_store, _| {
4894                buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
4895            });
4896            this.breakpoint_store.read(cx).broadcast();
4897            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
4898            this.collaborators
4899                .insert(collaborator.peer_id, collaborator);
4900        });
4901
4902        Ok(())
4903    }
4904
4905    async fn handle_update_project_collaborator(
4906        this: Entity<Self>,
4907        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4908        mut cx: AsyncApp,
4909    ) -> Result<()> {
4910        let old_peer_id = envelope
4911            .payload
4912            .old_peer_id
4913            .context("missing old peer id")?;
4914        let new_peer_id = envelope
4915            .payload
4916            .new_peer_id
4917            .context("missing new peer id")?;
4918        this.update(&mut cx, |this, cx| {
4919            let collaborator = this
4920                .collaborators
4921                .remove(&old_peer_id)
4922                .context("received UpdateProjectCollaborator for unknown peer")?;
4923            let is_host = collaborator.is_host;
4924            this.collaborators.insert(new_peer_id, collaborator);
4925
4926            log::info!("peer {} became {}", old_peer_id, new_peer_id,);
4927            this.buffer_store.update(cx, |buffer_store, _| {
4928                buffer_store.update_peer_id(&old_peer_id, new_peer_id)
4929            });
4930
4931            if is_host {
4932                this.buffer_store
4933                    .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
4934                this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
4935                    .unwrap();
4936                cx.emit(Event::HostReshared);
4937            }
4938
4939            cx.emit(Event::CollaboratorUpdated {
4940                old_peer_id,
4941                new_peer_id,
4942            });
4943            Ok(())
4944        })
4945    }
4946
4947    async fn handle_remove_collaborator(
4948        this: Entity<Self>,
4949        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4950        mut cx: AsyncApp,
4951    ) -> Result<()> {
4952        this.update(&mut cx, |this, cx| {
4953            let peer_id = envelope.payload.peer_id.context("invalid peer id")?;
4954            let replica_id = this
4955                .collaborators
4956                .remove(&peer_id)
4957                .with_context(|| format!("unknown peer {peer_id:?}"))?
4958                .replica_id;
4959            this.buffer_store.update(cx, |buffer_store, cx| {
4960                buffer_store.forget_shared_buffers_for(&peer_id);
4961                for buffer in buffer_store.buffers() {
4962                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4963                }
4964            });
4965            this.git_store.update(cx, |git_store, _| {
4966                git_store.forget_shared_diffs_for(&peer_id);
4967            });
4968
4969            cx.emit(Event::CollaboratorLeft(peer_id));
4970            Ok(())
4971        })
4972    }
4973
4974    async fn handle_update_project(
4975        this: Entity<Self>,
4976        envelope: TypedEnvelope<proto::UpdateProject>,
4977        mut cx: AsyncApp,
4978    ) -> Result<()> {
4979        this.update(&mut cx, |this, cx| {
4980            // Don't handle messages that were sent before the response to us joining the project
4981            if envelope.message_id > this.join_project_response_message_id {
4982                cx.update_global::<SettingsStore, _>(|store, cx| {
4983                    for worktree_metadata in &envelope.payload.worktrees {
4984                        store
4985                            .clear_local_settings(WorktreeId::from_proto(worktree_metadata.id), cx)
4986                            .log_err();
4987                    }
4988                });
4989
4990                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4991            }
4992            Ok(())
4993        })
4994    }
4995
4996    async fn handle_toast(
4997        this: Entity<Self>,
4998        envelope: TypedEnvelope<proto::Toast>,
4999        mut cx: AsyncApp,
5000    ) -> Result<()> {
5001        this.update(&mut cx, |_, cx| {
5002            cx.emit(Event::Toast {
5003                notification_id: envelope.payload.notification_id.into(),
5004                message: envelope.payload.message,
5005                link: None,
5006            });
5007            Ok(())
5008        })
5009    }
5010
5011    async fn handle_language_server_prompt_request(
5012        this: Entity<Self>,
5013        envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
5014        mut cx: AsyncApp,
5015    ) -> Result<proto::LanguageServerPromptResponse> {
5016        let (tx, rx) = smol::channel::bounded(1);
5017        let actions: Vec<_> = envelope
5018            .payload
5019            .actions
5020            .into_iter()
5021            .map(|action| MessageActionItem {
5022                title: action,
5023                properties: Default::default(),
5024            })
5025            .collect();
5026        this.update(&mut cx, |_, cx| {
5027            cx.emit(Event::LanguageServerPrompt(
5028                LanguageServerPromptRequest::new(
5029                    proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
5030                    envelope.payload.message,
5031                    actions.clone(),
5032                    envelope.payload.lsp_name,
5033                    tx,
5034                ),
5035            ));
5036
5037            anyhow::Ok(())
5038        })?;
5039
5040        // We drop `this` to avoid holding a reference in this future for too
5041        // long.
5042        // If we keep the reference, we might not drop the `Project` early
5043        // enough when closing a window and it will only get releases on the
5044        // next `flush_effects()` call.
5045        drop(this);
5046
5047        let mut rx = pin!(rx);
5048        let answer = rx.next().await;
5049
5050        Ok(LanguageServerPromptResponse {
5051            action_response: answer.and_then(|answer| {
5052                actions
5053                    .iter()
5054                    .position(|action| *action == answer)
5055                    .map(|index| index as u64)
5056            }),
5057        })
5058    }
5059
5060    async fn handle_hide_toast(
5061        this: Entity<Self>,
5062        envelope: TypedEnvelope<proto::HideToast>,
5063        mut cx: AsyncApp,
5064    ) -> Result<()> {
5065        this.update(&mut cx, |_, cx| {
5066            cx.emit(Event::HideToast {
5067                notification_id: envelope.payload.notification_id.into(),
5068            });
5069            Ok(())
5070        })
5071    }
5072
5073    // Collab sends UpdateWorktree protos as messages
5074    async fn handle_update_worktree(
5075        this: Entity<Self>,
5076        envelope: TypedEnvelope<proto::UpdateWorktree>,
5077        mut cx: AsyncApp,
5078    ) -> Result<()> {
5079        this.update(&mut cx, |project, cx| {
5080            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5081            if let Some(worktree) = project.worktree_for_id(worktree_id, cx) {
5082                worktree.update(cx, |worktree, _| {
5083                    let worktree = worktree.as_remote_mut().unwrap();
5084                    worktree.update_from_remote(envelope.payload);
5085                });
5086            }
5087            Ok(())
5088        })
5089    }
5090
5091    async fn handle_update_buffer_from_remote_server(
5092        this: Entity<Self>,
5093        envelope: TypedEnvelope<proto::UpdateBuffer>,
5094        cx: AsyncApp,
5095    ) -> Result<proto::Ack> {
5096        let buffer_store = this.read_with(&cx, |this, cx| {
5097            if let Some(remote_id) = this.remote_id() {
5098                let mut payload = envelope.payload.clone();
5099                payload.project_id = remote_id;
5100                cx.background_spawn(this.collab_client.request(payload))
5101                    .detach_and_log_err(cx);
5102            }
5103            this.buffer_store.clone()
5104        });
5105        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
5106    }
5107
5108    async fn handle_trust_worktrees(
5109        this: Entity<Self>,
5110        envelope: TypedEnvelope<proto::TrustWorktrees>,
5111        mut cx: AsyncApp,
5112    ) -> Result<proto::Ack> {
5113        if this.read_with(&cx, |project, _| project.is_via_collab()) {
5114            return Ok(proto::Ack {});
5115        }
5116
5117        let trusted_worktrees = cx
5118            .update(|cx| TrustedWorktrees::try_get_global(cx))
5119            .context("missing trusted worktrees")?;
5120        trusted_worktrees.update(&mut cx, |trusted_worktrees, cx| {
5121            trusted_worktrees.trust(
5122                &this.read(cx).worktree_store(),
5123                envelope
5124                    .payload
5125                    .trusted_paths
5126                    .into_iter()
5127                    .filter_map(|proto_path| PathTrust::from_proto(proto_path))
5128                    .collect(),
5129                cx,
5130            );
5131        });
5132        Ok(proto::Ack {})
5133    }
5134
5135    async fn handle_restrict_worktrees(
5136        this: Entity<Self>,
5137        envelope: TypedEnvelope<proto::RestrictWorktrees>,
5138        mut cx: AsyncApp,
5139    ) -> Result<proto::Ack> {
5140        if this.read_with(&cx, |project, _| project.is_via_collab()) {
5141            return Ok(proto::Ack {});
5142        }
5143
5144        let trusted_worktrees = cx
5145            .update(|cx| TrustedWorktrees::try_get_global(cx))
5146            .context("missing trusted worktrees")?;
5147        trusted_worktrees.update(&mut cx, |trusted_worktrees, cx| {
5148            let worktree_store = this.read(cx).worktree_store().downgrade();
5149            let restricted_paths = envelope
5150                .payload
5151                .worktree_ids
5152                .into_iter()
5153                .map(WorktreeId::from_proto)
5154                .map(PathTrust::Worktree)
5155                .collect::<HashSet<_>>();
5156            trusted_worktrees.restrict(worktree_store, restricted_paths, cx);
5157        });
5158        Ok(proto::Ack {})
5159    }
5160
5161    // Goes from host to client.
5162    async fn handle_find_search_candidates_chunk(
5163        this: Entity<Self>,
5164        envelope: TypedEnvelope<proto::FindSearchCandidatesChunk>,
5165        mut cx: AsyncApp,
5166    ) -> Result<proto::Ack> {
5167        let buffer_store = this.read_with(&mut cx, |this, _| this.buffer_store.clone());
5168        BufferStore::handle_find_search_candidates_chunk(buffer_store, envelope, cx).await
5169    }
5170
5171    // Goes from client to host.
5172    async fn handle_find_search_candidates_cancel(
5173        this: Entity<Self>,
5174        envelope: TypedEnvelope<proto::FindSearchCandidatesCancelled>,
5175        mut cx: AsyncApp,
5176    ) -> Result<()> {
5177        let buffer_store = this.read_with(&mut cx, |this, _| this.buffer_store.clone());
5178        BufferStore::handle_find_search_candidates_cancel(buffer_store, envelope, cx).await
5179    }
5180
5181    async fn handle_update_buffer(
5182        this: Entity<Self>,
5183        envelope: TypedEnvelope<proto::UpdateBuffer>,
5184        cx: AsyncApp,
5185    ) -> Result<proto::Ack> {
5186        let buffer_store = this.read_with(&cx, |this, cx| {
5187            if let Some(ssh) = &this.remote_client {
5188                let mut payload = envelope.payload.clone();
5189                payload.project_id = REMOTE_SERVER_PROJECT_ID;
5190                cx.background_spawn(ssh.read(cx).proto_client().request(payload))
5191                    .detach_and_log_err(cx);
5192            }
5193            this.buffer_store.clone()
5194        });
5195        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
5196    }
5197
5198    fn retain_remotely_created_models(
5199        &mut self,
5200        cx: &mut Context<Self>,
5201    ) -> RemotelyCreatedModelGuard {
5202        Self::retain_remotely_created_models_impl(
5203            &self.remotely_created_models,
5204            &self.buffer_store,
5205            &self.worktree_store,
5206            cx,
5207        )
5208    }
5209
5210    fn retain_remotely_created_models_impl(
5211        models: &Arc<Mutex<RemotelyCreatedModels>>,
5212        buffer_store: &Entity<BufferStore>,
5213        worktree_store: &Entity<WorktreeStore>,
5214        cx: &mut App,
5215    ) -> RemotelyCreatedModelGuard {
5216        {
5217            let mut remotely_create_models = models.lock();
5218            if remotely_create_models.retain_count == 0 {
5219                remotely_create_models.buffers = buffer_store.read(cx).buffers().collect();
5220                remotely_create_models.worktrees = worktree_store.read(cx).worktrees().collect();
5221            }
5222            remotely_create_models.retain_count += 1;
5223        }
5224        RemotelyCreatedModelGuard {
5225            remote_models: Arc::downgrade(&models),
5226        }
5227    }
5228
5229    async fn handle_create_buffer_for_peer(
5230        this: Entity<Self>,
5231        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
5232        mut cx: AsyncApp,
5233    ) -> Result<()> {
5234        this.update(&mut cx, |this, cx| {
5235            this.buffer_store.update(cx, |buffer_store, cx| {
5236                buffer_store.handle_create_buffer_for_peer(
5237                    envelope,
5238                    this.replica_id(),
5239                    this.capability(),
5240                    cx,
5241                )
5242            })
5243        })
5244    }
5245
5246    async fn handle_toggle_lsp_logs(
5247        project: Entity<Self>,
5248        envelope: TypedEnvelope<proto::ToggleLspLogs>,
5249        mut cx: AsyncApp,
5250    ) -> Result<()> {
5251        let toggled_log_kind =
5252            match proto::toggle_lsp_logs::LogType::from_i32(envelope.payload.log_type)
5253                .context("invalid log type")?
5254            {
5255                proto::toggle_lsp_logs::LogType::Log => LogKind::Logs,
5256                proto::toggle_lsp_logs::LogType::Trace => LogKind::Trace,
5257                proto::toggle_lsp_logs::LogType::Rpc => LogKind::Rpc,
5258            };
5259        project.update(&mut cx, |_, cx| {
5260            cx.emit(Event::ToggleLspLogs {
5261                server_id: LanguageServerId::from_proto(envelope.payload.server_id),
5262                enabled: envelope.payload.enabled,
5263                toggled_log_kind,
5264            })
5265        });
5266        Ok(())
5267    }
5268
5269    async fn handle_synchronize_buffers(
5270        this: Entity<Self>,
5271        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
5272        mut cx: AsyncApp,
5273    ) -> Result<proto::SynchronizeBuffersResponse> {
5274        let response = this.update(&mut cx, |this, cx| {
5275            let client = this.collab_client.clone();
5276            this.buffer_store.update(cx, |this, cx| {
5277                this.handle_synchronize_buffers(envelope, cx, client)
5278            })
5279        })?;
5280
5281        Ok(response)
5282    }
5283
5284    // Goes from client to host.
5285    async fn handle_search_candidate_buffers(
5286        this: Entity<Self>,
5287        envelope: TypedEnvelope<proto::FindSearchCandidates>,
5288        mut cx: AsyncApp,
5289    ) -> Result<proto::Ack> {
5290        let peer_id = envelope.original_sender_id.unwrap_or(envelope.sender_id);
5291        let message = envelope.payload;
5292        let project_id = message.project_id;
5293        let path_style = this.read_with(&cx, |this, cx| this.path_style(cx));
5294        let query =
5295            SearchQuery::from_proto(message.query.context("missing query field")?, path_style)?;
5296
5297        let handle = message.handle;
5298        let buffer_store = this.read_with(&cx, |this, _| this.buffer_store().clone());
5299        let client = this.read_with(&cx, |this, _| this.client());
5300        let task = cx.spawn(async move |cx| {
5301            let results = this.update(cx, |this, cx| {
5302                this.search_impl(query, cx).matching_buffers(cx)
5303            });
5304            let (batcher, batches) = project_search::AdaptiveBatcher::new(cx.background_executor());
5305            let mut new_matches = Box::pin(results.rx);
5306
5307            let sender_task = cx.background_executor().spawn({
5308                let client = client.clone();
5309                async move {
5310                    let mut batches = std::pin::pin!(batches);
5311                    while let Some(buffer_ids) = batches.next().await {
5312                        client
5313                            .request(proto::FindSearchCandidatesChunk {
5314                                handle,
5315                                peer_id: Some(peer_id),
5316                                project_id,
5317                                variant: Some(
5318                                    proto::find_search_candidates_chunk::Variant::Matches(
5319                                        proto::FindSearchCandidatesMatches { buffer_ids },
5320                                    ),
5321                                ),
5322                            })
5323                            .await?;
5324                    }
5325                    anyhow::Ok(())
5326                }
5327            });
5328
5329            while let Some(buffer) = new_matches.next().await {
5330                let buffer_id = this.update(cx, |this, cx| {
5331                    this.create_buffer_for_peer(&buffer, peer_id, cx).to_proto()
5332                });
5333                batcher.push(buffer_id).await;
5334            }
5335            batcher.flush().await;
5336
5337            sender_task.await?;
5338
5339            let _ = client
5340                .request(proto::FindSearchCandidatesChunk {
5341                    handle,
5342                    peer_id: Some(peer_id),
5343                    project_id,
5344                    variant: Some(proto::find_search_candidates_chunk::Variant::Done(
5345                        proto::FindSearchCandidatesDone {},
5346                    )),
5347                })
5348                .await?;
5349            anyhow::Ok(())
5350        });
5351        buffer_store.update(&mut cx, |this, _| {
5352            this.register_ongoing_project_search((peer_id, handle), task);
5353        });
5354
5355        Ok(proto::Ack {})
5356    }
5357
5358    async fn handle_open_buffer_by_id(
5359        this: Entity<Self>,
5360        envelope: TypedEnvelope<proto::OpenBufferById>,
5361        mut cx: AsyncApp,
5362    ) -> Result<proto::OpenBufferResponse> {
5363        let peer_id = envelope.original_sender_id()?;
5364        let buffer_id = BufferId::new(envelope.payload.id)?;
5365        let buffer = this
5366            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))
5367            .await?;
5368        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
5369    }
5370
5371    async fn handle_open_buffer_by_path(
5372        this: Entity<Self>,
5373        envelope: TypedEnvelope<proto::OpenBufferByPath>,
5374        mut cx: AsyncApp,
5375    ) -> Result<proto::OpenBufferResponse> {
5376        let peer_id = envelope.original_sender_id()?;
5377        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5378        let path = RelPath::from_proto(&envelope.payload.path)?;
5379        let open_buffer = this
5380            .update(&mut cx, |this, cx| {
5381                this.open_buffer(ProjectPath { worktree_id, path }, cx)
5382            })
5383            .await?;
5384        Project::respond_to_open_buffer_request(this, open_buffer, peer_id, &mut cx)
5385    }
5386
5387    async fn handle_open_new_buffer(
5388        this: Entity<Self>,
5389        envelope: TypedEnvelope<proto::OpenNewBuffer>,
5390        mut cx: AsyncApp,
5391    ) -> Result<proto::OpenBufferResponse> {
5392        let buffer = this
5393            .update(&mut cx, |this, cx| this.create_buffer(None, true, cx))
5394            .await?;
5395        let peer_id = envelope.original_sender_id()?;
5396
5397        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
5398    }
5399
5400    fn respond_to_open_buffer_request(
5401        this: Entity<Self>,
5402        buffer: Entity<Buffer>,
5403        peer_id: proto::PeerId,
5404        cx: &mut AsyncApp,
5405    ) -> Result<proto::OpenBufferResponse> {
5406        this.update(cx, |this, cx| {
5407            let is_private = buffer
5408                .read(cx)
5409                .file()
5410                .map(|f| f.is_private())
5411                .unwrap_or_default();
5412            anyhow::ensure!(!is_private, ErrorCode::UnsharedItem);
5413            Ok(proto::OpenBufferResponse {
5414                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
5415            })
5416        })
5417    }
5418
5419    fn create_buffer_for_peer(
5420        &mut self,
5421        buffer: &Entity<Buffer>,
5422        peer_id: proto::PeerId,
5423        cx: &mut App,
5424    ) -> BufferId {
5425        self.buffer_store
5426            .update(cx, |buffer_store, cx| {
5427                buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
5428            })
5429            .detach_and_log_err(cx);
5430        buffer.read(cx).remote_id()
5431    }
5432
5433    async fn handle_create_image_for_peer(
5434        this: Entity<Self>,
5435        envelope: TypedEnvelope<proto::CreateImageForPeer>,
5436        mut cx: AsyncApp,
5437    ) -> Result<()> {
5438        this.update(&mut cx, |this, cx| {
5439            this.image_store.update(cx, |image_store, cx| {
5440                image_store.handle_create_image_for_peer(envelope, cx)
5441            })
5442        })
5443    }
5444
5445    async fn handle_create_file_for_peer(
5446        this: Entity<Self>,
5447        envelope: TypedEnvelope<proto::CreateFileForPeer>,
5448        mut cx: AsyncApp,
5449    ) -> Result<()> {
5450        use proto::create_file_for_peer::Variant;
5451        log::debug!("handle_create_file_for_peer: received message");
5452
5453        let downloading_files: Arc<Mutex<HashMap<(WorktreeId, String), DownloadingFile>>> =
5454            this.update(&mut cx, |this, _| this.downloading_files.clone());
5455
5456        match &envelope.payload.variant {
5457            Some(Variant::State(state)) => {
5458                log::debug!(
5459                    "handle_create_file_for_peer: got State: id={}, content_size={}",
5460                    state.id,
5461                    state.content_size
5462                );
5463
5464                // Extract worktree_id and path from the File field
5465                if let Some(ref file) = state.file {
5466                    let worktree_id = WorktreeId::from_proto(file.worktree_id);
5467                    let path = file.path.clone();
5468                    let key = (worktree_id, path);
5469                    log::debug!("handle_create_file_for_peer: looking up key={:?}", key);
5470
5471                    let mut files = downloading_files.lock();
5472                    log::trace!(
5473                        "handle_create_file_for_peer: current downloading_files keys: {:?}",
5474                        files.keys().collect::<Vec<_>>()
5475                    );
5476
5477                    if let Some(file_entry) = files.get_mut(&key) {
5478                        file_entry.total_size = state.content_size;
5479                        file_entry.file_id = Some(state.id);
5480                        log::debug!(
5481                            "handle_create_file_for_peer: updated file entry: total_size={}, file_id={}",
5482                            state.content_size,
5483                            state.id
5484                        );
5485                    } else {
5486                        log::warn!(
5487                            "handle_create_file_for_peer: key={:?} not found in downloading_files",
5488                            key
5489                        );
5490                    }
5491                } else {
5492                    log::warn!("handle_create_file_for_peer: State has no file field");
5493                }
5494            }
5495            Some(Variant::Chunk(chunk)) => {
5496                log::debug!(
5497                    "handle_create_file_for_peer: got Chunk: file_id={}, data_len={}",
5498                    chunk.file_id,
5499                    chunk.data.len()
5500                );
5501
5502                // Extract data while holding the lock, then release it before await
5503                let (key_to_remove, write_info): (
5504                    Option<(WorktreeId, String)>,
5505                    Option<(PathBuf, Vec<u8>)>,
5506                ) = {
5507                    let mut files = downloading_files.lock();
5508                    let mut found_key: Option<(WorktreeId, String)> = None;
5509                    let mut write_data: Option<(PathBuf, Vec<u8>)> = None;
5510
5511                    for (key, file_entry) in files.iter_mut() {
5512                        if file_entry.file_id == Some(chunk.file_id) {
5513                            file_entry.chunks.extend_from_slice(&chunk.data);
5514                            log::debug!(
5515                                "handle_create_file_for_peer: accumulated {} bytes, total_size={}",
5516                                file_entry.chunks.len(),
5517                                file_entry.total_size
5518                            );
5519
5520                            if file_entry.chunks.len() as u64 >= file_entry.total_size
5521                                && file_entry.total_size > 0
5522                            {
5523                                let destination = file_entry.destination_path.clone();
5524                                let content = std::mem::take(&mut file_entry.chunks);
5525                                found_key = Some(key.clone());
5526                                write_data = Some((destination, content));
5527                            }
5528                            break;
5529                        }
5530                    }
5531                    (found_key, write_data)
5532                }; // MutexGuard is dropped here
5533
5534                // Perform the async write outside the lock
5535                if let Some((destination, content)) = write_info {
5536                    log::debug!(
5537                        "handle_create_file_for_peer: writing {} bytes to {:?}",
5538                        content.len(),
5539                        destination
5540                    );
5541                    match smol::fs::write(&destination, &content).await {
5542                        Ok(_) => log::info!(
5543                            "handle_create_file_for_peer: successfully wrote file to {:?}",
5544                            destination
5545                        ),
5546                        Err(e) => log::error!(
5547                            "handle_create_file_for_peer: failed to write file: {:?}",
5548                            e
5549                        ),
5550                    }
5551                }
5552
5553                // Remove the completed entry
5554                if let Some(key) = key_to_remove {
5555                    downloading_files.lock().remove(&key);
5556                    log::debug!("handle_create_file_for_peer: removed completed download entry");
5557                }
5558            }
5559            None => {
5560                log::warn!("handle_create_file_for_peer: got None variant");
5561            }
5562        }
5563
5564        Ok(())
5565    }
5566
5567    fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
5568        let project_id = match self.client_state {
5569            ProjectClientState::Remote {
5570                sharing_has_stopped,
5571                remote_id,
5572                ..
5573            } => {
5574                if sharing_has_stopped {
5575                    return Task::ready(Err(anyhow!(
5576                        "can't synchronize remote buffers on a readonly project"
5577                    )));
5578                } else {
5579                    remote_id
5580                }
5581            }
5582            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
5583                return Task::ready(Err(anyhow!(
5584                    "can't synchronize remote buffers on a local project"
5585                )));
5586            }
5587        };
5588
5589        let client = self.collab_client.clone();
5590        cx.spawn(async move |this, cx| {
5591            let (buffers, incomplete_buffer_ids) = this.update(cx, |this, cx| {
5592                this.buffer_store.read(cx).buffer_version_info(cx)
5593            })?;
5594            let response = client
5595                .request(proto::SynchronizeBuffers {
5596                    project_id,
5597                    buffers,
5598                })
5599                .await?;
5600
5601            let send_updates_for_buffers = this.update(cx, |this, cx| {
5602                response
5603                    .buffers
5604                    .into_iter()
5605                    .map(|buffer| {
5606                        let client = client.clone();
5607                        let buffer_id = match BufferId::new(buffer.id) {
5608                            Ok(id) => id,
5609                            Err(e) => {
5610                                return Task::ready(Err(e));
5611                            }
5612                        };
5613                        let remote_version = language::proto::deserialize_version(&buffer.version);
5614                        if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5615                            let operations =
5616                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
5617                            cx.background_spawn(async move {
5618                                let operations = operations.await;
5619                                for chunk in split_operations(operations) {
5620                                    client
5621                                        .request(proto::UpdateBuffer {
5622                                            project_id,
5623                                            buffer_id: buffer_id.into(),
5624                                            operations: chunk,
5625                                        })
5626                                        .await?;
5627                                }
5628                                anyhow::Ok(())
5629                            })
5630                        } else {
5631                            Task::ready(Ok(()))
5632                        }
5633                    })
5634                    .collect::<Vec<_>>()
5635            })?;
5636
5637            // Any incomplete buffers have open requests waiting. Request that the host sends
5638            // creates these buffers for us again to unblock any waiting futures.
5639            for id in incomplete_buffer_ids {
5640                cx.background_spawn(client.request(proto::OpenBufferById {
5641                    project_id,
5642                    id: id.into(),
5643                }))
5644                .detach();
5645            }
5646
5647            futures::future::join_all(send_updates_for_buffers)
5648                .await
5649                .into_iter()
5650                .collect()
5651        })
5652    }
5653
5654    pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
5655        self.worktree_store.read(cx).worktree_metadata_protos(cx)
5656    }
5657
5658    /// Iterator of all open buffers that have unsaved changes
5659    pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
5660        self.buffer_store.read(cx).buffers().filter_map(|buf| {
5661            let buf = buf.read(cx);
5662            if buf.is_dirty() {
5663                buf.project_path(cx)
5664            } else {
5665                None
5666            }
5667        })
5668    }
5669
5670    fn set_worktrees_from_proto(
5671        &mut self,
5672        worktrees: Vec<proto::WorktreeMetadata>,
5673        cx: &mut Context<Project>,
5674    ) -> Result<()> {
5675        self.worktree_store.update(cx, |worktree_store, cx| {
5676            worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
5677        })
5678    }
5679
5680    fn set_collaborators_from_proto(
5681        &mut self,
5682        messages: Vec<proto::Collaborator>,
5683        cx: &mut Context<Self>,
5684    ) -> Result<()> {
5685        let mut collaborators = HashMap::default();
5686        for message in messages {
5687            let collaborator = Collaborator::from_proto(message)?;
5688            collaborators.insert(collaborator.peer_id, collaborator);
5689        }
5690        for old_peer_id in self.collaborators.keys() {
5691            if !collaborators.contains_key(old_peer_id) {
5692                cx.emit(Event::CollaboratorLeft(*old_peer_id));
5693            }
5694        }
5695        self.collaborators = collaborators;
5696        Ok(())
5697    }
5698
5699    pub fn supplementary_language_servers<'a>(
5700        &'a self,
5701        cx: &'a App,
5702    ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
5703        self.lsp_store.read(cx).supplementary_language_servers()
5704    }
5705
5706    pub fn any_language_server_supports_inlay_hints(&self, buffer: &Buffer, cx: &mut App) -> bool {
5707        let Some(language) = buffer.language().cloned() else {
5708            return false;
5709        };
5710        self.lsp_store.update(cx, |lsp_store, _| {
5711            let relevant_language_servers = lsp_store
5712                .languages
5713                .lsp_adapters(&language.name())
5714                .into_iter()
5715                .map(|lsp_adapter| lsp_adapter.name())
5716                .collect::<HashSet<_>>();
5717            lsp_store
5718                .language_server_statuses()
5719                .filter_map(|(server_id, server_status)| {
5720                    relevant_language_servers
5721                        .contains(&server_status.name)
5722                        .then_some(server_id)
5723                })
5724                .filter_map(|server_id| lsp_store.lsp_server_capabilities.get(&server_id))
5725                .any(InlayHints::check_capabilities)
5726        })
5727    }
5728
5729    pub fn any_language_server_supports_semantic_tokens(
5730        &self,
5731        buffer: &Buffer,
5732        cx: &mut App,
5733    ) -> bool {
5734        let Some(language) = buffer.language().cloned() else {
5735            return false;
5736        };
5737        let lsp_store = self.lsp_store.read(cx);
5738        let relevant_language_servers = lsp_store
5739            .languages
5740            .lsp_adapters(&language.name())
5741            .into_iter()
5742            .map(|lsp_adapter| lsp_adapter.name())
5743            .collect::<HashSet<_>>();
5744        lsp_store
5745            .language_server_statuses()
5746            .filter_map(|(server_id, server_status)| {
5747                relevant_language_servers
5748                    .contains(&server_status.name)
5749                    .then_some(server_id)
5750            })
5751            .filter_map(|server_id| lsp_store.lsp_server_capabilities.get(&server_id))
5752            .any(|capabilities| capabilities.semantic_tokens_provider.is_some())
5753    }
5754
5755    pub fn language_server_id_for_name(
5756        &self,
5757        buffer: &Buffer,
5758        name: &LanguageServerName,
5759        cx: &App,
5760    ) -> Option<LanguageServerId> {
5761        let language = buffer.language()?;
5762        let relevant_language_servers = self
5763            .languages
5764            .lsp_adapters(&language.name())
5765            .into_iter()
5766            .map(|lsp_adapter| lsp_adapter.name())
5767            .collect::<HashSet<_>>();
5768        if !relevant_language_servers.contains(name) {
5769            return None;
5770        }
5771        self.language_server_statuses(cx)
5772            .filter(|(_, server_status)| relevant_language_servers.contains(&server_status.name))
5773            .find_map(|(server_id, server_status)| {
5774                if &server_status.name == name {
5775                    Some(server_id)
5776                } else {
5777                    None
5778                }
5779            })
5780    }
5781
5782    #[cfg(feature = "test-support")]
5783    pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
5784        self.lsp_store.update(cx, |this, cx| {
5785            this.running_language_servers_for_local_buffer(buffer, cx)
5786                .next()
5787                .is_some()
5788        })
5789    }
5790
5791    pub fn git_init(
5792        &self,
5793        path: Arc<Path>,
5794        fallback_branch_name: String,
5795        cx: &App,
5796    ) -> Task<Result<()>> {
5797        self.git_store
5798            .read(cx)
5799            .git_init(path, fallback_branch_name, cx)
5800    }
5801
5802    pub fn buffer_store(&self) -> &Entity<BufferStore> {
5803        &self.buffer_store
5804    }
5805
5806    pub fn git_store(&self) -> &Entity<GitStore> {
5807        &self.git_store
5808    }
5809
5810    pub fn agent_server_store(&self) -> &Entity<AgentServerStore> {
5811        &self.agent_server_store
5812    }
5813
5814    #[cfg(feature = "test-support")]
5815    pub fn git_scans_complete(&self, cx: &Context<Self>) -> Task<()> {
5816        use futures::future::join_all;
5817        cx.spawn(async move |this, cx| {
5818            let scans_complete = this
5819                .read_with(cx, |this, cx| {
5820                    this.worktrees(cx)
5821                        .filter_map(|worktree| Some(worktree.read(cx).as_local()?.scan_complete()))
5822                        .collect::<Vec<_>>()
5823                })
5824                .unwrap();
5825            join_all(scans_complete).await;
5826            let barriers = this
5827                .update(cx, |this, cx| {
5828                    let repos = this.repositories(cx).values().cloned().collect::<Vec<_>>();
5829                    repos
5830                        .into_iter()
5831                        .map(|repo| repo.update(cx, |repo, _| repo.barrier()))
5832                        .collect::<Vec<_>>()
5833                })
5834                .unwrap();
5835            join_all(barriers).await;
5836        })
5837    }
5838
5839    pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
5840        self.git_store.read(cx).active_repository()
5841    }
5842
5843    pub fn repositories<'a>(&self, cx: &'a App) -> &'a HashMap<RepositoryId, Entity<Repository>> {
5844        self.git_store.read(cx).repositories()
5845    }
5846
5847    pub fn status_for_buffer_id(&self, buffer_id: BufferId, cx: &App) -> Option<FileStatus> {
5848        self.git_store.read(cx).status_for_buffer_id(buffer_id, cx)
5849    }
5850
5851    pub fn set_agent_location(
5852        &mut self,
5853        new_location: Option<AgentLocation>,
5854        cx: &mut Context<Self>,
5855    ) {
5856        if let Some(old_location) = self.agent_location.as_ref() {
5857            old_location
5858                .buffer
5859                .update(cx, |buffer, cx| buffer.remove_agent_selections(cx))
5860                .ok();
5861        }
5862
5863        if let Some(location) = new_location.as_ref() {
5864            location
5865                .buffer
5866                .update(cx, |buffer, cx| {
5867                    buffer.set_agent_selections(
5868                        Arc::from([language::Selection {
5869                            id: 0,
5870                            start: location.position,
5871                            end: location.position,
5872                            reversed: false,
5873                            goal: language::SelectionGoal::None,
5874                        }]),
5875                        false,
5876                        CursorShape::Hollow,
5877                        cx,
5878                    )
5879                })
5880                .ok();
5881        }
5882
5883        self.agent_location = new_location;
5884        cx.emit(Event::AgentLocationChanged);
5885    }
5886
5887    pub fn agent_location(&self) -> Option<AgentLocation> {
5888        self.agent_location.clone()
5889    }
5890
5891    pub fn path_style(&self, cx: &App) -> PathStyle {
5892        self.worktree_store.read(cx).path_style()
5893    }
5894
5895    pub fn contains_local_settings_file(
5896        &self,
5897        worktree_id: WorktreeId,
5898        rel_path: &RelPath,
5899        cx: &App,
5900    ) -> bool {
5901        self.worktree_for_id(worktree_id, cx)
5902            .map_or(false, |worktree| {
5903                worktree.read(cx).entry_for_path(rel_path).is_some()
5904            })
5905    }
5906}
5907
5908pub struct PathMatchCandidateSet {
5909    pub snapshot: Snapshot,
5910    pub include_ignored: bool,
5911    pub include_root_name: bool,
5912    pub candidates: Candidates,
5913}
5914
5915pub enum Candidates {
5916    /// Only consider directories.
5917    Directories,
5918    /// Only consider files.
5919    Files,
5920    /// Consider directories and files.
5921    Entries,
5922}
5923
5924impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
5925    type Candidates = PathMatchCandidateSetIter<'a>;
5926
5927    fn id(&self) -> usize {
5928        self.snapshot.id().to_usize()
5929    }
5930
5931    fn len(&self) -> usize {
5932        match self.candidates {
5933            Candidates::Files => {
5934                if self.include_ignored {
5935                    self.snapshot.file_count()
5936                } else {
5937                    self.snapshot.visible_file_count()
5938                }
5939            }
5940
5941            Candidates::Directories => {
5942                if self.include_ignored {
5943                    self.snapshot.dir_count()
5944                } else {
5945                    self.snapshot.visible_dir_count()
5946                }
5947            }
5948
5949            Candidates::Entries => {
5950                if self.include_ignored {
5951                    self.snapshot.entry_count()
5952                } else {
5953                    self.snapshot.visible_entry_count()
5954                }
5955            }
5956        }
5957    }
5958
5959    fn prefix(&self) -> Arc<RelPath> {
5960        if self.snapshot.root_entry().is_some_and(|e| e.is_file()) || self.include_root_name {
5961            self.snapshot.root_name().into()
5962        } else {
5963            RelPath::empty().into()
5964        }
5965    }
5966
5967    fn root_is_file(&self) -> bool {
5968        self.snapshot.root_entry().is_some_and(|f| f.is_file())
5969    }
5970
5971    fn path_style(&self) -> PathStyle {
5972        self.snapshot.path_style()
5973    }
5974
5975    fn candidates(&'a self, start: usize) -> Self::Candidates {
5976        PathMatchCandidateSetIter {
5977            traversal: match self.candidates {
5978                Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
5979                Candidates::Files => self.snapshot.files(self.include_ignored, start),
5980                Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
5981            },
5982        }
5983    }
5984}
5985
5986pub struct PathMatchCandidateSetIter<'a> {
5987    traversal: Traversal<'a>,
5988}
5989
5990impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
5991    type Item = fuzzy::PathMatchCandidate<'a>;
5992
5993    fn next(&mut self) -> Option<Self::Item> {
5994        self.traversal
5995            .next()
5996            .map(|entry| fuzzy::PathMatchCandidate {
5997                is_dir: entry.kind.is_dir(),
5998                path: &entry.path,
5999                char_bag: entry.char_bag,
6000            })
6001    }
6002}
6003
6004impl EventEmitter<Event> for Project {}
6005
6006impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
6007    fn from(val: &'a ProjectPath) -> Self {
6008        SettingsLocation {
6009            worktree_id: val.worktree_id,
6010            path: val.path.as_ref(),
6011        }
6012    }
6013}
6014
6015impl<P: Into<Arc<RelPath>>> From<(WorktreeId, P)> for ProjectPath {
6016    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6017        Self {
6018            worktree_id,
6019            path: path.into(),
6020        }
6021    }
6022}
6023
6024/// ResolvedPath is a path that has been resolved to either a ProjectPath
6025/// or an AbsPath and that *exists*.
6026#[derive(Debug, Clone)]
6027pub enum ResolvedPath {
6028    ProjectPath {
6029        project_path: ProjectPath,
6030        is_dir: bool,
6031    },
6032    AbsPath {
6033        path: String,
6034        is_dir: bool,
6035    },
6036}
6037
6038impl ResolvedPath {
6039    pub fn abs_path(&self) -> Option<&str> {
6040        match self {
6041            Self::AbsPath { path, .. } => Some(path),
6042            _ => None,
6043        }
6044    }
6045
6046    pub fn into_abs_path(self) -> Option<String> {
6047        match self {
6048            Self::AbsPath { path, .. } => Some(path),
6049            _ => None,
6050        }
6051    }
6052
6053    pub fn project_path(&self) -> Option<&ProjectPath> {
6054        match self {
6055            Self::ProjectPath { project_path, .. } => Some(project_path),
6056            _ => None,
6057        }
6058    }
6059
6060    pub fn is_file(&self) -> bool {
6061        !self.is_dir()
6062    }
6063
6064    pub fn is_dir(&self) -> bool {
6065        match self {
6066            Self::ProjectPath { is_dir, .. } => *is_dir,
6067            Self::AbsPath { is_dir, .. } => *is_dir,
6068        }
6069    }
6070}
6071
6072impl ProjectItem for Buffer {
6073    fn try_open(
6074        project: &Entity<Project>,
6075        path: &ProjectPath,
6076        cx: &mut App,
6077    ) -> Option<Task<Result<Entity<Self>>>> {
6078        Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
6079    }
6080
6081    fn entry_id(&self, _cx: &App) -> Option<ProjectEntryId> {
6082        File::from_dyn(self.file()).and_then(|file| file.project_entry_id())
6083    }
6084
6085    fn project_path(&self, cx: &App) -> Option<ProjectPath> {
6086        let file = self.file()?;
6087
6088        (!matches!(file.disk_state(), DiskState::Historic { .. })).then(|| ProjectPath {
6089            worktree_id: file.worktree_id(cx),
6090            path: file.path().clone(),
6091        })
6092    }
6093
6094    fn is_dirty(&self) -> bool {
6095        self.is_dirty()
6096    }
6097}
6098
6099impl Completion {
6100    pub fn kind(&self) -> Option<CompletionItemKind> {
6101        self.source
6102            // `lsp::CompletionListItemDefaults` has no `kind` field
6103            .lsp_completion(false)
6104            .and_then(|lsp_completion| lsp_completion.kind)
6105    }
6106
6107    pub fn label(&self) -> Option<String> {
6108        self.source
6109            .lsp_completion(false)
6110            .map(|lsp_completion| lsp_completion.label.clone())
6111    }
6112
6113    /// A key that can be used to sort completions when displaying
6114    /// them to the user.
6115    pub fn sort_key(&self) -> (usize, &str) {
6116        const DEFAULT_KIND_KEY: usize = 4;
6117        let kind_key = self
6118            .kind()
6119            .and_then(|lsp_completion_kind| match lsp_completion_kind {
6120                lsp::CompletionItemKind::KEYWORD => Some(0),
6121                lsp::CompletionItemKind::VARIABLE => Some(1),
6122                lsp::CompletionItemKind::CONSTANT => Some(2),
6123                lsp::CompletionItemKind::PROPERTY => Some(3),
6124                _ => None,
6125            })
6126            .unwrap_or(DEFAULT_KIND_KEY);
6127        (kind_key, self.label.filter_text())
6128    }
6129
6130    /// Whether this completion is a snippet.
6131    pub fn is_snippet_kind(&self) -> bool {
6132        matches!(
6133            &self.source,
6134            CompletionSource::Lsp { lsp_completion, .. }
6135            if lsp_completion.kind == Some(CompletionItemKind::SNIPPET)
6136        )
6137    }
6138
6139    /// Whether this completion is a snippet or snippet-style LSP completion.
6140    pub fn is_snippet(&self) -> bool {
6141        self.source
6142            // `lsp::CompletionListItemDefaults` has `insert_text_format` field
6143            .lsp_completion(true)
6144            .is_some_and(|lsp_completion| {
6145                lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
6146            })
6147    }
6148
6149    /// Returns the corresponding color for this completion.
6150    ///
6151    /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
6152    pub fn color(&self) -> Option<Hsla> {
6153        // `lsp::CompletionListItemDefaults` has no `kind` field
6154        let lsp_completion = self.source.lsp_completion(false)?;
6155        if lsp_completion.kind? == CompletionItemKind::COLOR {
6156            return color_extractor::extract_color(&lsp_completion);
6157        }
6158        None
6159    }
6160}
6161
6162fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
6163    match level {
6164        proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
6165        proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
6166        proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
6167    }
6168}
6169
6170fn provide_inline_values(
6171    captures: impl Iterator<Item = (Range<usize>, language::DebuggerTextObject)>,
6172    snapshot: &language::BufferSnapshot,
6173    max_row: usize,
6174) -> Vec<InlineValueLocation> {
6175    let mut variables = Vec::new();
6176    let mut variable_position = HashSet::default();
6177    let mut scopes = Vec::new();
6178
6179    let active_debug_line_offset = snapshot.point_to_offset(Point::new(max_row as u32, 0));
6180
6181    for (capture_range, capture_kind) in captures {
6182        match capture_kind {
6183            language::DebuggerTextObject::Variable => {
6184                let variable_name = snapshot
6185                    .text_for_range(capture_range.clone())
6186                    .collect::<String>();
6187                let point = snapshot.offset_to_point(capture_range.end);
6188
6189                while scopes
6190                    .last()
6191                    .is_some_and(|scope: &Range<_>| !scope.contains(&capture_range.start))
6192                {
6193                    scopes.pop();
6194                }
6195
6196                if point.row as usize > max_row {
6197                    break;
6198                }
6199
6200                let scope = if scopes
6201                    .last()
6202                    .is_none_or(|scope| !scope.contains(&active_debug_line_offset))
6203                {
6204                    VariableScope::Global
6205                } else {
6206                    VariableScope::Local
6207                };
6208
6209                if variable_position.insert(capture_range.end) {
6210                    variables.push(InlineValueLocation {
6211                        variable_name,
6212                        scope,
6213                        lookup: VariableLookupKind::Variable,
6214                        row: point.row as usize,
6215                        column: point.column as usize,
6216                    });
6217                }
6218            }
6219            language::DebuggerTextObject::Scope => {
6220                while scopes.last().map_or_else(
6221                    || false,
6222                    |scope: &Range<usize>| {
6223                        !(scope.contains(&capture_range.start)
6224                            && scope.contains(&capture_range.end))
6225                    },
6226                ) {
6227                    scopes.pop();
6228                }
6229                scopes.push(capture_range);
6230            }
6231        }
6232    }
6233
6234    variables
6235}