project.rs

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