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