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                    cx,
1359                )
1360            });
1361            cx.subscribe(&settings_observer, Self::on_settings_observer_event)
1362                .detach();
1363
1364            let environment = cx.new(|cx| {
1365                ProjectEnvironment::new(
1366                    None,
1367                    worktree_store.downgrade(),
1368                    Some(remote.downgrade()),
1369                    false,
1370                    cx,
1371                )
1372            });
1373
1374            let lsp_store = cx.new(|cx| {
1375                LspStore::new_remote(
1376                    buffer_store.clone(),
1377                    worktree_store.clone(),
1378                    languages.clone(),
1379                    remote_proto.clone(),
1380                    REMOTE_SERVER_PROJECT_ID,
1381                    cx,
1382                )
1383            });
1384            cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
1385
1386            let breakpoint_store = cx.new(|_| {
1387                BreakpointStore::remote(
1388                    REMOTE_SERVER_PROJECT_ID,
1389                    remote_proto.clone(),
1390                    buffer_store.clone(),
1391                    worktree_store.clone(),
1392                )
1393            });
1394
1395            let dap_store = cx.new(|cx| {
1396                DapStore::new_remote(
1397                    REMOTE_SERVER_PROJECT_ID,
1398                    remote.clone(),
1399                    breakpoint_store.clone(),
1400                    worktree_store.clone(),
1401                    node.clone(),
1402                    client.http_client(),
1403                    fs.clone(),
1404                    cx,
1405                )
1406            });
1407
1408            let git_store = cx.new(|cx| {
1409                GitStore::remote(
1410                    &worktree_store,
1411                    buffer_store.clone(),
1412                    remote_proto.clone(),
1413                    REMOTE_SERVER_PROJECT_ID,
1414                    cx,
1415                )
1416            });
1417
1418            let agent_server_store =
1419                cx.new(|_| AgentServerStore::remote(REMOTE_SERVER_PROJECT_ID, remote.clone()));
1420
1421            cx.subscribe(&remote, Self::on_remote_client_event).detach();
1422
1423            let this = Self {
1424                buffer_ordered_messages_tx: tx,
1425                collaborators: Default::default(),
1426                worktree_store,
1427                buffer_store,
1428                image_store,
1429                lsp_store,
1430                context_server_store,
1431                breakpoint_store,
1432                dap_store,
1433                join_project_response_message_id: 0,
1434                client_state: ProjectClientState::Local,
1435                git_store,
1436                agent_server_store,
1437                client_subscriptions: Vec::new(),
1438                _subscriptions: vec![
1439                    cx.on_release(Self::release),
1440                    cx.on_app_quit(|this, cx| {
1441                        let shutdown = this.remote_client.take().and_then(|client| {
1442                            client.update(cx, |client, cx| {
1443                                client.shutdown_processes(
1444                                    Some(proto::ShutdownRemoteServer {}),
1445                                    cx.background_executor().clone(),
1446                                )
1447                            })
1448                        });
1449
1450                        cx.background_executor().spawn(async move {
1451                            if let Some(shutdown) = shutdown {
1452                                shutdown.await;
1453                            }
1454                        })
1455                    }),
1456                ],
1457                active_entry: None,
1458                snippets,
1459                languages,
1460                collab_client: client,
1461                task_store,
1462                user_store,
1463                settings_observer,
1464                fs,
1465                remote_client: Some(remote.clone()),
1466                buffers_needing_diff: Default::default(),
1467                git_diff_debouncer: DebouncedDelay::new(),
1468                terminals: Terminals {
1469                    local_handles: Vec::new(),
1470                },
1471                node: Some(node),
1472                search_history: Self::new_search_history(),
1473                environment,
1474                remotely_created_models: Default::default(),
1475
1476                search_included_history: Self::new_search_history(),
1477                search_excluded_history: Self::new_search_history(),
1478
1479                toolchain_store: Some(toolchain_store),
1480                agent_location: None,
1481            };
1482
1483            // remote server -> local machine handlers
1484            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &cx.entity());
1485            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.buffer_store);
1486            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.worktree_store);
1487            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.lsp_store);
1488            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.dap_store);
1489            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.breakpoint_store);
1490            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.settings_observer);
1491            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.git_store);
1492            remote_proto.subscribe_to_entity(REMOTE_SERVER_PROJECT_ID, &this.agent_server_store);
1493
1494            remote_proto.add_entity_message_handler(Self::handle_create_buffer_for_peer);
1495            remote_proto.add_entity_message_handler(Self::handle_create_image_for_peer);
1496            remote_proto.add_entity_message_handler(Self::handle_update_worktree);
1497            remote_proto.add_entity_message_handler(Self::handle_update_project);
1498            remote_proto.add_entity_message_handler(Self::handle_toast);
1499            remote_proto.add_entity_request_handler(Self::handle_language_server_prompt_request);
1500            remote_proto.add_entity_message_handler(Self::handle_hide_toast);
1501            remote_proto.add_entity_request_handler(Self::handle_update_buffer_from_remote_server);
1502            remote_proto.add_entity_request_handler(Self::handle_trust_worktrees);
1503            remote_proto.add_entity_request_handler(Self::handle_restrict_worktrees);
1504            remote_proto.add_entity_request_handler(Self::handle_find_search_candidates_chunk);
1505
1506            remote_proto.add_entity_message_handler(Self::handle_find_search_candidates_cancel);
1507            BufferStore::init(&remote_proto);
1508            LspStore::init(&remote_proto);
1509            SettingsObserver::init(&remote_proto);
1510            TaskStore::init(Some(&remote_proto));
1511            ToolchainStore::init(&remote_proto);
1512            DapStore::init(&remote_proto, cx);
1513            BreakpointStore::init(&remote_proto);
1514            GitStore::init(&remote_proto);
1515            AgentServerStore::init_remote(&remote_proto);
1516
1517            this
1518        })
1519    }
1520
1521    pub async fn in_room(
1522        remote_id: u64,
1523        client: Arc<Client>,
1524        user_store: Entity<UserStore>,
1525        languages: Arc<LanguageRegistry>,
1526        fs: Arc<dyn Fs>,
1527        cx: AsyncApp,
1528    ) -> Result<Entity<Self>> {
1529        client.connect(true, &cx).await.into_response()?;
1530
1531        let subscriptions = [
1532            EntitySubscription::Project(client.subscribe_to_entity::<Self>(remote_id)?),
1533            EntitySubscription::BufferStore(client.subscribe_to_entity::<BufferStore>(remote_id)?),
1534            EntitySubscription::GitStore(client.subscribe_to_entity::<GitStore>(remote_id)?),
1535            EntitySubscription::WorktreeStore(
1536                client.subscribe_to_entity::<WorktreeStore>(remote_id)?,
1537            ),
1538            EntitySubscription::LspStore(client.subscribe_to_entity::<LspStore>(remote_id)?),
1539            EntitySubscription::SettingsObserver(
1540                client.subscribe_to_entity::<SettingsObserver>(remote_id)?,
1541            ),
1542            EntitySubscription::DapStore(client.subscribe_to_entity::<DapStore>(remote_id)?),
1543            EntitySubscription::BreakpointStore(
1544                client.subscribe_to_entity::<BreakpointStore>(remote_id)?,
1545            ),
1546        ];
1547        let committer = get_git_committer(&cx).await;
1548        let response = client
1549            .request_envelope(proto::JoinProject {
1550                project_id: remote_id,
1551                committer_email: committer.email,
1552                committer_name: committer.name,
1553            })
1554            .await?;
1555        Self::from_join_project_response(
1556            response,
1557            subscriptions,
1558            client,
1559            false,
1560            user_store,
1561            languages,
1562            fs,
1563            cx,
1564        )
1565        .await
1566    }
1567
1568    async fn from_join_project_response(
1569        response: TypedEnvelope<proto::JoinProjectResponse>,
1570        subscriptions: [EntitySubscription; 8],
1571        client: Arc<Client>,
1572        run_tasks: bool,
1573        user_store: Entity<UserStore>,
1574        languages: Arc<LanguageRegistry>,
1575        fs: Arc<dyn Fs>,
1576        mut cx: AsyncApp,
1577    ) -> Result<Entity<Self>> {
1578        let remote_id = response.payload.project_id;
1579        let role = response.payload.role();
1580
1581        let path_style = if response.payload.windows_paths {
1582            PathStyle::Windows
1583        } else {
1584            PathStyle::Posix
1585        };
1586
1587        let worktree_store = cx.new(|_| {
1588            WorktreeStore::remote(
1589                true,
1590                client.clone().into(),
1591                response.payload.project_id,
1592                path_style,
1593            )
1594        });
1595        let buffer_store = cx.new(|cx| {
1596            BufferStore::remote(worktree_store.clone(), client.clone().into(), remote_id, cx)
1597        });
1598        let image_store = cx.new(|cx| {
1599            ImageStore::remote(worktree_store.clone(), client.clone().into(), remote_id, cx)
1600        });
1601
1602        let environment =
1603            cx.new(|cx| ProjectEnvironment::new(None, worktree_store.downgrade(), None, true, cx));
1604        let breakpoint_store = cx.new(|_| {
1605            BreakpointStore::remote(
1606                remote_id,
1607                client.clone().into(),
1608                buffer_store.clone(),
1609                worktree_store.clone(),
1610            )
1611        });
1612        let dap_store = cx.new(|cx| {
1613            DapStore::new_collab(
1614                remote_id,
1615                client.clone().into(),
1616                breakpoint_store.clone(),
1617                worktree_store.clone(),
1618                fs.clone(),
1619                cx,
1620            )
1621        });
1622
1623        let lsp_store = cx.new(|cx| {
1624            LspStore::new_remote(
1625                buffer_store.clone(),
1626                worktree_store.clone(),
1627                languages.clone(),
1628                client.clone().into(),
1629                remote_id,
1630                cx,
1631            )
1632        });
1633
1634        let task_store = cx.new(|cx| {
1635            if run_tasks {
1636                TaskStore::remote(
1637                    buffer_store.downgrade(),
1638                    worktree_store.clone(),
1639                    Arc::new(EmptyToolchainStore),
1640                    client.clone().into(),
1641                    remote_id,
1642                    cx,
1643                )
1644            } else {
1645                TaskStore::Noop
1646            }
1647        });
1648
1649        let settings_observer = cx.new(|cx| {
1650            SettingsObserver::new_remote(
1651                fs.clone(),
1652                worktree_store.clone(),
1653                task_store.clone(),
1654                None,
1655                cx,
1656            )
1657        });
1658
1659        let git_store = cx.new(|cx| {
1660            GitStore::remote(
1661                // In this remote case we pass None for the environment
1662                &worktree_store,
1663                buffer_store.clone(),
1664                client.clone().into(),
1665                remote_id,
1666                cx,
1667            )
1668        });
1669
1670        let agent_server_store = cx.new(|cx| AgentServerStore::collab(cx));
1671        let replica_id = ReplicaId::new(response.payload.replica_id as u16);
1672
1673        let project = cx.new(|cx| {
1674            let snippets = SnippetProvider::new(fs.clone(), BTreeSet::from_iter([]), cx);
1675
1676            let weak_self = cx.weak_entity();
1677            let context_server_store =
1678                cx.new(|cx| ContextServerStore::new(worktree_store.clone(), weak_self, cx));
1679
1680            let mut worktrees = Vec::new();
1681            for worktree in response.payload.worktrees {
1682                let worktree = Worktree::remote(
1683                    remote_id,
1684                    replica_id,
1685                    worktree,
1686                    client.clone().into(),
1687                    path_style,
1688                    cx,
1689                );
1690                worktrees.push(worktree);
1691            }
1692
1693            let (tx, rx) = mpsc::unbounded();
1694            cx.spawn(async move |this, cx| Self::send_buffer_ordered_messages(this, rx, cx).await)
1695                .detach();
1696
1697            cx.subscribe(&worktree_store, Self::on_worktree_store_event)
1698                .detach();
1699
1700            cx.subscribe(&buffer_store, Self::on_buffer_store_event)
1701                .detach();
1702            cx.subscribe(&lsp_store, Self::on_lsp_store_event).detach();
1703            cx.subscribe(&settings_observer, Self::on_settings_observer_event)
1704                .detach();
1705
1706            cx.subscribe(&dap_store, Self::on_dap_store_event).detach();
1707
1708            let mut project = Self {
1709                buffer_ordered_messages_tx: tx,
1710                buffer_store: buffer_store.clone(),
1711                image_store,
1712                worktree_store: worktree_store.clone(),
1713                lsp_store: lsp_store.clone(),
1714                context_server_store,
1715                active_entry: None,
1716                collaborators: Default::default(),
1717                join_project_response_message_id: response.message_id,
1718                languages,
1719                user_store: user_store.clone(),
1720                task_store,
1721                snippets,
1722                fs,
1723                remote_client: None,
1724                settings_observer: settings_observer.clone(),
1725                client_subscriptions: Default::default(),
1726                _subscriptions: vec![cx.on_release(Self::release)],
1727                collab_client: client.clone(),
1728                client_state: ProjectClientState::Remote {
1729                    sharing_has_stopped: false,
1730                    capability: Capability::ReadWrite,
1731                    remote_id,
1732                    replica_id,
1733                },
1734                breakpoint_store: breakpoint_store.clone(),
1735                dap_store: dap_store.clone(),
1736                git_store: git_store.clone(),
1737                agent_server_store,
1738                buffers_needing_diff: Default::default(),
1739                git_diff_debouncer: DebouncedDelay::new(),
1740                terminals: Terminals {
1741                    local_handles: Vec::new(),
1742                },
1743                node: None,
1744                search_history: Self::new_search_history(),
1745                search_included_history: Self::new_search_history(),
1746                search_excluded_history: Self::new_search_history(),
1747                environment,
1748                remotely_created_models: Arc::new(Mutex::new(RemotelyCreatedModels::default())),
1749                toolchain_store: None,
1750                agent_location: None,
1751            };
1752            project.set_role(role, cx);
1753            for worktree in worktrees {
1754                project.add_worktree(&worktree, cx);
1755            }
1756            project
1757        });
1758
1759        let weak_project = project.downgrade();
1760        lsp_store.update(&mut cx, |lsp_store, cx| {
1761            lsp_store.set_language_server_statuses_from_proto(
1762                weak_project,
1763                response.payload.language_servers,
1764                response.payload.language_server_capabilities,
1765                cx,
1766            );
1767        });
1768
1769        let subscriptions = subscriptions
1770            .into_iter()
1771            .map(|s| match s {
1772                EntitySubscription::BufferStore(subscription) => {
1773                    subscription.set_entity(&buffer_store, &cx)
1774                }
1775                EntitySubscription::WorktreeStore(subscription) => {
1776                    subscription.set_entity(&worktree_store, &cx)
1777                }
1778                EntitySubscription::GitStore(subscription) => {
1779                    subscription.set_entity(&git_store, &cx)
1780                }
1781                EntitySubscription::SettingsObserver(subscription) => {
1782                    subscription.set_entity(&settings_observer, &cx)
1783                }
1784                EntitySubscription::Project(subscription) => subscription.set_entity(&project, &cx),
1785                EntitySubscription::LspStore(subscription) => {
1786                    subscription.set_entity(&lsp_store, &cx)
1787                }
1788                EntitySubscription::DapStore(subscription) => {
1789                    subscription.set_entity(&dap_store, &cx)
1790                }
1791                EntitySubscription::BreakpointStore(subscription) => {
1792                    subscription.set_entity(&breakpoint_store, &cx)
1793                }
1794            })
1795            .collect::<Vec<_>>();
1796
1797        let user_ids = response
1798            .payload
1799            .collaborators
1800            .iter()
1801            .map(|peer| peer.user_id)
1802            .collect();
1803        user_store
1804            .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))
1805            .await?;
1806
1807        project.update(&mut cx, |this, cx| {
1808            this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
1809            this.client_subscriptions.extend(subscriptions);
1810            anyhow::Ok(())
1811        })?;
1812
1813        Ok(project)
1814    }
1815
1816    fn new_search_history() -> SearchHistory {
1817        SearchHistory::new(
1818            Some(MAX_PROJECT_SEARCH_HISTORY_SIZE),
1819            search_history::QueryInsertionBehavior::AlwaysInsert,
1820        )
1821    }
1822
1823    fn release(&mut self, cx: &mut App) {
1824        if let Some(client) = self.remote_client.take() {
1825            let shutdown = client.update(cx, |client, cx| {
1826                client.shutdown_processes(
1827                    Some(proto::ShutdownRemoteServer {}),
1828                    cx.background_executor().clone(),
1829                )
1830            });
1831
1832            cx.background_spawn(async move {
1833                if let Some(shutdown) = shutdown {
1834                    shutdown.await;
1835                }
1836            })
1837            .detach()
1838        }
1839
1840        match &self.client_state {
1841            ProjectClientState::Local => {}
1842            ProjectClientState::Shared { .. } => {
1843                let _ = self.unshare_internal(cx);
1844            }
1845            ProjectClientState::Remote { remote_id, .. } => {
1846                let _ = self.collab_client.send(proto::LeaveProject {
1847                    project_id: *remote_id,
1848                });
1849                self.disconnected_from_host_internal(cx);
1850            }
1851        }
1852    }
1853
1854    #[cfg(any(test, feature = "test-support"))]
1855    pub async fn example(
1856        root_paths: impl IntoIterator<Item = &Path>,
1857        cx: &mut AsyncApp,
1858    ) -> Entity<Project> {
1859        use clock::FakeSystemClock;
1860
1861        let fs = Arc::new(RealFs::new(None, cx.background_executor().clone()));
1862        let languages = LanguageRegistry::test(cx.background_executor().clone());
1863        let clock = Arc::new(FakeSystemClock::new());
1864        let http_client = http_client::FakeHttpClient::with_404_response();
1865        let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
1866        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1867        let project = cx.update(|cx| {
1868            Project::local(
1869                client,
1870                node_runtime::NodeRuntime::unavailable(),
1871                user_store,
1872                Arc::new(languages),
1873                fs,
1874                None,
1875                false,
1876                cx,
1877            )
1878        });
1879        for path in root_paths {
1880            let (tree, _): (Entity<Worktree>, _) = project
1881                .update(cx, |project, cx| {
1882                    project.find_or_create_worktree(path, true, cx)
1883                })
1884                .await
1885                .unwrap();
1886            tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1887                .await;
1888        }
1889        project
1890    }
1891
1892    #[cfg(any(test, feature = "test-support"))]
1893    pub async fn test(
1894        fs: Arc<dyn Fs>,
1895        root_paths: impl IntoIterator<Item = &Path>,
1896        cx: &mut gpui::TestAppContext,
1897    ) -> Entity<Project> {
1898        Self::test_project(fs, root_paths, false, cx).await
1899    }
1900
1901    #[cfg(any(test, feature = "test-support"))]
1902    pub async fn test_with_worktree_trust(
1903        fs: Arc<dyn Fs>,
1904        root_paths: impl IntoIterator<Item = &Path>,
1905        cx: &mut gpui::TestAppContext,
1906    ) -> Entity<Project> {
1907        Self::test_project(fs, root_paths, true, cx).await
1908    }
1909
1910    #[cfg(any(test, feature = "test-support"))]
1911    async fn test_project(
1912        fs: Arc<dyn Fs>,
1913        root_paths: impl IntoIterator<Item = &Path>,
1914        init_worktree_trust: bool,
1915        cx: &mut gpui::TestAppContext,
1916    ) -> Entity<Project> {
1917        use clock::FakeSystemClock;
1918
1919        let languages = LanguageRegistry::test(cx.executor());
1920        let clock = Arc::new(FakeSystemClock::new());
1921        let http_client = http_client::FakeHttpClient::with_404_response();
1922        let client = cx.update(|cx| client::Client::new(clock, http_client.clone(), cx));
1923        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1924        let project = cx.update(|cx| {
1925            Project::local(
1926                client,
1927                node_runtime::NodeRuntime::unavailable(),
1928                user_store,
1929                Arc::new(languages),
1930                fs,
1931                None,
1932                init_worktree_trust,
1933                cx,
1934            )
1935        });
1936        for path in root_paths {
1937            let (tree, _) = project
1938                .update(cx, |project, cx| {
1939                    project.find_or_create_worktree(path, true, cx)
1940                })
1941                .await
1942                .unwrap();
1943
1944            tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
1945                .await;
1946        }
1947        project
1948    }
1949
1950    #[inline]
1951    pub fn dap_store(&self) -> Entity<DapStore> {
1952        self.dap_store.clone()
1953    }
1954
1955    #[inline]
1956    pub fn breakpoint_store(&self) -> Entity<BreakpointStore> {
1957        self.breakpoint_store.clone()
1958    }
1959
1960    pub fn active_debug_session(&self, cx: &App) -> Option<(Entity<Session>, ActiveStackFrame)> {
1961        let active_position = self.breakpoint_store.read(cx).active_position()?;
1962        let session = self
1963            .dap_store
1964            .read(cx)
1965            .session_by_id(active_position.session_id)?;
1966        Some((session, active_position.clone()))
1967    }
1968
1969    #[inline]
1970    pub fn lsp_store(&self) -> Entity<LspStore> {
1971        self.lsp_store.clone()
1972    }
1973
1974    #[inline]
1975    pub fn worktree_store(&self) -> Entity<WorktreeStore> {
1976        self.worktree_store.clone()
1977    }
1978
1979    #[inline]
1980    pub fn context_server_store(&self) -> Entity<ContextServerStore> {
1981        self.context_server_store.clone()
1982    }
1983
1984    #[inline]
1985    pub fn buffer_for_id(&self, remote_id: BufferId, cx: &App) -> Option<Entity<Buffer>> {
1986        self.buffer_store.read(cx).get(remote_id)
1987    }
1988
1989    #[inline]
1990    pub fn languages(&self) -> &Arc<LanguageRegistry> {
1991        &self.languages
1992    }
1993
1994    #[inline]
1995    pub fn client(&self) -> Arc<Client> {
1996        self.collab_client.clone()
1997    }
1998
1999    #[inline]
2000    pub fn remote_client(&self) -> Option<Entity<RemoteClient>> {
2001        self.remote_client.clone()
2002    }
2003
2004    #[inline]
2005    pub fn user_store(&self) -> Entity<UserStore> {
2006        self.user_store.clone()
2007    }
2008
2009    #[inline]
2010    pub fn node_runtime(&self) -> Option<&NodeRuntime> {
2011        self.node.as_ref()
2012    }
2013
2014    #[inline]
2015    pub fn opened_buffers(&self, cx: &App) -> Vec<Entity<Buffer>> {
2016        self.buffer_store.read(cx).buffers().collect()
2017    }
2018
2019    #[inline]
2020    pub fn environment(&self) -> &Entity<ProjectEnvironment> {
2021        &self.environment
2022    }
2023
2024    #[inline]
2025    pub fn cli_environment(&self, cx: &App) -> Option<HashMap<String, String>> {
2026        self.environment.read(cx).get_cli_environment()
2027    }
2028
2029    #[inline]
2030    pub fn peek_environment_error<'a>(&'a self, cx: &'a App) -> Option<&'a String> {
2031        self.environment.read(cx).peek_environment_error()
2032    }
2033
2034    #[inline]
2035    pub fn pop_environment_error(&mut self, cx: &mut Context<Self>) {
2036        self.environment.update(cx, |environment, _| {
2037            environment.pop_environment_error();
2038        });
2039    }
2040
2041    #[cfg(any(test, feature = "test-support"))]
2042    #[inline]
2043    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &App) -> bool {
2044        self.buffer_store
2045            .read(cx)
2046            .get_by_path(&path.into())
2047            .is_some()
2048    }
2049
2050    #[inline]
2051    pub fn fs(&self) -> &Arc<dyn Fs> {
2052        &self.fs
2053    }
2054
2055    #[inline]
2056    pub fn remote_id(&self) -> Option<u64> {
2057        match self.client_state {
2058            ProjectClientState::Local => None,
2059            ProjectClientState::Shared { remote_id, .. }
2060            | ProjectClientState::Remote { remote_id, .. } => Some(remote_id),
2061        }
2062    }
2063
2064    #[inline]
2065    pub fn supports_terminal(&self, _cx: &App) -> bool {
2066        if self.is_local() {
2067            return true;
2068        }
2069        if self.is_via_remote_server() {
2070            return true;
2071        }
2072
2073        false
2074    }
2075
2076    #[inline]
2077    pub fn remote_connection_state(&self, cx: &App) -> Option<remote::ConnectionState> {
2078        self.remote_client
2079            .as_ref()
2080            .map(|remote| remote.read(cx).connection_state())
2081    }
2082
2083    #[inline]
2084    pub fn remote_connection_options(&self, cx: &App) -> Option<RemoteConnectionOptions> {
2085        self.remote_client
2086            .as_ref()
2087            .map(|remote| remote.read(cx).connection_options())
2088    }
2089
2090    #[inline]
2091    pub fn replica_id(&self) -> ReplicaId {
2092        match self.client_state {
2093            ProjectClientState::Remote { replica_id, .. } => replica_id,
2094            _ => {
2095                if self.remote_client.is_some() {
2096                    ReplicaId::REMOTE_SERVER
2097                } else {
2098                    ReplicaId::LOCAL
2099                }
2100            }
2101        }
2102    }
2103
2104    #[inline]
2105    pub fn task_store(&self) -> &Entity<TaskStore> {
2106        &self.task_store
2107    }
2108
2109    #[inline]
2110    pub fn snippets(&self) -> &Entity<SnippetProvider> {
2111        &self.snippets
2112    }
2113
2114    #[inline]
2115    pub fn search_history(&self, kind: SearchInputKind) -> &SearchHistory {
2116        match kind {
2117            SearchInputKind::Query => &self.search_history,
2118            SearchInputKind::Include => &self.search_included_history,
2119            SearchInputKind::Exclude => &self.search_excluded_history,
2120        }
2121    }
2122
2123    #[inline]
2124    pub fn search_history_mut(&mut self, kind: SearchInputKind) -> &mut SearchHistory {
2125        match kind {
2126            SearchInputKind::Query => &mut self.search_history,
2127            SearchInputKind::Include => &mut self.search_included_history,
2128            SearchInputKind::Exclude => &mut self.search_excluded_history,
2129        }
2130    }
2131
2132    #[inline]
2133    pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
2134        &self.collaborators
2135    }
2136
2137    #[inline]
2138    pub fn host(&self) -> Option<&Collaborator> {
2139        self.collaborators.values().find(|c| c.is_host)
2140    }
2141
2142    #[inline]
2143    pub fn set_worktrees_reordered(&mut self, worktrees_reordered: bool, cx: &mut App) {
2144        self.worktree_store.update(cx, |store, _| {
2145            store.set_worktrees_reordered(worktrees_reordered);
2146        });
2147    }
2148
2149    /// Collect all worktrees, including ones that don't appear in the project panel
2150    #[inline]
2151    pub fn worktrees<'a>(
2152        &self,
2153        cx: &'a App,
2154    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
2155        self.worktree_store.read(cx).worktrees()
2156    }
2157
2158    /// Collect all user-visible worktrees, the ones that appear in the project panel.
2159    #[inline]
2160    pub fn visible_worktrees<'a>(
2161        &'a self,
2162        cx: &'a App,
2163    ) -> impl 'a + DoubleEndedIterator<Item = Entity<Worktree>> {
2164        self.worktree_store.read(cx).visible_worktrees(cx)
2165    }
2166
2167    #[inline]
2168    pub fn worktree_for_root_name(&self, root_name: &str, cx: &App) -> Option<Entity<Worktree>> {
2169        self.visible_worktrees(cx)
2170            .find(|tree| tree.read(cx).root_name() == root_name)
2171    }
2172
2173    #[inline]
2174    pub fn worktree_root_names<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = &'a str> {
2175        self.visible_worktrees(cx)
2176            .map(|tree| tree.read(cx).root_name().as_unix_str())
2177    }
2178
2179    #[inline]
2180    pub fn worktree_for_id(&self, id: WorktreeId, cx: &App) -> Option<Entity<Worktree>> {
2181        self.worktree_store.read(cx).worktree_for_id(id, cx)
2182    }
2183
2184    pub fn worktree_for_entry(
2185        &self,
2186        entry_id: ProjectEntryId,
2187        cx: &App,
2188    ) -> Option<Entity<Worktree>> {
2189        self.worktree_store
2190            .read(cx)
2191            .worktree_for_entry(entry_id, cx)
2192    }
2193
2194    #[inline]
2195    pub fn worktree_id_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<WorktreeId> {
2196        self.worktree_for_entry(entry_id, cx)
2197            .map(|worktree| worktree.read(cx).id())
2198    }
2199
2200    /// Checks if the entry is the root of a worktree.
2201    #[inline]
2202    pub fn entry_is_worktree_root(&self, entry_id: ProjectEntryId, cx: &App) -> bool {
2203        self.worktree_for_entry(entry_id, cx)
2204            .map(|worktree| {
2205                worktree
2206                    .read(cx)
2207                    .root_entry()
2208                    .is_some_and(|e| e.id == entry_id)
2209            })
2210            .unwrap_or(false)
2211    }
2212
2213    #[inline]
2214    pub fn project_path_git_status(
2215        &self,
2216        project_path: &ProjectPath,
2217        cx: &App,
2218    ) -> Option<FileStatus> {
2219        self.git_store
2220            .read(cx)
2221            .project_path_git_status(project_path, cx)
2222    }
2223
2224    #[inline]
2225    pub fn visibility_for_paths(
2226        &self,
2227        paths: &[PathBuf],
2228        metadatas: &[Metadata],
2229        exclude_sub_dirs: bool,
2230        cx: &App,
2231    ) -> Option<bool> {
2232        paths
2233            .iter()
2234            .zip(metadatas)
2235            .map(|(path, metadata)| self.visibility_for_path(path, metadata, exclude_sub_dirs, cx))
2236            .max()
2237            .flatten()
2238    }
2239
2240    pub fn visibility_for_path(
2241        &self,
2242        path: &Path,
2243        metadata: &Metadata,
2244        exclude_sub_dirs: bool,
2245        cx: &App,
2246    ) -> Option<bool> {
2247        let path = SanitizedPath::new(path).as_path();
2248        self.worktrees(cx)
2249            .filter_map(|worktree| {
2250                let worktree = worktree.read(cx);
2251                let abs_path = worktree.as_local()?.abs_path();
2252                let contains = path == abs_path.as_ref()
2253                    || (path.starts_with(abs_path) && (!exclude_sub_dirs || !metadata.is_dir));
2254                contains.then(|| worktree.is_visible())
2255            })
2256            .max()
2257    }
2258
2259    pub fn create_entry(
2260        &mut self,
2261        project_path: impl Into<ProjectPath>,
2262        is_directory: bool,
2263        cx: &mut Context<Self>,
2264    ) -> Task<Result<CreatedEntry>> {
2265        let project_path = project_path.into();
2266        let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) else {
2267            return Task::ready(Err(anyhow!(format!(
2268                "No worktree for path {project_path:?}"
2269            ))));
2270        };
2271        worktree.update(cx, |worktree, cx| {
2272            worktree.create_entry(project_path.path, is_directory, None, cx)
2273        })
2274    }
2275
2276    #[inline]
2277    pub fn copy_entry(
2278        &mut self,
2279        entry_id: ProjectEntryId,
2280        new_project_path: ProjectPath,
2281        cx: &mut Context<Self>,
2282    ) -> Task<Result<Option<Entry>>> {
2283        self.worktree_store.update(cx, |worktree_store, cx| {
2284            worktree_store.copy_entry(entry_id, new_project_path, cx)
2285        })
2286    }
2287
2288    /// Renames the project entry with given `entry_id`.
2289    ///
2290    /// `new_path` is a relative path to worktree root.
2291    /// If root entry is renamed then its new root name is used instead.
2292    pub fn rename_entry(
2293        &mut self,
2294        entry_id: ProjectEntryId,
2295        new_path: ProjectPath,
2296        cx: &mut Context<Self>,
2297    ) -> Task<Result<CreatedEntry>> {
2298        let worktree_store = self.worktree_store.clone();
2299        let Some((worktree, old_path, is_dir)) = worktree_store
2300            .read(cx)
2301            .worktree_and_entry_for_id(entry_id, cx)
2302            .map(|(worktree, entry)| (worktree, entry.path.clone(), entry.is_dir()))
2303        else {
2304            return Task::ready(Err(anyhow!(format!("No worktree for entry {entry_id:?}"))));
2305        };
2306
2307        let worktree_id = worktree.read(cx).id();
2308        let is_root_entry = self.entry_is_worktree_root(entry_id, cx);
2309
2310        let lsp_store = self.lsp_store().downgrade();
2311        cx.spawn(async move |project, cx| {
2312            let (old_abs_path, new_abs_path) = {
2313                let root_path = worktree.read_with(cx, |this, _| this.abs_path());
2314                let new_abs_path = if is_root_entry {
2315                    root_path
2316                        .parent()
2317                        .unwrap()
2318                        .join(new_path.path.as_std_path())
2319                } else {
2320                    root_path.join(&new_path.path.as_std_path())
2321                };
2322                (root_path.join(old_path.as_std_path()), new_abs_path)
2323            };
2324            let transaction = LspStore::will_rename_entry(
2325                lsp_store.clone(),
2326                worktree_id,
2327                &old_abs_path,
2328                &new_abs_path,
2329                is_dir,
2330                cx.clone(),
2331            )
2332            .await;
2333
2334            let entry = worktree_store
2335                .update(cx, |worktree_store, cx| {
2336                    worktree_store.rename_entry(entry_id, new_path.clone(), cx)
2337                })
2338                .await?;
2339
2340            project
2341                .update(cx, |_, cx| {
2342                    cx.emit(Event::EntryRenamed(
2343                        transaction,
2344                        new_path.clone(),
2345                        new_abs_path.clone(),
2346                    ));
2347                })
2348                .ok();
2349
2350            lsp_store
2351                .read_with(cx, |this, _| {
2352                    this.did_rename_entry(worktree_id, &old_abs_path, &new_abs_path, is_dir);
2353                })
2354                .ok();
2355            Ok(entry)
2356        })
2357    }
2358
2359    #[inline]
2360    pub fn delete_file(
2361        &mut self,
2362        path: ProjectPath,
2363        trash: bool,
2364        cx: &mut Context<Self>,
2365    ) -> Option<Task<Result<()>>> {
2366        let entry = self.entry_for_path(&path, cx)?;
2367        self.delete_entry(entry.id, trash, cx)
2368    }
2369
2370    #[inline]
2371    pub fn delete_entry(
2372        &mut self,
2373        entry_id: ProjectEntryId,
2374        trash: bool,
2375        cx: &mut Context<Self>,
2376    ) -> Option<Task<Result<()>>> {
2377        let worktree = self.worktree_for_entry(entry_id, cx)?;
2378        cx.emit(Event::DeletedEntry(worktree.read(cx).id(), entry_id));
2379        worktree.update(cx, |worktree, cx| {
2380            worktree.delete_entry(entry_id, trash, cx)
2381        })
2382    }
2383
2384    #[inline]
2385    pub fn expand_entry(
2386        &mut self,
2387        worktree_id: WorktreeId,
2388        entry_id: ProjectEntryId,
2389        cx: &mut Context<Self>,
2390    ) -> Option<Task<Result<()>>> {
2391        let worktree = self.worktree_for_id(worktree_id, cx)?;
2392        worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
2393    }
2394
2395    pub fn expand_all_for_entry(
2396        &mut self,
2397        worktree_id: WorktreeId,
2398        entry_id: ProjectEntryId,
2399        cx: &mut Context<Self>,
2400    ) -> Option<Task<Result<()>>> {
2401        let worktree = self.worktree_for_id(worktree_id, cx)?;
2402        let task = worktree.update(cx, |worktree, cx| {
2403            worktree.expand_all_for_entry(entry_id, cx)
2404        });
2405        Some(cx.spawn(async move |this, cx| {
2406            task.context("no task")?.await?;
2407            this.update(cx, |_, cx| {
2408                cx.emit(Event::ExpandedAllForEntry(worktree_id, entry_id));
2409            })?;
2410            Ok(())
2411        }))
2412    }
2413
2414    pub fn shared(&mut self, project_id: u64, cx: &mut Context<Self>) -> Result<()> {
2415        anyhow::ensure!(
2416            matches!(self.client_state, ProjectClientState::Local),
2417            "project was already shared"
2418        );
2419
2420        self.client_subscriptions.extend([
2421            self.collab_client
2422                .subscribe_to_entity(project_id)?
2423                .set_entity(&cx.entity(), &cx.to_async()),
2424            self.collab_client
2425                .subscribe_to_entity(project_id)?
2426                .set_entity(&self.worktree_store, &cx.to_async()),
2427            self.collab_client
2428                .subscribe_to_entity(project_id)?
2429                .set_entity(&self.buffer_store, &cx.to_async()),
2430            self.collab_client
2431                .subscribe_to_entity(project_id)?
2432                .set_entity(&self.lsp_store, &cx.to_async()),
2433            self.collab_client
2434                .subscribe_to_entity(project_id)?
2435                .set_entity(&self.settings_observer, &cx.to_async()),
2436            self.collab_client
2437                .subscribe_to_entity(project_id)?
2438                .set_entity(&self.dap_store, &cx.to_async()),
2439            self.collab_client
2440                .subscribe_to_entity(project_id)?
2441                .set_entity(&self.breakpoint_store, &cx.to_async()),
2442            self.collab_client
2443                .subscribe_to_entity(project_id)?
2444                .set_entity(&self.git_store, &cx.to_async()),
2445        ]);
2446
2447        self.buffer_store.update(cx, |buffer_store, cx| {
2448            buffer_store.shared(project_id, self.collab_client.clone().into(), cx)
2449        });
2450        self.worktree_store.update(cx, |worktree_store, cx| {
2451            worktree_store.shared(project_id, self.collab_client.clone().into(), cx);
2452        });
2453        self.lsp_store.update(cx, |lsp_store, cx| {
2454            lsp_store.shared(project_id, self.collab_client.clone().into(), cx)
2455        });
2456        self.breakpoint_store.update(cx, |breakpoint_store, _| {
2457            breakpoint_store.shared(project_id, self.collab_client.clone().into())
2458        });
2459        self.dap_store.update(cx, |dap_store, cx| {
2460            dap_store.shared(project_id, self.collab_client.clone().into(), cx);
2461        });
2462        self.task_store.update(cx, |task_store, cx| {
2463            task_store.shared(project_id, self.collab_client.clone().into(), cx);
2464        });
2465        self.settings_observer.update(cx, |settings_observer, cx| {
2466            settings_observer.shared(project_id, self.collab_client.clone().into(), cx)
2467        });
2468        self.git_store.update(cx, |git_store, cx| {
2469            git_store.shared(project_id, self.collab_client.clone().into(), cx)
2470        });
2471
2472        self.client_state = ProjectClientState::Shared {
2473            remote_id: project_id,
2474        };
2475
2476        cx.emit(Event::RemoteIdChanged(Some(project_id)));
2477        Ok(())
2478    }
2479
2480    pub fn reshared(
2481        &mut self,
2482        message: proto::ResharedProject,
2483        cx: &mut Context<Self>,
2484    ) -> Result<()> {
2485        self.buffer_store
2486            .update(cx, |buffer_store, _| buffer_store.forget_shared_buffers());
2487        self.set_collaborators_from_proto(message.collaborators, cx)?;
2488
2489        self.worktree_store.update(cx, |worktree_store, cx| {
2490            worktree_store.send_project_updates(cx);
2491        });
2492        if let Some(remote_id) = self.remote_id() {
2493            self.git_store.update(cx, |git_store, cx| {
2494                git_store.shared(remote_id, self.collab_client.clone().into(), cx)
2495            });
2496        }
2497        cx.emit(Event::Reshared);
2498        Ok(())
2499    }
2500
2501    pub fn rejoined(
2502        &mut self,
2503        message: proto::RejoinedProject,
2504        message_id: u32,
2505        cx: &mut Context<Self>,
2506    ) -> Result<()> {
2507        cx.update_global::<SettingsStore, _>(|store, cx| {
2508            for worktree_metadata in &message.worktrees {
2509                store
2510                    .clear_local_settings(WorktreeId::from_proto(worktree_metadata.id), cx)
2511                    .log_err();
2512            }
2513        });
2514
2515        self.join_project_response_message_id = message_id;
2516        self.set_worktrees_from_proto(message.worktrees, cx)?;
2517        self.set_collaborators_from_proto(message.collaborators, cx)?;
2518
2519        let project = cx.weak_entity();
2520        self.lsp_store.update(cx, |lsp_store, cx| {
2521            lsp_store.set_language_server_statuses_from_proto(
2522                project,
2523                message.language_servers,
2524                message.language_server_capabilities,
2525                cx,
2526            )
2527        });
2528        self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
2529            .unwrap();
2530        cx.emit(Event::Rejoined);
2531        Ok(())
2532    }
2533
2534    #[inline]
2535    pub fn unshare(&mut self, cx: &mut Context<Self>) -> Result<()> {
2536        self.unshare_internal(cx)?;
2537        cx.emit(Event::RemoteIdChanged(None));
2538        Ok(())
2539    }
2540
2541    fn unshare_internal(&mut self, cx: &mut App) -> Result<()> {
2542        anyhow::ensure!(
2543            !self.is_via_collab(),
2544            "attempted to unshare a remote project"
2545        );
2546
2547        if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
2548            self.client_state = ProjectClientState::Local;
2549            self.collaborators.clear();
2550            self.client_subscriptions.clear();
2551            self.worktree_store.update(cx, |store, cx| {
2552                store.unshared(cx);
2553            });
2554            self.buffer_store.update(cx, |buffer_store, cx| {
2555                buffer_store.forget_shared_buffers();
2556                buffer_store.unshared(cx)
2557            });
2558            self.task_store.update(cx, |task_store, cx| {
2559                task_store.unshared(cx);
2560            });
2561            self.breakpoint_store.update(cx, |breakpoint_store, cx| {
2562                breakpoint_store.unshared(cx);
2563            });
2564            self.dap_store.update(cx, |dap_store, cx| {
2565                dap_store.unshared(cx);
2566            });
2567            self.settings_observer.update(cx, |settings_observer, cx| {
2568                settings_observer.unshared(cx);
2569            });
2570            self.git_store.update(cx, |git_store, cx| {
2571                git_store.unshared(cx);
2572            });
2573
2574            self.collab_client
2575                .send(proto::UnshareProject {
2576                    project_id: remote_id,
2577                })
2578                .ok();
2579            Ok(())
2580        } else {
2581            anyhow::bail!("attempted to unshare an unshared project");
2582        }
2583    }
2584
2585    pub fn disconnected_from_host(&mut self, cx: &mut Context<Self>) {
2586        if self.is_disconnected(cx) {
2587            return;
2588        }
2589        self.disconnected_from_host_internal(cx);
2590        cx.emit(Event::DisconnectedFromHost);
2591    }
2592
2593    pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut Context<Self>) {
2594        let new_capability =
2595            if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
2596                Capability::ReadWrite
2597            } else {
2598                Capability::ReadOnly
2599            };
2600        if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
2601            if *capability == new_capability {
2602                return;
2603            }
2604
2605            *capability = new_capability;
2606            for buffer in self.opened_buffers(cx) {
2607                buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
2608            }
2609        }
2610    }
2611
2612    fn disconnected_from_host_internal(&mut self, cx: &mut App) {
2613        if let ProjectClientState::Remote {
2614            sharing_has_stopped,
2615            ..
2616        } = &mut self.client_state
2617        {
2618            *sharing_has_stopped = true;
2619            self.collaborators.clear();
2620            self.worktree_store.update(cx, |store, cx| {
2621                store.disconnected_from_host(cx);
2622            });
2623            self.buffer_store.update(cx, |buffer_store, cx| {
2624                buffer_store.disconnected_from_host(cx)
2625            });
2626            self.lsp_store
2627                .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
2628        }
2629    }
2630
2631    #[inline]
2632    pub fn close(&mut self, cx: &mut Context<Self>) {
2633        cx.emit(Event::Closed);
2634    }
2635
2636    #[inline]
2637    pub fn is_disconnected(&self, cx: &App) -> bool {
2638        match &self.client_state {
2639            ProjectClientState::Remote {
2640                sharing_has_stopped,
2641                ..
2642            } => *sharing_has_stopped,
2643            ProjectClientState::Local if self.is_via_remote_server() => {
2644                self.remote_client_is_disconnected(cx)
2645            }
2646            _ => false,
2647        }
2648    }
2649
2650    #[inline]
2651    fn remote_client_is_disconnected(&self, cx: &App) -> bool {
2652        self.remote_client
2653            .as_ref()
2654            .map(|remote| remote.read(cx).is_disconnected())
2655            .unwrap_or(false)
2656    }
2657
2658    #[inline]
2659    pub fn capability(&self) -> Capability {
2660        match &self.client_state {
2661            ProjectClientState::Remote { capability, .. } => *capability,
2662            ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
2663        }
2664    }
2665
2666    #[inline]
2667    pub fn is_read_only(&self, cx: &App) -> bool {
2668        self.is_disconnected(cx) || !self.capability().editable()
2669    }
2670
2671    #[inline]
2672    pub fn is_local(&self) -> bool {
2673        match &self.client_state {
2674            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2675                self.remote_client.is_none()
2676            }
2677            ProjectClientState::Remote { .. } => false,
2678        }
2679    }
2680
2681    /// Whether this project is a remote server (not counting collab).
2682    #[inline]
2683    pub fn is_via_remote_server(&self) -> bool {
2684        match &self.client_state {
2685            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2686                self.remote_client.is_some()
2687            }
2688            ProjectClientState::Remote { .. } => false,
2689        }
2690    }
2691
2692    /// Whether this project is from collab (not counting remote servers).
2693    #[inline]
2694    pub fn is_via_collab(&self) -> bool {
2695        match &self.client_state {
2696            ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
2697            ProjectClientState::Remote { .. } => true,
2698        }
2699    }
2700
2701    /// `!self.is_local()`
2702    #[inline]
2703    pub fn is_remote(&self) -> bool {
2704        debug_assert_eq!(
2705            !self.is_local(),
2706            self.is_via_collab() || self.is_via_remote_server()
2707        );
2708        !self.is_local()
2709    }
2710
2711    pub fn disable_worktree_scanner(&mut self, cx: &mut Context<Self>) {
2712        self.worktree_store.update(cx, |worktree_store, _cx| {
2713            worktree_store.disable_scanner();
2714        });
2715    }
2716
2717    #[inline]
2718    pub fn create_buffer(
2719        &mut self,
2720        searchable: bool,
2721        cx: &mut Context<Self>,
2722    ) -> Task<Result<Entity<Buffer>>> {
2723        self.buffer_store.update(cx, |buffer_store, cx| {
2724            buffer_store.create_buffer(searchable, cx)
2725        })
2726    }
2727
2728    #[inline]
2729    pub fn create_local_buffer(
2730        &mut self,
2731        text: &str,
2732        language: Option<Arc<Language>>,
2733        project_searchable: bool,
2734        cx: &mut Context<Self>,
2735    ) -> Entity<Buffer> {
2736        if self.is_remote() {
2737            panic!("called create_local_buffer on a remote project")
2738        }
2739        self.buffer_store.update(cx, |buffer_store, cx| {
2740            buffer_store.create_local_buffer(text, language, project_searchable, cx)
2741        })
2742    }
2743
2744    pub fn open_path(
2745        &mut self,
2746        path: ProjectPath,
2747        cx: &mut Context<Self>,
2748    ) -> Task<Result<(Option<ProjectEntryId>, Entity<Buffer>)>> {
2749        let task = self.open_buffer(path, cx);
2750        cx.spawn(async move |_project, cx| {
2751            let buffer = task.await?;
2752            let project_entry_id = buffer.read_with(cx, |buffer, _cx| {
2753                File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id())
2754            });
2755
2756            Ok((project_entry_id, buffer))
2757        })
2758    }
2759
2760    pub fn open_local_buffer(
2761        &mut self,
2762        abs_path: impl AsRef<Path>,
2763        cx: &mut Context<Self>,
2764    ) -> Task<Result<Entity<Buffer>>> {
2765        let worktree_task = self.find_or_create_worktree(abs_path.as_ref(), false, cx);
2766        cx.spawn(async move |this, cx| {
2767            let (worktree, relative_path) = worktree_task.await?;
2768            this.update(cx, |this, cx| {
2769                this.open_buffer((worktree.read(cx).id(), relative_path), cx)
2770            })?
2771            .await
2772        })
2773    }
2774
2775    #[cfg(any(test, feature = "test-support"))]
2776    pub fn open_local_buffer_with_lsp(
2777        &mut self,
2778        abs_path: impl AsRef<Path>,
2779        cx: &mut Context<Self>,
2780    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
2781        if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
2782            self.open_buffer_with_lsp((worktree.read(cx).id(), relative_path), cx)
2783        } else {
2784            Task::ready(Err(anyhow!("no such path")))
2785        }
2786    }
2787
2788    pub fn open_buffer(
2789        &mut self,
2790        path: impl Into<ProjectPath>,
2791        cx: &mut App,
2792    ) -> Task<Result<Entity<Buffer>>> {
2793        if self.is_disconnected(cx) {
2794            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2795        }
2796
2797        self.buffer_store.update(cx, |buffer_store, cx| {
2798            buffer_store.open_buffer(path.into(), cx)
2799        })
2800    }
2801
2802    #[cfg(any(test, feature = "test-support"))]
2803    pub fn open_buffer_with_lsp(
2804        &mut self,
2805        path: impl Into<ProjectPath>,
2806        cx: &mut Context<Self>,
2807    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
2808        let buffer = self.open_buffer(path, cx);
2809        cx.spawn(async move |this, cx| {
2810            let buffer = buffer.await?;
2811            let handle = this.update(cx, |project, cx| {
2812                project.register_buffer_with_language_servers(&buffer, cx)
2813            })?;
2814            Ok((buffer, handle))
2815        })
2816    }
2817
2818    pub fn register_buffer_with_language_servers(
2819        &self,
2820        buffer: &Entity<Buffer>,
2821        cx: &mut App,
2822    ) -> OpenLspBufferHandle {
2823        self.lsp_store.update(cx, |lsp_store, cx| {
2824            lsp_store.register_buffer_with_language_servers(buffer, HashSet::default(), false, cx)
2825        })
2826    }
2827
2828    pub fn open_unstaged_diff(
2829        &mut self,
2830        buffer: Entity<Buffer>,
2831        cx: &mut Context<Self>,
2832    ) -> Task<Result<Entity<BufferDiff>>> {
2833        if self.is_disconnected(cx) {
2834            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2835        }
2836        self.git_store
2837            .update(cx, |git_store, cx| git_store.open_unstaged_diff(buffer, cx))
2838    }
2839
2840    pub fn open_uncommitted_diff(
2841        &mut self,
2842        buffer: Entity<Buffer>,
2843        cx: &mut Context<Self>,
2844    ) -> Task<Result<Entity<BufferDiff>>> {
2845        if self.is_disconnected(cx) {
2846            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2847        }
2848        self.git_store.update(cx, |git_store, cx| {
2849            git_store.open_uncommitted_diff(buffer, cx)
2850        })
2851    }
2852
2853    pub fn open_buffer_by_id(
2854        &mut self,
2855        id: BufferId,
2856        cx: &mut Context<Self>,
2857    ) -> Task<Result<Entity<Buffer>>> {
2858        if let Some(buffer) = self.buffer_for_id(id, cx) {
2859            Task::ready(Ok(buffer))
2860        } else if self.is_local() || self.is_via_remote_server() {
2861            Task::ready(Err(anyhow!("buffer {id} does not exist")))
2862        } else if let Some(project_id) = self.remote_id() {
2863            let request = self.collab_client.request(proto::OpenBufferById {
2864                project_id,
2865                id: id.into(),
2866            });
2867            cx.spawn(async move |project, cx| {
2868                let buffer_id = BufferId::new(request.await?.buffer_id)?;
2869                project
2870                    .update(cx, |project, cx| {
2871                        project.buffer_store.update(cx, |buffer_store, cx| {
2872                            buffer_store.wait_for_remote_buffer(buffer_id, cx)
2873                        })
2874                    })?
2875                    .await
2876            })
2877        } else {
2878            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
2879        }
2880    }
2881
2882    pub fn save_buffers(
2883        &self,
2884        buffers: HashSet<Entity<Buffer>>,
2885        cx: &mut Context<Self>,
2886    ) -> Task<Result<()>> {
2887        cx.spawn(async move |this, cx| {
2888            let save_tasks = buffers.into_iter().filter_map(|buffer| {
2889                this.update(cx, |this, cx| this.save_buffer(buffer, cx))
2890                    .ok()
2891            });
2892            try_join_all(save_tasks).await?;
2893            Ok(())
2894        })
2895    }
2896
2897    pub fn save_buffer(&self, buffer: Entity<Buffer>, cx: &mut Context<Self>) -> Task<Result<()>> {
2898        self.buffer_store
2899            .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
2900    }
2901
2902    pub fn save_buffer_as(
2903        &mut self,
2904        buffer: Entity<Buffer>,
2905        path: ProjectPath,
2906        cx: &mut Context<Self>,
2907    ) -> Task<Result<()>> {
2908        self.buffer_store.update(cx, |buffer_store, cx| {
2909            buffer_store.save_buffer_as(buffer.clone(), path, cx)
2910        })
2911    }
2912
2913    pub fn get_open_buffer(&self, path: &ProjectPath, cx: &App) -> Option<Entity<Buffer>> {
2914        self.buffer_store.read(cx).get_by_path(path)
2915    }
2916
2917    fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
2918        {
2919            let mut remotely_created_models = self.remotely_created_models.lock();
2920            if remotely_created_models.retain_count > 0 {
2921                remotely_created_models.buffers.push(buffer.clone())
2922            }
2923        }
2924
2925        self.request_buffer_diff_recalculation(buffer, cx);
2926
2927        cx.subscribe(buffer, |this, buffer, event, cx| {
2928            this.on_buffer_event(buffer, event, cx);
2929        })
2930        .detach();
2931
2932        Ok(())
2933    }
2934
2935    pub fn open_image(
2936        &mut self,
2937        path: impl Into<ProjectPath>,
2938        cx: &mut Context<Self>,
2939    ) -> Task<Result<Entity<ImageItem>>> {
2940        if self.is_disconnected(cx) {
2941            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2942        }
2943
2944        let open_image_task = self.image_store.update(cx, |image_store, cx| {
2945            image_store.open_image(path.into(), cx)
2946        });
2947
2948        let weak_project = cx.entity().downgrade();
2949        cx.spawn(async move |_, cx| {
2950            let image_item = open_image_task.await?;
2951
2952            // Check if metadata already exists (e.g., for remote images)
2953            let needs_metadata =
2954                cx.read_entity(&image_item, |item, _| item.image_metadata.is_none());
2955
2956            if needs_metadata {
2957                let project = weak_project.upgrade().context("Project dropped")?;
2958                let metadata =
2959                    ImageItem::load_image_metadata(image_item.clone(), project, cx).await?;
2960                image_item.update(cx, |image_item, cx| {
2961                    image_item.image_metadata = Some(metadata);
2962                    cx.emit(ImageItemEvent::MetadataUpdated);
2963                });
2964            }
2965
2966            Ok(image_item)
2967        })
2968    }
2969
2970    async fn send_buffer_ordered_messages(
2971        project: WeakEntity<Self>,
2972        rx: UnboundedReceiver<BufferOrderedMessage>,
2973        cx: &mut AsyncApp,
2974    ) -> Result<()> {
2975        const MAX_BATCH_SIZE: usize = 128;
2976
2977        let mut operations_by_buffer_id = HashMap::default();
2978        async fn flush_operations(
2979            this: &WeakEntity<Project>,
2980            operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
2981            needs_resync_with_host: &mut bool,
2982            is_local: bool,
2983            cx: &mut AsyncApp,
2984        ) -> Result<()> {
2985            for (buffer_id, operations) in operations_by_buffer_id.drain() {
2986                let request = this.read_with(cx, |this, _| {
2987                    let project_id = this.remote_id()?;
2988                    Some(this.collab_client.request(proto::UpdateBuffer {
2989                        buffer_id: buffer_id.into(),
2990                        project_id,
2991                        operations,
2992                    }))
2993                })?;
2994                if let Some(request) = request
2995                    && request.await.is_err()
2996                    && !is_local
2997                {
2998                    *needs_resync_with_host = true;
2999                    break;
3000                }
3001            }
3002            Ok(())
3003        }
3004
3005        let mut needs_resync_with_host = false;
3006        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
3007
3008        while let Some(changes) = changes.next().await {
3009            let is_local = project.read_with(cx, |this, _| this.is_local())?;
3010
3011            for change in changes {
3012                match change {
3013                    BufferOrderedMessage::Operation {
3014                        buffer_id,
3015                        operation,
3016                    } => {
3017                        if needs_resync_with_host {
3018                            continue;
3019                        }
3020
3021                        operations_by_buffer_id
3022                            .entry(buffer_id)
3023                            .or_insert(Vec::new())
3024                            .push(operation);
3025                    }
3026
3027                    BufferOrderedMessage::Resync => {
3028                        operations_by_buffer_id.clear();
3029                        if project
3030                            .update(cx, |this, cx| this.synchronize_remote_buffers(cx))?
3031                            .await
3032                            .is_ok()
3033                        {
3034                            needs_resync_with_host = false;
3035                        }
3036                    }
3037
3038                    BufferOrderedMessage::LanguageServerUpdate {
3039                        language_server_id,
3040                        message,
3041                        name,
3042                    } => {
3043                        flush_operations(
3044                            &project,
3045                            &mut operations_by_buffer_id,
3046                            &mut needs_resync_with_host,
3047                            is_local,
3048                            cx,
3049                        )
3050                        .await?;
3051
3052                        project.read_with(cx, |project, _| {
3053                            if let Some(project_id) = project.remote_id() {
3054                                project
3055                                    .collab_client
3056                                    .send(proto::UpdateLanguageServer {
3057                                        project_id,
3058                                        server_name: name.map(|name| String::from(name.0)),
3059                                        language_server_id: language_server_id.to_proto(),
3060                                        variant: Some(message),
3061                                    })
3062                                    .log_err();
3063                            }
3064                        })?;
3065                    }
3066                }
3067            }
3068
3069            flush_operations(
3070                &project,
3071                &mut operations_by_buffer_id,
3072                &mut needs_resync_with_host,
3073                is_local,
3074                cx,
3075            )
3076            .await?;
3077        }
3078
3079        Ok(())
3080    }
3081
3082    fn on_buffer_store_event(
3083        &mut self,
3084        _: Entity<BufferStore>,
3085        event: &BufferStoreEvent,
3086        cx: &mut Context<Self>,
3087    ) {
3088        match event {
3089            BufferStoreEvent::BufferAdded(buffer) => {
3090                self.register_buffer(buffer, cx).log_err();
3091            }
3092            BufferStoreEvent::BufferDropped(buffer_id) => {
3093                if let Some(ref remote_client) = self.remote_client {
3094                    remote_client
3095                        .read(cx)
3096                        .proto_client()
3097                        .send(proto::CloseBuffer {
3098                            project_id: 0,
3099                            buffer_id: buffer_id.to_proto(),
3100                        })
3101                        .log_err();
3102                }
3103            }
3104            _ => {}
3105        }
3106    }
3107
3108    fn on_image_store_event(
3109        &mut self,
3110        _: Entity<ImageStore>,
3111        event: &ImageStoreEvent,
3112        cx: &mut Context<Self>,
3113    ) {
3114        match event {
3115            ImageStoreEvent::ImageAdded(image) => {
3116                cx.subscribe(image, |this, image, event, cx| {
3117                    this.on_image_event(image, event, cx);
3118                })
3119                .detach();
3120            }
3121        }
3122    }
3123
3124    fn on_dap_store_event(
3125        &mut self,
3126        _: Entity<DapStore>,
3127        event: &DapStoreEvent,
3128        cx: &mut Context<Self>,
3129    ) {
3130        if let DapStoreEvent::Notification(message) = event {
3131            cx.emit(Event::Toast {
3132                notification_id: "dap".into(),
3133                message: message.clone(),
3134            });
3135        }
3136    }
3137
3138    fn on_lsp_store_event(
3139        &mut self,
3140        _: Entity<LspStore>,
3141        event: &LspStoreEvent,
3142        cx: &mut Context<Self>,
3143    ) {
3144        match event {
3145            LspStoreEvent::DiagnosticsUpdated { server_id, paths } => {
3146                cx.emit(Event::DiagnosticsUpdated {
3147                    paths: paths.clone(),
3148                    language_server_id: *server_id,
3149                })
3150            }
3151            LspStoreEvent::LanguageServerAdded(server_id, name, worktree_id) => cx.emit(
3152                Event::LanguageServerAdded(*server_id, name.clone(), *worktree_id),
3153            ),
3154            LspStoreEvent::LanguageServerRemoved(server_id) => {
3155                cx.emit(Event::LanguageServerRemoved(*server_id))
3156            }
3157            LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
3158                Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
3159            ),
3160            LspStoreEvent::LanguageDetected {
3161                buffer,
3162                new_language,
3163            } => {
3164                let Some(_) = new_language else {
3165                    cx.emit(Event::LanguageNotFound(buffer.clone()));
3166                    return;
3167                };
3168            }
3169            LspStoreEvent::RefreshInlayHints {
3170                server_id,
3171                request_id,
3172            } => cx.emit(Event::RefreshInlayHints {
3173                server_id: *server_id,
3174                request_id: *request_id,
3175            }),
3176            LspStoreEvent::RefreshCodeLens => cx.emit(Event::RefreshCodeLens),
3177            LspStoreEvent::LanguageServerPrompt(prompt) => {
3178                cx.emit(Event::LanguageServerPrompt(prompt.clone()))
3179            }
3180            LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
3181                cx.emit(Event::DiskBasedDiagnosticsStarted {
3182                    language_server_id: *language_server_id,
3183                });
3184            }
3185            LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
3186                cx.emit(Event::DiskBasedDiagnosticsFinished {
3187                    language_server_id: *language_server_id,
3188                });
3189            }
3190            LspStoreEvent::LanguageServerUpdate {
3191                language_server_id,
3192                name,
3193                message,
3194            } => {
3195                if self.is_local() {
3196                    self.enqueue_buffer_ordered_message(
3197                        BufferOrderedMessage::LanguageServerUpdate {
3198                            language_server_id: *language_server_id,
3199                            message: message.clone(),
3200                            name: name.clone(),
3201                        },
3202                    )
3203                    .ok();
3204                }
3205
3206                match message {
3207                    proto::update_language_server::Variant::MetadataUpdated(update) => {
3208                        self.lsp_store.update(cx, |lsp_store, _| {
3209                            if let Some(capabilities) = update
3210                                .capabilities
3211                                .as_ref()
3212                                .and_then(|capabilities| serde_json::from_str(capabilities).ok())
3213                            {
3214                                lsp_store
3215                                    .lsp_server_capabilities
3216                                    .insert(*language_server_id, capabilities);
3217                            }
3218
3219                            if let Some(language_server_status) = lsp_store
3220                                .language_server_statuses
3221                                .get_mut(language_server_id)
3222                            {
3223                                if let Some(binary) = &update.binary {
3224                                    language_server_status.binary = Some(LanguageServerBinary {
3225                                        path: PathBuf::from(&binary.path),
3226                                        arguments: binary
3227                                            .arguments
3228                                            .iter()
3229                                            .map(OsString::from)
3230                                            .collect(),
3231                                        env: None,
3232                                    });
3233                                }
3234
3235                                language_server_status.configuration = update
3236                                    .configuration
3237                                    .as_ref()
3238                                    .and_then(|config_str| serde_json::from_str(config_str).ok());
3239
3240                                language_server_status.workspace_folders = update
3241                                    .workspace_folders
3242                                    .iter()
3243                                    .filter_map(|uri_str| lsp::Uri::from_str(uri_str).ok())
3244                                    .collect();
3245                            }
3246                        });
3247                    }
3248                    proto::update_language_server::Variant::RegisteredForBuffer(update) => {
3249                        if let Some(buffer_id) = BufferId::new(update.buffer_id).ok() {
3250                            cx.emit(Event::LanguageServerBufferRegistered {
3251                                buffer_id,
3252                                server_id: *language_server_id,
3253                                buffer_abs_path: PathBuf::from(&update.buffer_abs_path),
3254                                name: name.clone(),
3255                            });
3256                        }
3257                    }
3258                    _ => (),
3259                }
3260            }
3261            LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
3262                notification_id: "lsp".into(),
3263                message: message.clone(),
3264            }),
3265            LspStoreEvent::SnippetEdit {
3266                buffer_id,
3267                edits,
3268                most_recent_edit,
3269            } => {
3270                if most_recent_edit.replica_id == self.replica_id() {
3271                    cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
3272                }
3273            }
3274            LspStoreEvent::WorkspaceEditApplied(transaction) => {
3275                cx.emit(Event::WorkspaceEditApplied(transaction.clone()))
3276            }
3277        }
3278    }
3279
3280    fn on_remote_client_event(
3281        &mut self,
3282        _: Entity<RemoteClient>,
3283        event: &remote::RemoteClientEvent,
3284        cx: &mut Context<Self>,
3285    ) {
3286        match event {
3287            remote::RemoteClientEvent::Disconnected => {
3288                self.worktree_store.update(cx, |store, cx| {
3289                    store.disconnected_from_host(cx);
3290                });
3291                self.buffer_store.update(cx, |buffer_store, cx| {
3292                    buffer_store.disconnected_from_host(cx)
3293                });
3294                self.lsp_store.update(cx, |lsp_store, _cx| {
3295                    lsp_store.disconnected_from_ssh_remote()
3296                });
3297                cx.emit(Event::DisconnectedFromRemote);
3298            }
3299        }
3300    }
3301
3302    fn on_settings_observer_event(
3303        &mut self,
3304        _: Entity<SettingsObserver>,
3305        event: &SettingsObserverEvent,
3306        cx: &mut Context<Self>,
3307    ) {
3308        match event {
3309            SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
3310                Err(InvalidSettingsError::LocalSettings { message, path }) => {
3311                    let message = format!("Failed to set local settings in {path:?}:\n{message}");
3312                    cx.emit(Event::Toast {
3313                        notification_id: format!("local-settings-{path:?}").into(),
3314                        message,
3315                    });
3316                }
3317                Ok(path) => cx.emit(Event::HideToast {
3318                    notification_id: format!("local-settings-{path:?}").into(),
3319                }),
3320                Err(_) => {}
3321            },
3322            SettingsObserverEvent::LocalTasksUpdated(result) => match result {
3323                Err(InvalidSettingsError::Tasks { message, path }) => {
3324                    let message = format!("Failed to set local tasks in {path:?}:\n{message}");
3325                    cx.emit(Event::Toast {
3326                        notification_id: format!("local-tasks-{path:?}").into(),
3327                        message,
3328                    });
3329                }
3330                Ok(path) => cx.emit(Event::HideToast {
3331                    notification_id: format!("local-tasks-{path:?}").into(),
3332                }),
3333                Err(_) => {}
3334            },
3335            SettingsObserverEvent::LocalDebugScenariosUpdated(result) => match result {
3336                Err(InvalidSettingsError::Debug { message, path }) => {
3337                    let message =
3338                        format!("Failed to set local debug scenarios in {path:?}:\n{message}");
3339                    cx.emit(Event::Toast {
3340                        notification_id: format!("local-debug-scenarios-{path:?}").into(),
3341                        message,
3342                    });
3343                }
3344                Ok(path) => cx.emit(Event::HideToast {
3345                    notification_id: format!("local-debug-scenarios-{path:?}").into(),
3346                }),
3347                Err(_) => {}
3348            },
3349        }
3350    }
3351
3352    fn on_worktree_store_event(
3353        &mut self,
3354        _: Entity<WorktreeStore>,
3355        event: &WorktreeStoreEvent,
3356        cx: &mut Context<Self>,
3357    ) {
3358        match event {
3359            WorktreeStoreEvent::WorktreeAdded(worktree) => {
3360                self.on_worktree_added(worktree, cx);
3361                cx.emit(Event::WorktreeAdded(worktree.read(cx).id()));
3362            }
3363            WorktreeStoreEvent::WorktreeRemoved(_, id) => {
3364                cx.emit(Event::WorktreeRemoved(*id));
3365            }
3366            WorktreeStoreEvent::WorktreeReleased(_, id) => {
3367                self.on_worktree_released(*id, cx);
3368            }
3369            WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
3370            WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
3371            WorktreeStoreEvent::WorktreeUpdatedEntries(worktree_id, changes) => {
3372                self.client()
3373                    .telemetry()
3374                    .report_discovered_project_type_events(*worktree_id, changes);
3375                cx.emit(Event::WorktreeUpdatedEntries(*worktree_id, changes.clone()))
3376            }
3377            WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, id) => {
3378                cx.emit(Event::DeletedEntry(*worktree_id, *id))
3379            }
3380            // Listen to the GitStore instead.
3381            WorktreeStoreEvent::WorktreeUpdatedGitRepositories(_, _) => {}
3382        }
3383    }
3384
3385    fn on_worktree_added(&mut self, worktree: &Entity<Worktree>, _: &mut Context<Self>) {
3386        let mut remotely_created_models = self.remotely_created_models.lock();
3387        if remotely_created_models.retain_count > 0 {
3388            remotely_created_models.worktrees.push(worktree.clone())
3389        }
3390    }
3391
3392    fn on_worktree_released(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
3393        if let Some(remote) = &self.remote_client {
3394            remote
3395                .read(cx)
3396                .proto_client()
3397                .send(proto::RemoveWorktree {
3398                    worktree_id: id_to_remove.to_proto(),
3399                })
3400                .log_err();
3401        }
3402    }
3403
3404    fn on_buffer_event(
3405        &mut self,
3406        buffer: Entity<Buffer>,
3407        event: &BufferEvent,
3408        cx: &mut Context<Self>,
3409    ) -> Option<()> {
3410        if matches!(event, BufferEvent::Edited | BufferEvent::Reloaded) {
3411            self.request_buffer_diff_recalculation(&buffer, cx);
3412        }
3413
3414        let buffer_id = buffer.read(cx).remote_id();
3415        match event {
3416            BufferEvent::ReloadNeeded => {
3417                if !self.is_via_collab() {
3418                    self.reload_buffers([buffer.clone()].into_iter().collect(), true, cx)
3419                        .detach_and_log_err(cx);
3420                }
3421            }
3422            BufferEvent::Operation {
3423                operation,
3424                is_local: true,
3425            } => {
3426                let operation = language::proto::serialize_operation(operation);
3427
3428                if let Some(remote) = &self.remote_client {
3429                    remote
3430                        .read(cx)
3431                        .proto_client()
3432                        .send(proto::UpdateBuffer {
3433                            project_id: 0,
3434                            buffer_id: buffer_id.to_proto(),
3435                            operations: vec![operation.clone()],
3436                        })
3437                        .ok();
3438                }
3439
3440                self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
3441                    buffer_id,
3442                    operation,
3443                })
3444                .ok();
3445            }
3446
3447            _ => {}
3448        }
3449
3450        None
3451    }
3452
3453    fn on_image_event(
3454        &mut self,
3455        image: Entity<ImageItem>,
3456        event: &ImageItemEvent,
3457        cx: &mut Context<Self>,
3458    ) -> Option<()> {
3459        // TODO: handle image events from remote
3460        if let ImageItemEvent::ReloadNeeded = event
3461            && !self.is_via_collab()
3462        {
3463            self.reload_images([image].into_iter().collect(), cx)
3464                .detach_and_log_err(cx);
3465        }
3466
3467        None
3468    }
3469
3470    fn request_buffer_diff_recalculation(
3471        &mut self,
3472        buffer: &Entity<Buffer>,
3473        cx: &mut Context<Self>,
3474    ) {
3475        self.buffers_needing_diff.insert(buffer.downgrade());
3476        let first_insertion = self.buffers_needing_diff.len() == 1;
3477        let settings = ProjectSettings::get_global(cx);
3478        let delay = settings.git.gutter_debounce;
3479
3480        if delay == 0 {
3481            if first_insertion {
3482                let this = cx.weak_entity();
3483                cx.defer(move |cx| {
3484                    if let Some(this) = this.upgrade() {
3485                        this.update(cx, |this, cx| {
3486                            this.recalculate_buffer_diffs(cx).detach();
3487                        });
3488                    }
3489                });
3490            }
3491            return;
3492        }
3493
3494        const MIN_DELAY: u64 = 50;
3495        let delay = delay.max(MIN_DELAY);
3496        let duration = Duration::from_millis(delay);
3497
3498        self.git_diff_debouncer
3499            .fire_new(duration, cx, move |this, cx| {
3500                this.recalculate_buffer_diffs(cx)
3501            });
3502    }
3503
3504    fn recalculate_buffer_diffs(&mut self, cx: &mut Context<Self>) -> Task<()> {
3505        cx.spawn(async move |this, cx| {
3506            loop {
3507                let task = this
3508                    .update(cx, |this, cx| {
3509                        let buffers = this
3510                            .buffers_needing_diff
3511                            .drain()
3512                            .filter_map(|buffer| buffer.upgrade())
3513                            .collect::<Vec<_>>();
3514                        if buffers.is_empty() {
3515                            None
3516                        } else {
3517                            Some(this.git_store.update(cx, |git_store, cx| {
3518                                git_store.recalculate_buffer_diffs(buffers, cx)
3519                            }))
3520                        }
3521                    })
3522                    .ok()
3523                    .flatten();
3524
3525                if let Some(task) = task {
3526                    task.await;
3527                } else {
3528                    break;
3529                }
3530            }
3531        })
3532    }
3533
3534    pub fn set_language_for_buffer(
3535        &mut self,
3536        buffer: &Entity<Buffer>,
3537        new_language: Arc<Language>,
3538        cx: &mut Context<Self>,
3539    ) {
3540        self.lsp_store.update(cx, |lsp_store, cx| {
3541            lsp_store.set_language_for_buffer(buffer, new_language, cx)
3542        })
3543    }
3544
3545    pub fn restart_language_servers_for_buffers(
3546        &mut self,
3547        buffers: Vec<Entity<Buffer>>,
3548        only_restart_servers: HashSet<LanguageServerSelector>,
3549        cx: &mut Context<Self>,
3550    ) {
3551        self.lsp_store.update(cx, |lsp_store, cx| {
3552            lsp_store.restart_language_servers_for_buffers(buffers, only_restart_servers, cx)
3553        })
3554    }
3555
3556    pub fn stop_language_servers_for_buffers(
3557        &mut self,
3558        buffers: Vec<Entity<Buffer>>,
3559        also_restart_servers: HashSet<LanguageServerSelector>,
3560        cx: &mut Context<Self>,
3561    ) {
3562        self.lsp_store
3563            .update(cx, |lsp_store, cx| {
3564                lsp_store.stop_language_servers_for_buffers(buffers, also_restart_servers, cx)
3565            })
3566            .detach_and_log_err(cx);
3567    }
3568
3569    pub fn cancel_language_server_work_for_buffers(
3570        &mut self,
3571        buffers: impl IntoIterator<Item = Entity<Buffer>>,
3572        cx: &mut Context<Self>,
3573    ) {
3574        self.lsp_store.update(cx, |lsp_store, cx| {
3575            lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
3576        })
3577    }
3578
3579    pub fn cancel_language_server_work(
3580        &mut self,
3581        server_id: LanguageServerId,
3582        token_to_cancel: Option<ProgressToken>,
3583        cx: &mut Context<Self>,
3584    ) {
3585        self.lsp_store.update(cx, |lsp_store, cx| {
3586            lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
3587        })
3588    }
3589
3590    fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
3591        self.buffer_ordered_messages_tx
3592            .unbounded_send(message)
3593            .map_err(|e| anyhow!(e))
3594    }
3595
3596    pub fn available_toolchains(
3597        &self,
3598        path: ProjectPath,
3599        language_name: LanguageName,
3600        cx: &App,
3601    ) -> Task<Option<Toolchains>> {
3602        if let Some(toolchain_store) = self.toolchain_store.as_ref().map(Entity::downgrade) {
3603            cx.spawn(async move |cx| {
3604                toolchain_store
3605                    .update(cx, |this, cx| this.list_toolchains(path, language_name, cx))
3606                    .ok()?
3607                    .await
3608            })
3609        } else {
3610            Task::ready(None)
3611        }
3612    }
3613
3614    pub async fn toolchain_metadata(
3615        languages: Arc<LanguageRegistry>,
3616        language_name: LanguageName,
3617    ) -> Option<ToolchainMetadata> {
3618        languages
3619            .language_for_name(language_name.as_ref())
3620            .await
3621            .ok()?
3622            .toolchain_lister()
3623            .map(|lister| lister.meta())
3624    }
3625
3626    pub fn add_toolchain(
3627        &self,
3628        toolchain: Toolchain,
3629        scope: ToolchainScope,
3630        cx: &mut Context<Self>,
3631    ) {
3632        maybe!({
3633            self.toolchain_store.as_ref()?.update(cx, |this, cx| {
3634                this.add_toolchain(toolchain, scope, cx);
3635            });
3636            Some(())
3637        });
3638    }
3639
3640    pub fn remove_toolchain(
3641        &self,
3642        toolchain: Toolchain,
3643        scope: ToolchainScope,
3644        cx: &mut Context<Self>,
3645    ) {
3646        maybe!({
3647            self.toolchain_store.as_ref()?.update(cx, |this, cx| {
3648                this.remove_toolchain(toolchain, scope, cx);
3649            });
3650            Some(())
3651        });
3652    }
3653
3654    pub fn user_toolchains(
3655        &self,
3656        cx: &App,
3657    ) -> Option<BTreeMap<ToolchainScope, IndexSet<Toolchain>>> {
3658        Some(self.toolchain_store.as_ref()?.read(cx).user_toolchains())
3659    }
3660
3661    pub fn resolve_toolchain(
3662        &self,
3663        path: PathBuf,
3664        language_name: LanguageName,
3665        cx: &App,
3666    ) -> Task<Result<Toolchain>> {
3667        if let Some(toolchain_store) = self.toolchain_store.as_ref().map(Entity::downgrade) {
3668            cx.spawn(async move |cx| {
3669                toolchain_store
3670                    .update(cx, |this, cx| {
3671                        this.resolve_toolchain(path, language_name, cx)
3672                    })?
3673                    .await
3674            })
3675        } else {
3676            Task::ready(Err(anyhow!("This project does not support toolchains")))
3677        }
3678    }
3679
3680    pub fn toolchain_store(&self) -> Option<Entity<ToolchainStore>> {
3681        self.toolchain_store.clone()
3682    }
3683    pub fn activate_toolchain(
3684        &self,
3685        path: ProjectPath,
3686        toolchain: Toolchain,
3687        cx: &mut App,
3688    ) -> Task<Option<()>> {
3689        let Some(toolchain_store) = self.toolchain_store.clone() else {
3690            return Task::ready(None);
3691        };
3692        toolchain_store.update(cx, |this, cx| this.activate_toolchain(path, toolchain, cx))
3693    }
3694    pub fn active_toolchain(
3695        &self,
3696        path: ProjectPath,
3697        language_name: LanguageName,
3698        cx: &App,
3699    ) -> Task<Option<Toolchain>> {
3700        let Some(toolchain_store) = self.toolchain_store.clone() else {
3701            return Task::ready(None);
3702        };
3703        toolchain_store
3704            .read(cx)
3705            .active_toolchain(path, language_name, cx)
3706    }
3707    pub fn language_server_statuses<'a>(
3708        &'a self,
3709        cx: &'a App,
3710    ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
3711        self.lsp_store.read(cx).language_server_statuses()
3712    }
3713
3714    pub fn last_formatting_failure<'a>(&self, cx: &'a App) -> Option<&'a str> {
3715        self.lsp_store.read(cx).last_formatting_failure()
3716    }
3717
3718    pub fn reset_last_formatting_failure(&self, cx: &mut App) {
3719        self.lsp_store
3720            .update(cx, |store, _| store.reset_last_formatting_failure());
3721    }
3722
3723    pub fn reload_buffers(
3724        &self,
3725        buffers: HashSet<Entity<Buffer>>,
3726        push_to_history: bool,
3727        cx: &mut Context<Self>,
3728    ) -> Task<Result<ProjectTransaction>> {
3729        self.buffer_store.update(cx, |buffer_store, cx| {
3730            buffer_store.reload_buffers(buffers, push_to_history, cx)
3731        })
3732    }
3733
3734    pub fn reload_images(
3735        &self,
3736        images: HashSet<Entity<ImageItem>>,
3737        cx: &mut Context<Self>,
3738    ) -> Task<Result<()>> {
3739        self.image_store
3740            .update(cx, |image_store, cx| image_store.reload_images(images, cx))
3741    }
3742
3743    pub fn format(
3744        &mut self,
3745        buffers: HashSet<Entity<Buffer>>,
3746        target: LspFormatTarget,
3747        push_to_history: bool,
3748        trigger: lsp_store::FormatTrigger,
3749        cx: &mut Context<Project>,
3750    ) -> Task<anyhow::Result<ProjectTransaction>> {
3751        self.lsp_store.update(cx, |lsp_store, cx| {
3752            lsp_store.format(buffers, target, push_to_history, trigger, cx)
3753        })
3754    }
3755
3756    pub fn definitions<T: ToPointUtf16>(
3757        &mut self,
3758        buffer: &Entity<Buffer>,
3759        position: T,
3760        cx: &mut Context<Self>,
3761    ) -> Task<Result<Option<Vec<LocationLink>>>> {
3762        let position = position.to_point_utf16(buffer.read(cx));
3763        let guard = self.retain_remotely_created_models(cx);
3764        let task = self.lsp_store.update(cx, |lsp_store, cx| {
3765            lsp_store.definitions(buffer, position, cx)
3766        });
3767        cx.background_spawn(async move {
3768            let result = task.await;
3769            drop(guard);
3770            result
3771        })
3772    }
3773
3774    pub fn declarations<T: ToPointUtf16>(
3775        &mut self,
3776        buffer: &Entity<Buffer>,
3777        position: T,
3778        cx: &mut Context<Self>,
3779    ) -> Task<Result<Option<Vec<LocationLink>>>> {
3780        let position = position.to_point_utf16(buffer.read(cx));
3781        let guard = self.retain_remotely_created_models(cx);
3782        let task = self.lsp_store.update(cx, |lsp_store, cx| {
3783            lsp_store.declarations(buffer, position, cx)
3784        });
3785        cx.background_spawn(async move {
3786            let result = task.await;
3787            drop(guard);
3788            result
3789        })
3790    }
3791
3792    pub fn type_definitions<T: ToPointUtf16>(
3793        &mut self,
3794        buffer: &Entity<Buffer>,
3795        position: T,
3796        cx: &mut Context<Self>,
3797    ) -> Task<Result<Option<Vec<LocationLink>>>> {
3798        let position = position.to_point_utf16(buffer.read(cx));
3799        let guard = self.retain_remotely_created_models(cx);
3800        let task = self.lsp_store.update(cx, |lsp_store, cx| {
3801            lsp_store.type_definitions(buffer, position, cx)
3802        });
3803        cx.background_spawn(async move {
3804            let result = task.await;
3805            drop(guard);
3806            result
3807        })
3808    }
3809
3810    pub fn implementations<T: ToPointUtf16>(
3811        &mut self,
3812        buffer: &Entity<Buffer>,
3813        position: T,
3814        cx: &mut Context<Self>,
3815    ) -> Task<Result<Option<Vec<LocationLink>>>> {
3816        let position = position.to_point_utf16(buffer.read(cx));
3817        let guard = self.retain_remotely_created_models(cx);
3818        let task = self.lsp_store.update(cx, |lsp_store, cx| {
3819            lsp_store.implementations(buffer, position, cx)
3820        });
3821        cx.background_spawn(async move {
3822            let result = task.await;
3823            drop(guard);
3824            result
3825        })
3826    }
3827
3828    pub fn references<T: ToPointUtf16>(
3829        &mut self,
3830        buffer: &Entity<Buffer>,
3831        position: T,
3832        cx: &mut Context<Self>,
3833    ) -> Task<Result<Option<Vec<Location>>>> {
3834        let position = position.to_point_utf16(buffer.read(cx));
3835        let guard = self.retain_remotely_created_models(cx);
3836        let task = self.lsp_store.update(cx, |lsp_store, cx| {
3837            lsp_store.references(buffer, position, cx)
3838        });
3839        cx.background_spawn(async move {
3840            let result = task.await;
3841            drop(guard);
3842            result
3843        })
3844    }
3845
3846    pub fn document_highlights<T: ToPointUtf16>(
3847        &mut self,
3848        buffer: &Entity<Buffer>,
3849        position: T,
3850        cx: &mut Context<Self>,
3851    ) -> Task<Result<Vec<DocumentHighlight>>> {
3852        let position = position.to_point_utf16(buffer.read(cx));
3853        self.request_lsp(
3854            buffer.clone(),
3855            LanguageServerToQuery::FirstCapable,
3856            GetDocumentHighlights { position },
3857            cx,
3858        )
3859    }
3860
3861    pub fn document_symbols(
3862        &mut self,
3863        buffer: &Entity<Buffer>,
3864        cx: &mut Context<Self>,
3865    ) -> Task<Result<Vec<DocumentSymbol>>> {
3866        self.request_lsp(
3867            buffer.clone(),
3868            LanguageServerToQuery::FirstCapable,
3869            GetDocumentSymbols,
3870            cx,
3871        )
3872    }
3873
3874    pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
3875        self.lsp_store
3876            .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
3877    }
3878
3879    pub fn open_buffer_for_symbol(
3880        &mut self,
3881        symbol: &Symbol,
3882        cx: &mut Context<Self>,
3883    ) -> Task<Result<Entity<Buffer>>> {
3884        self.lsp_store.update(cx, |lsp_store, cx| {
3885            lsp_store.open_buffer_for_symbol(symbol, cx)
3886        })
3887    }
3888
3889    pub fn open_server_settings(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
3890        let guard = self.retain_remotely_created_models(cx);
3891        let Some(remote) = self.remote_client.as_ref() else {
3892            return Task::ready(Err(anyhow!("not an ssh project")));
3893        };
3894
3895        let proto_client = remote.read(cx).proto_client();
3896
3897        cx.spawn(async move |project, cx| {
3898            let buffer = proto_client
3899                .request(proto::OpenServerSettings {
3900                    project_id: REMOTE_SERVER_PROJECT_ID,
3901                })
3902                .await?;
3903
3904            let buffer = project
3905                .update(cx, |project, cx| {
3906                    project.buffer_store.update(cx, |buffer_store, cx| {
3907                        anyhow::Ok(
3908                            buffer_store
3909                                .wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx),
3910                        )
3911                    })
3912                })??
3913                .await;
3914
3915            drop(guard);
3916            buffer
3917        })
3918    }
3919
3920    pub fn open_local_buffer_via_lsp(
3921        &mut self,
3922        abs_path: lsp::Uri,
3923        language_server_id: LanguageServerId,
3924        cx: &mut Context<Self>,
3925    ) -> Task<Result<Entity<Buffer>>> {
3926        self.lsp_store.update(cx, |lsp_store, cx| {
3927            lsp_store.open_local_buffer_via_lsp(abs_path, language_server_id, cx)
3928        })
3929    }
3930
3931    pub fn hover<T: ToPointUtf16>(
3932        &self,
3933        buffer: &Entity<Buffer>,
3934        position: T,
3935        cx: &mut Context<Self>,
3936    ) -> Task<Option<Vec<Hover>>> {
3937        let position = position.to_point_utf16(buffer.read(cx));
3938        self.lsp_store
3939            .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
3940    }
3941
3942    pub fn linked_edits(
3943        &self,
3944        buffer: &Entity<Buffer>,
3945        position: Anchor,
3946        cx: &mut Context<Self>,
3947    ) -> Task<Result<Vec<Range<Anchor>>>> {
3948        self.lsp_store.update(cx, |lsp_store, cx| {
3949            lsp_store.linked_edits(buffer, position, cx)
3950        })
3951    }
3952
3953    pub fn completions<T: ToOffset + ToPointUtf16>(
3954        &self,
3955        buffer: &Entity<Buffer>,
3956        position: T,
3957        context: CompletionContext,
3958        cx: &mut Context<Self>,
3959    ) -> Task<Result<Vec<CompletionResponse>>> {
3960        let position = position.to_point_utf16(buffer.read(cx));
3961        self.lsp_store.update(cx, |lsp_store, cx| {
3962            lsp_store.completions(buffer, position, context, cx)
3963        })
3964    }
3965
3966    pub fn code_actions<T: Clone + ToOffset>(
3967        &mut self,
3968        buffer_handle: &Entity<Buffer>,
3969        range: Range<T>,
3970        kinds: Option<Vec<CodeActionKind>>,
3971        cx: &mut Context<Self>,
3972    ) -> Task<Result<Option<Vec<CodeAction>>>> {
3973        let buffer = buffer_handle.read(cx);
3974        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3975        self.lsp_store.update(cx, |lsp_store, cx| {
3976            lsp_store.code_actions(buffer_handle, range, kinds, cx)
3977        })
3978    }
3979
3980    pub fn code_lens_actions<T: Clone + ToOffset>(
3981        &mut self,
3982        buffer: &Entity<Buffer>,
3983        range: Range<T>,
3984        cx: &mut Context<Self>,
3985    ) -> Task<Result<Option<Vec<CodeAction>>>> {
3986        let snapshot = buffer.read(cx).snapshot();
3987        let range = range.to_point(&snapshot);
3988        let range_start = snapshot.anchor_before(range.start);
3989        let range_end = if range.start == range.end {
3990            range_start
3991        } else {
3992            snapshot.anchor_after(range.end)
3993        };
3994        let range = range_start..range_end;
3995        let code_lens_actions = self
3996            .lsp_store
3997            .update(cx, |lsp_store, cx| lsp_store.code_lens_actions(buffer, cx));
3998
3999        cx.background_spawn(async move {
4000            let mut code_lens_actions = code_lens_actions
4001                .await
4002                .map_err(|e| anyhow!("code lens fetch failed: {e:#}"))?;
4003            if let Some(code_lens_actions) = &mut code_lens_actions {
4004                code_lens_actions.retain(|code_lens_action| {
4005                    range
4006                        .start
4007                        .cmp(&code_lens_action.range.start, &snapshot)
4008                        .is_ge()
4009                        && range
4010                            .end
4011                            .cmp(&code_lens_action.range.end, &snapshot)
4012                            .is_le()
4013                });
4014            }
4015            Ok(code_lens_actions)
4016        })
4017    }
4018
4019    pub fn apply_code_action(
4020        &self,
4021        buffer_handle: Entity<Buffer>,
4022        action: CodeAction,
4023        push_to_history: bool,
4024        cx: &mut Context<Self>,
4025    ) -> Task<Result<ProjectTransaction>> {
4026        self.lsp_store.update(cx, |lsp_store, cx| {
4027            lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
4028        })
4029    }
4030
4031    pub fn apply_code_action_kind(
4032        &self,
4033        buffers: HashSet<Entity<Buffer>>,
4034        kind: CodeActionKind,
4035        push_to_history: bool,
4036        cx: &mut Context<Self>,
4037    ) -> Task<Result<ProjectTransaction>> {
4038        self.lsp_store.update(cx, |lsp_store, cx| {
4039            lsp_store.apply_code_action_kind(buffers, kind, push_to_history, cx)
4040        })
4041    }
4042
4043    pub fn prepare_rename<T: ToPointUtf16>(
4044        &mut self,
4045        buffer: Entity<Buffer>,
4046        position: T,
4047        cx: &mut Context<Self>,
4048    ) -> Task<Result<PrepareRenameResponse>> {
4049        let position = position.to_point_utf16(buffer.read(cx));
4050        self.request_lsp(
4051            buffer,
4052            LanguageServerToQuery::FirstCapable,
4053            PrepareRename { position },
4054            cx,
4055        )
4056    }
4057
4058    pub fn perform_rename<T: ToPointUtf16>(
4059        &mut self,
4060        buffer: Entity<Buffer>,
4061        position: T,
4062        new_name: String,
4063        cx: &mut Context<Self>,
4064    ) -> Task<Result<ProjectTransaction>> {
4065        let push_to_history = true;
4066        let position = position.to_point_utf16(buffer.read(cx));
4067        self.request_lsp(
4068            buffer,
4069            LanguageServerToQuery::FirstCapable,
4070            PerformRename {
4071                position,
4072                new_name,
4073                push_to_history,
4074            },
4075            cx,
4076        )
4077    }
4078
4079    pub fn on_type_format<T: ToPointUtf16>(
4080        &mut self,
4081        buffer: Entity<Buffer>,
4082        position: T,
4083        trigger: String,
4084        push_to_history: bool,
4085        cx: &mut Context<Self>,
4086    ) -> Task<Result<Option<Transaction>>> {
4087        self.lsp_store.update(cx, |lsp_store, cx| {
4088            lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
4089        })
4090    }
4091
4092    pub fn inline_values(
4093        &mut self,
4094        session: Entity<Session>,
4095        active_stack_frame: ActiveStackFrame,
4096        buffer_handle: Entity<Buffer>,
4097        range: Range<text::Anchor>,
4098        cx: &mut Context<Self>,
4099    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
4100        let snapshot = buffer_handle.read(cx).snapshot();
4101
4102        let captures =
4103            snapshot.debug_variables_query(Anchor::min_for_buffer(snapshot.remote_id())..range.end);
4104
4105        let row = snapshot
4106            .summary_for_anchor::<text::PointUtf16>(&range.end)
4107            .row as usize;
4108
4109        let inline_value_locations = provide_inline_values(captures, &snapshot, row);
4110
4111        let stack_frame_id = active_stack_frame.stack_frame_id;
4112        cx.spawn(async move |this, cx| {
4113            this.update(cx, |project, cx| {
4114                project.dap_store().update(cx, |dap_store, cx| {
4115                    dap_store.resolve_inline_value_locations(
4116                        session,
4117                        stack_frame_id,
4118                        buffer_handle,
4119                        inline_value_locations,
4120                        cx,
4121                    )
4122                })
4123            })?
4124            .await
4125        })
4126    }
4127
4128    fn search_impl(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> SearchResultsHandle {
4129        let client: Option<(AnyProtoClient, _)> = if let Some(ssh_client) = &self.remote_client {
4130            Some((ssh_client.read(cx).proto_client(), 0))
4131        } else if let Some(remote_id) = self.remote_id() {
4132            self.is_local()
4133                .not()
4134                .then(|| (self.collab_client.clone().into(), remote_id))
4135        } else {
4136            None
4137        };
4138        let searcher = if query.is_opened_only() {
4139            project_search::Search::open_buffers_only(
4140                self.buffer_store.clone(),
4141                self.worktree_store.clone(),
4142                project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4143            )
4144        } else {
4145            match client {
4146                Some((client, remote_id)) => project_search::Search::remote(
4147                    self.buffer_store.clone(),
4148                    self.worktree_store.clone(),
4149                    project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4150                    (client, remote_id, self.remotely_created_models.clone()),
4151                ),
4152                None => project_search::Search::local(
4153                    self.fs.clone(),
4154                    self.buffer_store.clone(),
4155                    self.worktree_store.clone(),
4156                    project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4157                    cx,
4158                ),
4159            }
4160        };
4161        searcher.into_handle(query, cx)
4162    }
4163
4164    pub fn search(
4165        &mut self,
4166        query: SearchQuery,
4167        cx: &mut Context<Self>,
4168    ) -> SearchResults<SearchResult> {
4169        self.search_impl(query, cx).results(cx)
4170    }
4171
4172    pub fn request_lsp<R: LspCommand>(
4173        &mut self,
4174        buffer_handle: Entity<Buffer>,
4175        server: LanguageServerToQuery,
4176        request: R,
4177        cx: &mut Context<Self>,
4178    ) -> Task<Result<R::Response>>
4179    where
4180        <R::LspRequest as lsp::request::Request>::Result: Send,
4181        <R::LspRequest as lsp::request::Request>::Params: Send,
4182    {
4183        let guard = self.retain_remotely_created_models(cx);
4184        let task = self.lsp_store.update(cx, |lsp_store, cx| {
4185            lsp_store.request_lsp(buffer_handle, server, request, cx)
4186        });
4187        cx.background_spawn(async move {
4188            let result = task.await;
4189            drop(guard);
4190            result
4191        })
4192    }
4193
4194    /// Move a worktree to a new position in the worktree order.
4195    ///
4196    /// The worktree will moved to the opposite side of the destination worktree.
4197    ///
4198    /// # Example
4199    ///
4200    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
4201    /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
4202    ///
4203    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
4204    /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
4205    ///
4206    /// # Errors
4207    ///
4208    /// An error will be returned if the worktree or destination worktree are not found.
4209    pub fn move_worktree(
4210        &mut self,
4211        source: WorktreeId,
4212        destination: WorktreeId,
4213        cx: &mut Context<Self>,
4214    ) -> Result<()> {
4215        self.worktree_store.update(cx, |worktree_store, cx| {
4216            worktree_store.move_worktree(source, destination, cx)
4217        })
4218    }
4219
4220    pub fn find_or_create_worktree(
4221        &mut self,
4222        abs_path: impl AsRef<Path>,
4223        visible: bool,
4224        cx: &mut Context<Self>,
4225    ) -> Task<Result<(Entity<Worktree>, Arc<RelPath>)>> {
4226        self.worktree_store.update(cx, |worktree_store, cx| {
4227            worktree_store.find_or_create_worktree(abs_path, visible, cx)
4228        })
4229    }
4230
4231    pub fn find_worktree(
4232        &self,
4233        abs_path: &Path,
4234        cx: &App,
4235    ) -> Option<(Entity<Worktree>, Arc<RelPath>)> {
4236        self.worktree_store.read(cx).find_worktree(abs_path, cx)
4237    }
4238
4239    pub fn is_shared(&self) -> bool {
4240        match &self.client_state {
4241            ProjectClientState::Shared { .. } => true,
4242            ProjectClientState::Local => false,
4243            ProjectClientState::Remote { .. } => true,
4244        }
4245    }
4246
4247    /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
4248    pub fn resolve_path_in_buffer(
4249        &self,
4250        path: &str,
4251        buffer: &Entity<Buffer>,
4252        cx: &mut Context<Self>,
4253    ) -> Task<Option<ResolvedPath>> {
4254        if util::paths::is_absolute(path, self.path_style(cx)) || path.starts_with("~") {
4255            self.resolve_abs_path(path, cx)
4256        } else {
4257            self.resolve_path_in_worktrees(path, buffer, cx)
4258        }
4259    }
4260
4261    pub fn resolve_abs_file_path(
4262        &self,
4263        path: &str,
4264        cx: &mut Context<Self>,
4265    ) -> Task<Option<ResolvedPath>> {
4266        let resolve_task = self.resolve_abs_path(path, cx);
4267        cx.background_spawn(async move {
4268            let resolved_path = resolve_task.await;
4269            resolved_path.filter(|path| path.is_file())
4270        })
4271    }
4272
4273    pub fn resolve_abs_path(&self, path: &str, cx: &App) -> Task<Option<ResolvedPath>> {
4274        if self.is_local() {
4275            let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
4276            let fs = self.fs.clone();
4277            cx.background_spawn(async move {
4278                let metadata = fs.metadata(&expanded).await.ok().flatten();
4279
4280                metadata.map(|metadata| ResolvedPath::AbsPath {
4281                    path: expanded.to_string_lossy().into_owned(),
4282                    is_dir: metadata.is_dir,
4283                })
4284            })
4285        } else if let Some(ssh_client) = self.remote_client.as_ref() {
4286            let request = ssh_client
4287                .read(cx)
4288                .proto_client()
4289                .request(proto::GetPathMetadata {
4290                    project_id: REMOTE_SERVER_PROJECT_ID,
4291                    path: path.into(),
4292                });
4293            cx.background_spawn(async move {
4294                let response = request.await.log_err()?;
4295                if response.exists {
4296                    Some(ResolvedPath::AbsPath {
4297                        path: response.path,
4298                        is_dir: response.is_dir,
4299                    })
4300                } else {
4301                    None
4302                }
4303            })
4304        } else {
4305            Task::ready(None)
4306        }
4307    }
4308
4309    fn resolve_path_in_worktrees(
4310        &self,
4311        path: &str,
4312        buffer: &Entity<Buffer>,
4313        cx: &mut Context<Self>,
4314    ) -> Task<Option<ResolvedPath>> {
4315        let mut candidates = vec![];
4316        let path_style = self.path_style(cx);
4317        if let Ok(path) = RelPath::new(path.as_ref(), path_style) {
4318            candidates.push(path.into_arc());
4319        }
4320
4321        if let Some(file) = buffer.read(cx).file()
4322            && let Some(dir) = file.path().parent()
4323        {
4324            if let Some(joined) = path_style.join(&*dir.display(path_style), path)
4325                && let Some(joined) = RelPath::new(joined.as_ref(), path_style).ok()
4326            {
4327                candidates.push(joined.into_arc());
4328            }
4329        }
4330
4331        let buffer_worktree_id = buffer.read(cx).file().map(|file| file.worktree_id(cx));
4332        let worktrees_with_ids: Vec<_> = self
4333            .worktrees(cx)
4334            .map(|worktree| {
4335                let id = worktree.read(cx).id();
4336                (worktree, id)
4337            })
4338            .collect();
4339
4340        cx.spawn(async move |_, cx| {
4341            if let Some(buffer_worktree_id) = buffer_worktree_id
4342                && let Some((worktree, _)) = worktrees_with_ids
4343                    .iter()
4344                    .find(|(_, id)| *id == buffer_worktree_id)
4345            {
4346                for candidate in candidates.iter() {
4347                    if let Some(path) = Self::resolve_path_in_worktree(worktree, candidate, cx) {
4348                        return Some(path);
4349                    }
4350                }
4351            }
4352            for (worktree, id) in worktrees_with_ids {
4353                if Some(id) == buffer_worktree_id {
4354                    continue;
4355                }
4356                for candidate in candidates.iter() {
4357                    if let Some(path) = Self::resolve_path_in_worktree(&worktree, candidate, cx) {
4358                        return Some(path);
4359                    }
4360                }
4361            }
4362            None
4363        })
4364    }
4365
4366    fn resolve_path_in_worktree(
4367        worktree: &Entity<Worktree>,
4368        path: &RelPath,
4369        cx: &mut AsyncApp,
4370    ) -> Option<ResolvedPath> {
4371        worktree.read_with(cx, |worktree, _| {
4372            worktree.entry_for_path(path).map(|entry| {
4373                let project_path = ProjectPath {
4374                    worktree_id: worktree.id(),
4375                    path: entry.path.clone(),
4376                };
4377                ResolvedPath::ProjectPath {
4378                    project_path,
4379                    is_dir: entry.is_dir(),
4380                }
4381            })
4382        })
4383    }
4384
4385    pub fn list_directory(
4386        &self,
4387        query: String,
4388        cx: &mut Context<Self>,
4389    ) -> Task<Result<Vec<DirectoryItem>>> {
4390        if self.is_local() {
4391            DirectoryLister::Local(cx.entity(), self.fs.clone()).list_directory(query, cx)
4392        } else if let Some(session) = self.remote_client.as_ref() {
4393            let request = proto::ListRemoteDirectory {
4394                dev_server_id: REMOTE_SERVER_PROJECT_ID,
4395                path: query,
4396                config: Some(proto::ListRemoteDirectoryConfig { is_dir: true }),
4397            };
4398
4399            let response = session.read(cx).proto_client().request(request);
4400            cx.background_spawn(async move {
4401                let proto::ListRemoteDirectoryResponse {
4402                    entries,
4403                    entry_info,
4404                } = response.await?;
4405                Ok(entries
4406                    .into_iter()
4407                    .zip(entry_info)
4408                    .map(|(entry, info)| DirectoryItem {
4409                        path: PathBuf::from(entry),
4410                        is_dir: info.is_dir,
4411                    })
4412                    .collect())
4413            })
4414        } else {
4415            Task::ready(Err(anyhow!("cannot list directory in remote project")))
4416        }
4417    }
4418
4419    pub fn create_worktree(
4420        &mut self,
4421        abs_path: impl AsRef<Path>,
4422        visible: bool,
4423        cx: &mut Context<Self>,
4424    ) -> Task<Result<Entity<Worktree>>> {
4425        self.worktree_store.update(cx, |worktree_store, cx| {
4426            worktree_store.create_worktree(abs_path, visible, cx)
4427        })
4428    }
4429
4430    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
4431        self.worktree_store.update(cx, |worktree_store, cx| {
4432            worktree_store.remove_worktree(id_to_remove, cx);
4433        });
4434    }
4435
4436    fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
4437        self.worktree_store.update(cx, |worktree_store, cx| {
4438            worktree_store.add(worktree, cx);
4439        });
4440    }
4441
4442    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
4443        let new_active_entry = entry.and_then(|project_path| {
4444            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4445            let entry = worktree.read(cx).entry_for_path(&project_path.path)?;
4446            Some(entry.id)
4447        });
4448        if new_active_entry != self.active_entry {
4449            self.active_entry = new_active_entry;
4450            self.lsp_store.update(cx, |lsp_store, _| {
4451                lsp_store.set_active_entry(new_active_entry);
4452            });
4453            cx.emit(Event::ActiveEntryChanged(new_active_entry));
4454        }
4455    }
4456
4457    pub fn language_servers_running_disk_based_diagnostics<'a>(
4458        &'a self,
4459        cx: &'a App,
4460    ) -> impl Iterator<Item = LanguageServerId> + 'a {
4461        self.lsp_store
4462            .read(cx)
4463            .language_servers_running_disk_based_diagnostics()
4464    }
4465
4466    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
4467        self.lsp_store
4468            .read(cx)
4469            .diagnostic_summary(include_ignored, cx)
4470    }
4471
4472    /// Returns a summary of the diagnostics for the provided project path only.
4473    pub fn diagnostic_summary_for_path(&self, path: &ProjectPath, cx: &App) -> DiagnosticSummary {
4474        self.lsp_store
4475            .read(cx)
4476            .diagnostic_summary_for_path(path, cx)
4477    }
4478
4479    pub fn diagnostic_summaries<'a>(
4480        &'a self,
4481        include_ignored: bool,
4482        cx: &'a App,
4483    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4484        self.lsp_store
4485            .read(cx)
4486            .diagnostic_summaries(include_ignored, cx)
4487    }
4488
4489    pub fn active_entry(&self) -> Option<ProjectEntryId> {
4490        self.active_entry
4491    }
4492
4493    pub fn entry_for_path<'a>(&'a self, path: &ProjectPath, cx: &'a App) -> Option<&'a Entry> {
4494        self.worktree_store.read(cx).entry_for_path(path, cx)
4495    }
4496
4497    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
4498        let worktree = self.worktree_for_entry(entry_id, cx)?;
4499        let worktree = worktree.read(cx);
4500        let worktree_id = worktree.id();
4501        let path = worktree.entry_for_id(entry_id)?.path.clone();
4502        Some(ProjectPath { worktree_id, path })
4503    }
4504
4505    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4506        Some(
4507            self.worktree_for_id(project_path.worktree_id, cx)?
4508                .read(cx)
4509                .absolutize(&project_path.path),
4510        )
4511    }
4512
4513    /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
4514    /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
4515    /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
4516    /// the first visible worktree that has an entry for that relative path.
4517    ///
4518    /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
4519    /// root name from paths.
4520    ///
4521    /// # Arguments
4522    ///
4523    /// * `path` - An absolute path, or a full path that starts with a worktree root name, or a
4524    ///   relative path within a visible worktree.
4525    /// * `cx` - A reference to the `AppContext`.
4526    ///
4527    /// # Returns
4528    ///
4529    /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
4530    pub fn find_project_path(&self, path: impl AsRef<Path>, cx: &App) -> Option<ProjectPath> {
4531        let path_style = self.path_style(cx);
4532        let path = path.as_ref();
4533        let worktree_store = self.worktree_store.read(cx);
4534
4535        if is_absolute(&path.to_string_lossy(), path_style) {
4536            for worktree in worktree_store.visible_worktrees(cx) {
4537                let worktree_abs_path = worktree.read(cx).abs_path();
4538
4539                if let Ok(relative_path) = path.strip_prefix(worktree_abs_path)
4540                    && let Ok(path) = RelPath::new(relative_path, path_style)
4541                {
4542                    return Some(ProjectPath {
4543                        worktree_id: worktree.read(cx).id(),
4544                        path: path.into_arc(),
4545                    });
4546                }
4547            }
4548        } else {
4549            for worktree in worktree_store.visible_worktrees(cx) {
4550                let worktree = worktree.read(cx);
4551                if let Ok(rel_path) = RelPath::new(path, path_style) {
4552                    if let Some(entry) = worktree.entry_for_path(&rel_path) {
4553                        return Some(ProjectPath {
4554                            worktree_id: worktree.id(),
4555                            path: entry.path.clone(),
4556                        });
4557                    }
4558                }
4559            }
4560
4561            for worktree in worktree_store.visible_worktrees(cx) {
4562                let worktree_root_name = worktree.read(cx).root_name();
4563                if let Ok(relative_path) = path.strip_prefix(worktree_root_name.as_std_path())
4564                    && let Ok(path) = RelPath::new(relative_path, path_style)
4565                {
4566                    return Some(ProjectPath {
4567                        worktree_id: worktree.read(cx).id(),
4568                        path: path.into_arc(),
4569                    });
4570                }
4571            }
4572        }
4573
4574        None
4575    }
4576
4577    /// If there's only one visible worktree, returns the given worktree-relative path with no prefix.
4578    ///
4579    /// Otherwise, returns the full path for the project path (obtained by prefixing the worktree-relative path with the name of the worktree).
4580    pub fn short_full_path_for_project_path(
4581        &self,
4582        project_path: &ProjectPath,
4583        cx: &App,
4584    ) -> Option<String> {
4585        let path_style = self.path_style(cx);
4586        if self.visible_worktrees(cx).take(2).count() < 2 {
4587            return Some(project_path.path.display(path_style).to_string());
4588        }
4589        self.worktree_for_id(project_path.worktree_id, cx)
4590            .map(|worktree| {
4591                let worktree_name = worktree.read(cx).root_name();
4592                worktree_name
4593                    .join(&project_path.path)
4594                    .display(path_style)
4595                    .to_string()
4596            })
4597    }
4598
4599    pub fn project_path_for_absolute_path(&self, abs_path: &Path, cx: &App) -> Option<ProjectPath> {
4600        self.worktree_store
4601            .read(cx)
4602            .project_path_for_absolute_path(abs_path, cx)
4603    }
4604
4605    pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4606        Some(
4607            self.worktree_for_id(project_path.worktree_id, cx)?
4608                .read(cx)
4609                .abs_path()
4610                .to_path_buf(),
4611        )
4612    }
4613
4614    pub fn blame_buffer(
4615        &self,
4616        buffer: &Entity<Buffer>,
4617        version: Option<clock::Global>,
4618        cx: &mut App,
4619    ) -> Task<Result<Option<Blame>>> {
4620        self.git_store.update(cx, |git_store, cx| {
4621            git_store.blame_buffer(buffer, version, cx)
4622        })
4623    }
4624
4625    pub fn get_permalink_to_line(
4626        &self,
4627        buffer: &Entity<Buffer>,
4628        selection: Range<u32>,
4629        cx: &mut App,
4630    ) -> Task<Result<url::Url>> {
4631        self.git_store.update(cx, |git_store, cx| {
4632            git_store.get_permalink_to_line(buffer, selection, cx)
4633        })
4634    }
4635
4636    // RPC message handlers
4637
4638    async fn handle_unshare_project(
4639        this: Entity<Self>,
4640        _: TypedEnvelope<proto::UnshareProject>,
4641        mut cx: AsyncApp,
4642    ) -> Result<()> {
4643        this.update(&mut cx, |this, cx| {
4644            if this.is_local() || this.is_via_remote_server() {
4645                this.unshare(cx)?;
4646            } else {
4647                this.disconnected_from_host(cx);
4648            }
4649            Ok(())
4650        })
4651    }
4652
4653    async fn handle_add_collaborator(
4654        this: Entity<Self>,
4655        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4656        mut cx: AsyncApp,
4657    ) -> Result<()> {
4658        let collaborator = envelope
4659            .payload
4660            .collaborator
4661            .take()
4662            .context("empty collaborator")?;
4663
4664        let collaborator = Collaborator::from_proto(collaborator)?;
4665        this.update(&mut cx, |this, cx| {
4666            this.buffer_store.update(cx, |buffer_store, _| {
4667                buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
4668            });
4669            this.breakpoint_store.read(cx).broadcast();
4670            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
4671            this.collaborators
4672                .insert(collaborator.peer_id, collaborator);
4673        });
4674
4675        Ok(())
4676    }
4677
4678    async fn handle_update_project_collaborator(
4679        this: Entity<Self>,
4680        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4681        mut cx: AsyncApp,
4682    ) -> Result<()> {
4683        let old_peer_id = envelope
4684            .payload
4685            .old_peer_id
4686            .context("missing old peer id")?;
4687        let new_peer_id = envelope
4688            .payload
4689            .new_peer_id
4690            .context("missing new peer id")?;
4691        this.update(&mut cx, |this, cx| {
4692            let collaborator = this
4693                .collaborators
4694                .remove(&old_peer_id)
4695                .context("received UpdateProjectCollaborator for unknown peer")?;
4696            let is_host = collaborator.is_host;
4697            this.collaborators.insert(new_peer_id, collaborator);
4698
4699            log::info!("peer {} became {}", old_peer_id, new_peer_id,);
4700            this.buffer_store.update(cx, |buffer_store, _| {
4701                buffer_store.update_peer_id(&old_peer_id, new_peer_id)
4702            });
4703
4704            if is_host {
4705                this.buffer_store
4706                    .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
4707                this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
4708                    .unwrap();
4709                cx.emit(Event::HostReshared);
4710            }
4711
4712            cx.emit(Event::CollaboratorUpdated {
4713                old_peer_id,
4714                new_peer_id,
4715            });
4716            Ok(())
4717        })
4718    }
4719
4720    async fn handle_remove_collaborator(
4721        this: Entity<Self>,
4722        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4723        mut cx: AsyncApp,
4724    ) -> Result<()> {
4725        this.update(&mut cx, |this, cx| {
4726            let peer_id = envelope.payload.peer_id.context("invalid peer id")?;
4727            let replica_id = this
4728                .collaborators
4729                .remove(&peer_id)
4730                .with_context(|| format!("unknown peer {peer_id:?}"))?
4731                .replica_id;
4732            this.buffer_store.update(cx, |buffer_store, cx| {
4733                buffer_store.forget_shared_buffers_for(&peer_id);
4734                for buffer in buffer_store.buffers() {
4735                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4736                }
4737            });
4738            this.git_store.update(cx, |git_store, _| {
4739                git_store.forget_shared_diffs_for(&peer_id);
4740            });
4741
4742            cx.emit(Event::CollaboratorLeft(peer_id));
4743            Ok(())
4744        })
4745    }
4746
4747    async fn handle_update_project(
4748        this: Entity<Self>,
4749        envelope: TypedEnvelope<proto::UpdateProject>,
4750        mut cx: AsyncApp,
4751    ) -> Result<()> {
4752        this.update(&mut cx, |this, cx| {
4753            // Don't handle messages that were sent before the response to us joining the project
4754            if envelope.message_id > this.join_project_response_message_id {
4755                cx.update_global::<SettingsStore, _>(|store, cx| {
4756                    for worktree_metadata in &envelope.payload.worktrees {
4757                        store
4758                            .clear_local_settings(WorktreeId::from_proto(worktree_metadata.id), cx)
4759                            .log_err();
4760                    }
4761                });
4762
4763                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4764            }
4765            Ok(())
4766        })
4767    }
4768
4769    async fn handle_toast(
4770        this: Entity<Self>,
4771        envelope: TypedEnvelope<proto::Toast>,
4772        mut cx: AsyncApp,
4773    ) -> Result<()> {
4774        this.update(&mut cx, |_, cx| {
4775            cx.emit(Event::Toast {
4776                notification_id: envelope.payload.notification_id.into(),
4777                message: envelope.payload.message,
4778            });
4779            Ok(())
4780        })
4781    }
4782
4783    async fn handle_language_server_prompt_request(
4784        this: Entity<Self>,
4785        envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
4786        mut cx: AsyncApp,
4787    ) -> Result<proto::LanguageServerPromptResponse> {
4788        let (tx, rx) = smol::channel::bounded(1);
4789        let actions: Vec<_> = envelope
4790            .payload
4791            .actions
4792            .into_iter()
4793            .map(|action| MessageActionItem {
4794                title: action,
4795                properties: Default::default(),
4796            })
4797            .collect();
4798        this.update(&mut cx, |_, cx| {
4799            cx.emit(Event::LanguageServerPrompt(LanguageServerPromptRequest {
4800                level: proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
4801                message: envelope.payload.message,
4802                actions: actions.clone(),
4803                lsp_name: envelope.payload.lsp_name,
4804                response_channel: tx,
4805            }));
4806
4807            anyhow::Ok(())
4808        })?;
4809
4810        // We drop `this` to avoid holding a reference in this future for too
4811        // long.
4812        // If we keep the reference, we might not drop the `Project` early
4813        // enough when closing a window and it will only get releases on the
4814        // next `flush_effects()` call.
4815        drop(this);
4816
4817        let mut rx = pin!(rx);
4818        let answer = rx.next().await;
4819
4820        Ok(LanguageServerPromptResponse {
4821            action_response: answer.and_then(|answer| {
4822                actions
4823                    .iter()
4824                    .position(|action| *action == answer)
4825                    .map(|index| index as u64)
4826            }),
4827        })
4828    }
4829
4830    async fn handle_hide_toast(
4831        this: Entity<Self>,
4832        envelope: TypedEnvelope<proto::HideToast>,
4833        mut cx: AsyncApp,
4834    ) -> Result<()> {
4835        this.update(&mut cx, |_, cx| {
4836            cx.emit(Event::HideToast {
4837                notification_id: envelope.payload.notification_id.into(),
4838            });
4839            Ok(())
4840        })
4841    }
4842
4843    // Collab sends UpdateWorktree protos as messages
4844    async fn handle_update_worktree(
4845        this: Entity<Self>,
4846        envelope: TypedEnvelope<proto::UpdateWorktree>,
4847        mut cx: AsyncApp,
4848    ) -> Result<()> {
4849        this.update(&mut cx, |project, cx| {
4850            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4851            if let Some(worktree) = project.worktree_for_id(worktree_id, cx) {
4852                worktree.update(cx, |worktree, _| {
4853                    let worktree = worktree.as_remote_mut().unwrap();
4854                    worktree.update_from_remote(envelope.payload);
4855                });
4856            }
4857            Ok(())
4858        })
4859    }
4860
4861    async fn handle_update_buffer_from_remote_server(
4862        this: Entity<Self>,
4863        envelope: TypedEnvelope<proto::UpdateBuffer>,
4864        cx: AsyncApp,
4865    ) -> Result<proto::Ack> {
4866        let buffer_store = this.read_with(&cx, |this, cx| {
4867            if let Some(remote_id) = this.remote_id() {
4868                let mut payload = envelope.payload.clone();
4869                payload.project_id = remote_id;
4870                cx.background_spawn(this.collab_client.request(payload))
4871                    .detach_and_log_err(cx);
4872            }
4873            this.buffer_store.clone()
4874        });
4875        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4876    }
4877
4878    async fn handle_trust_worktrees(
4879        this: Entity<Self>,
4880        envelope: TypedEnvelope<proto::TrustWorktrees>,
4881        mut cx: AsyncApp,
4882    ) -> Result<proto::Ack> {
4883        if this.read_with(&cx, |project, _| project.is_via_collab()) {
4884            return Ok(proto::Ack {});
4885        }
4886
4887        let trusted_worktrees = cx
4888            .update(|cx| TrustedWorktrees::try_get_global(cx))
4889            .context("missing trusted worktrees")?;
4890        trusted_worktrees.update(&mut cx, |trusted_worktrees, cx| {
4891            trusted_worktrees.trust(
4892                &this.read(cx).worktree_store(),
4893                envelope
4894                    .payload
4895                    .trusted_paths
4896                    .into_iter()
4897                    .filter_map(|proto_path| PathTrust::from_proto(proto_path))
4898                    .collect(),
4899                cx,
4900            );
4901        });
4902        Ok(proto::Ack {})
4903    }
4904
4905    async fn handle_restrict_worktrees(
4906        this: Entity<Self>,
4907        envelope: TypedEnvelope<proto::RestrictWorktrees>,
4908        mut cx: AsyncApp,
4909    ) -> Result<proto::Ack> {
4910        if this.read_with(&cx, |project, _| project.is_via_collab()) {
4911            return Ok(proto::Ack {});
4912        }
4913
4914        let trusted_worktrees = cx
4915            .update(|cx| TrustedWorktrees::try_get_global(cx))
4916            .context("missing trusted worktrees")?;
4917        trusted_worktrees.update(&mut cx, |trusted_worktrees, cx| {
4918            let worktree_store = this.read(cx).worktree_store().downgrade();
4919            let restricted_paths = envelope
4920                .payload
4921                .worktree_ids
4922                .into_iter()
4923                .map(WorktreeId::from_proto)
4924                .map(PathTrust::Worktree)
4925                .collect::<HashSet<_>>();
4926            trusted_worktrees.restrict(worktree_store, restricted_paths, cx);
4927        });
4928        Ok(proto::Ack {})
4929    }
4930
4931    // Goes from host to client.
4932    async fn handle_find_search_candidates_chunk(
4933        this: Entity<Self>,
4934        envelope: TypedEnvelope<proto::FindSearchCandidatesChunk>,
4935        mut cx: AsyncApp,
4936    ) -> Result<proto::Ack> {
4937        let buffer_store = this.read_with(&mut cx, |this, _| this.buffer_store.clone());
4938        BufferStore::handle_find_search_candidates_chunk(buffer_store, envelope, cx).await
4939    }
4940
4941    // Goes from client to host.
4942    async fn handle_find_search_candidates_cancel(
4943        this: Entity<Self>,
4944        envelope: TypedEnvelope<proto::FindSearchCandidatesCancelled>,
4945        mut cx: AsyncApp,
4946    ) -> Result<()> {
4947        let buffer_store = this.read_with(&mut cx, |this, _| this.buffer_store.clone());
4948        BufferStore::handle_find_search_candidates_cancel(buffer_store, envelope, cx).await
4949    }
4950
4951    async fn handle_update_buffer(
4952        this: Entity<Self>,
4953        envelope: TypedEnvelope<proto::UpdateBuffer>,
4954        cx: AsyncApp,
4955    ) -> Result<proto::Ack> {
4956        let buffer_store = this.read_with(&cx, |this, cx| {
4957            if let Some(ssh) = &this.remote_client {
4958                let mut payload = envelope.payload.clone();
4959                payload.project_id = REMOTE_SERVER_PROJECT_ID;
4960                cx.background_spawn(ssh.read(cx).proto_client().request(payload))
4961                    .detach_and_log_err(cx);
4962            }
4963            this.buffer_store.clone()
4964        });
4965        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4966    }
4967
4968    fn retain_remotely_created_models(
4969        &mut self,
4970        cx: &mut Context<Self>,
4971    ) -> RemotelyCreatedModelGuard {
4972        Self::retain_remotely_created_models_impl(
4973            &self.remotely_created_models,
4974            &self.buffer_store,
4975            &self.worktree_store,
4976            cx,
4977        )
4978    }
4979
4980    fn retain_remotely_created_models_impl(
4981        models: &Arc<Mutex<RemotelyCreatedModels>>,
4982        buffer_store: &Entity<BufferStore>,
4983        worktree_store: &Entity<WorktreeStore>,
4984        cx: &mut App,
4985    ) -> RemotelyCreatedModelGuard {
4986        {
4987            let mut remotely_create_models = models.lock();
4988            if remotely_create_models.retain_count == 0 {
4989                remotely_create_models.buffers = buffer_store.read(cx).buffers().collect();
4990                remotely_create_models.worktrees = worktree_store.read(cx).worktrees().collect();
4991            }
4992            remotely_create_models.retain_count += 1;
4993        }
4994        RemotelyCreatedModelGuard {
4995            remote_models: Arc::downgrade(&models),
4996        }
4997    }
4998
4999    async fn handle_create_buffer_for_peer(
5000        this: Entity<Self>,
5001        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
5002        mut cx: AsyncApp,
5003    ) -> Result<()> {
5004        this.update(&mut cx, |this, cx| {
5005            this.buffer_store.update(cx, |buffer_store, cx| {
5006                buffer_store.handle_create_buffer_for_peer(
5007                    envelope,
5008                    this.replica_id(),
5009                    this.capability(),
5010                    cx,
5011                )
5012            })
5013        })
5014    }
5015
5016    async fn handle_toggle_lsp_logs(
5017        project: Entity<Self>,
5018        envelope: TypedEnvelope<proto::ToggleLspLogs>,
5019        mut cx: AsyncApp,
5020    ) -> Result<()> {
5021        let toggled_log_kind =
5022            match proto::toggle_lsp_logs::LogType::from_i32(envelope.payload.log_type)
5023                .context("invalid log type")?
5024            {
5025                proto::toggle_lsp_logs::LogType::Log => LogKind::Logs,
5026                proto::toggle_lsp_logs::LogType::Trace => LogKind::Trace,
5027                proto::toggle_lsp_logs::LogType::Rpc => LogKind::Rpc,
5028            };
5029        project.update(&mut cx, |_, cx| {
5030            cx.emit(Event::ToggleLspLogs {
5031                server_id: LanguageServerId::from_proto(envelope.payload.server_id),
5032                enabled: envelope.payload.enabled,
5033                toggled_log_kind,
5034            })
5035        });
5036        Ok(())
5037    }
5038
5039    async fn handle_synchronize_buffers(
5040        this: Entity<Self>,
5041        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
5042        mut cx: AsyncApp,
5043    ) -> Result<proto::SynchronizeBuffersResponse> {
5044        let response = this.update(&mut cx, |this, cx| {
5045            let client = this.collab_client.clone();
5046            this.buffer_store.update(cx, |this, cx| {
5047                this.handle_synchronize_buffers(envelope, cx, client)
5048            })
5049        })?;
5050
5051        Ok(response)
5052    }
5053
5054    // Goes from client to host.
5055    async fn handle_search_candidate_buffers(
5056        this: Entity<Self>,
5057        envelope: TypedEnvelope<proto::FindSearchCandidates>,
5058        mut cx: AsyncApp,
5059    ) -> Result<proto::Ack> {
5060        let peer_id = envelope.original_sender_id.unwrap_or(envelope.sender_id);
5061        let message = envelope.payload;
5062        let project_id = message.project_id;
5063        let path_style = this.read_with(&cx, |this, cx| this.path_style(cx));
5064        let query =
5065            SearchQuery::from_proto(message.query.context("missing query field")?, path_style)?;
5066
5067        let handle = message.handle;
5068        let buffer_store = this.read_with(&cx, |this, _| this.buffer_store().clone());
5069        let client = this.read_with(&cx, |this, _| this.client());
5070        let task = cx.spawn(async move |cx| {
5071            let results = this.update(cx, |this, cx| {
5072                this.search_impl(query, cx).matching_buffers(cx)
5073            });
5074            let (batcher, batches) = project_search::AdaptiveBatcher::new(cx.background_executor());
5075            let mut new_matches = Box::pin(results.rx);
5076
5077            let sender_task = cx.background_executor().spawn({
5078                let client = client.clone();
5079                async move {
5080                    let mut batches = std::pin::pin!(batches);
5081                    while let Some(buffer_ids) = batches.next().await {
5082                        client
5083                            .request(proto::FindSearchCandidatesChunk {
5084                                handle,
5085                                peer_id: Some(peer_id),
5086                                project_id,
5087                                variant: Some(
5088                                    proto::find_search_candidates_chunk::Variant::Matches(
5089                                        proto::FindSearchCandidatesMatches { buffer_ids },
5090                                    ),
5091                                ),
5092                            })
5093                            .await?;
5094                    }
5095                    anyhow::Ok(())
5096                }
5097            });
5098
5099            while let Some(buffer) = new_matches.next().await {
5100                let buffer_id = this.update(cx, |this, cx| {
5101                    this.create_buffer_for_peer(&buffer, peer_id, cx).to_proto()
5102                });
5103                batcher.push(buffer_id).await;
5104            }
5105            batcher.flush().await;
5106
5107            sender_task.await?;
5108
5109            let _ = client
5110                .request(proto::FindSearchCandidatesChunk {
5111                    handle,
5112                    peer_id: Some(peer_id),
5113                    project_id,
5114                    variant: Some(proto::find_search_candidates_chunk::Variant::Done(
5115                        proto::FindSearchCandidatesDone {},
5116                    )),
5117                })
5118                .await?;
5119            anyhow::Ok(())
5120        });
5121        buffer_store.update(&mut cx, |this, _| {
5122            this.register_ongoing_project_search((peer_id, handle), task);
5123        });
5124
5125        Ok(proto::Ack {})
5126    }
5127
5128    async fn handle_open_buffer_by_id(
5129        this: Entity<Self>,
5130        envelope: TypedEnvelope<proto::OpenBufferById>,
5131        mut cx: AsyncApp,
5132    ) -> Result<proto::OpenBufferResponse> {
5133        let peer_id = envelope.original_sender_id()?;
5134        let buffer_id = BufferId::new(envelope.payload.id)?;
5135        let buffer = this
5136            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))
5137            .await?;
5138        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
5139    }
5140
5141    async fn handle_open_buffer_by_path(
5142        this: Entity<Self>,
5143        envelope: TypedEnvelope<proto::OpenBufferByPath>,
5144        mut cx: AsyncApp,
5145    ) -> Result<proto::OpenBufferResponse> {
5146        let peer_id = envelope.original_sender_id()?;
5147        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5148        let path = RelPath::from_proto(&envelope.payload.path)?;
5149        let open_buffer = this
5150            .update(&mut cx, |this, cx| {
5151                this.open_buffer(ProjectPath { worktree_id, path }, cx)
5152            })
5153            .await?;
5154        Project::respond_to_open_buffer_request(this, open_buffer, peer_id, &mut cx)
5155    }
5156
5157    async fn handle_open_new_buffer(
5158        this: Entity<Self>,
5159        envelope: TypedEnvelope<proto::OpenNewBuffer>,
5160        mut cx: AsyncApp,
5161    ) -> Result<proto::OpenBufferResponse> {
5162        let buffer = this
5163            .update(&mut cx, |this, cx| this.create_buffer(true, cx))
5164            .await?;
5165        let peer_id = envelope.original_sender_id()?;
5166
5167        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
5168    }
5169
5170    fn respond_to_open_buffer_request(
5171        this: Entity<Self>,
5172        buffer: Entity<Buffer>,
5173        peer_id: proto::PeerId,
5174        cx: &mut AsyncApp,
5175    ) -> Result<proto::OpenBufferResponse> {
5176        this.update(cx, |this, cx| {
5177            let is_private = buffer
5178                .read(cx)
5179                .file()
5180                .map(|f| f.is_private())
5181                .unwrap_or_default();
5182            anyhow::ensure!(!is_private, ErrorCode::UnsharedItem);
5183            Ok(proto::OpenBufferResponse {
5184                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
5185            })
5186        })
5187    }
5188
5189    fn create_buffer_for_peer(
5190        &mut self,
5191        buffer: &Entity<Buffer>,
5192        peer_id: proto::PeerId,
5193        cx: &mut App,
5194    ) -> BufferId {
5195        self.buffer_store
5196            .update(cx, |buffer_store, cx| {
5197                buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
5198            })
5199            .detach_and_log_err(cx);
5200        buffer.read(cx).remote_id()
5201    }
5202
5203    async fn handle_create_image_for_peer(
5204        this: Entity<Self>,
5205        envelope: TypedEnvelope<proto::CreateImageForPeer>,
5206        mut cx: AsyncApp,
5207    ) -> Result<()> {
5208        this.update(&mut cx, |this, cx| {
5209            this.image_store.update(cx, |image_store, cx| {
5210                image_store.handle_create_image_for_peer(envelope, cx)
5211            })
5212        })
5213    }
5214
5215    fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
5216        let project_id = match self.client_state {
5217            ProjectClientState::Remote {
5218                sharing_has_stopped,
5219                remote_id,
5220                ..
5221            } => {
5222                if sharing_has_stopped {
5223                    return Task::ready(Err(anyhow!(
5224                        "can't synchronize remote buffers on a readonly project"
5225                    )));
5226                } else {
5227                    remote_id
5228                }
5229            }
5230            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
5231                return Task::ready(Err(anyhow!(
5232                    "can't synchronize remote buffers on a local project"
5233                )));
5234            }
5235        };
5236
5237        let client = self.collab_client.clone();
5238        cx.spawn(async move |this, cx| {
5239            let (buffers, incomplete_buffer_ids) = this.update(cx, |this, cx| {
5240                this.buffer_store.read(cx).buffer_version_info(cx)
5241            })?;
5242            let response = client
5243                .request(proto::SynchronizeBuffers {
5244                    project_id,
5245                    buffers,
5246                })
5247                .await?;
5248
5249            let send_updates_for_buffers = this.update(cx, |this, cx| {
5250                response
5251                    .buffers
5252                    .into_iter()
5253                    .map(|buffer| {
5254                        let client = client.clone();
5255                        let buffer_id = match BufferId::new(buffer.id) {
5256                            Ok(id) => id,
5257                            Err(e) => {
5258                                return Task::ready(Err(e));
5259                            }
5260                        };
5261                        let remote_version = language::proto::deserialize_version(&buffer.version);
5262                        if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5263                            let operations =
5264                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
5265                            cx.background_spawn(async move {
5266                                let operations = operations.await;
5267                                for chunk in split_operations(operations) {
5268                                    client
5269                                        .request(proto::UpdateBuffer {
5270                                            project_id,
5271                                            buffer_id: buffer_id.into(),
5272                                            operations: chunk,
5273                                        })
5274                                        .await?;
5275                                }
5276                                anyhow::Ok(())
5277                            })
5278                        } else {
5279                            Task::ready(Ok(()))
5280                        }
5281                    })
5282                    .collect::<Vec<_>>()
5283            })?;
5284
5285            // Any incomplete buffers have open requests waiting. Request that the host sends
5286            // creates these buffers for us again to unblock any waiting futures.
5287            for id in incomplete_buffer_ids {
5288                cx.background_spawn(client.request(proto::OpenBufferById {
5289                    project_id,
5290                    id: id.into(),
5291                }))
5292                .detach();
5293            }
5294
5295            futures::future::join_all(send_updates_for_buffers)
5296                .await
5297                .into_iter()
5298                .collect()
5299        })
5300    }
5301
5302    pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
5303        self.worktree_store.read(cx).worktree_metadata_protos(cx)
5304    }
5305
5306    /// Iterator of all open buffers that have unsaved changes
5307    pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
5308        self.buffer_store.read(cx).buffers().filter_map(|buf| {
5309            let buf = buf.read(cx);
5310            if buf.is_dirty() {
5311                buf.project_path(cx)
5312            } else {
5313                None
5314            }
5315        })
5316    }
5317
5318    fn set_worktrees_from_proto(
5319        &mut self,
5320        worktrees: Vec<proto::WorktreeMetadata>,
5321        cx: &mut Context<Project>,
5322    ) -> Result<()> {
5323        self.worktree_store.update(cx, |worktree_store, cx| {
5324            worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
5325        })
5326    }
5327
5328    fn set_collaborators_from_proto(
5329        &mut self,
5330        messages: Vec<proto::Collaborator>,
5331        cx: &mut Context<Self>,
5332    ) -> Result<()> {
5333        let mut collaborators = HashMap::default();
5334        for message in messages {
5335            let collaborator = Collaborator::from_proto(message)?;
5336            collaborators.insert(collaborator.peer_id, collaborator);
5337        }
5338        for old_peer_id in self.collaborators.keys() {
5339            if !collaborators.contains_key(old_peer_id) {
5340                cx.emit(Event::CollaboratorLeft(*old_peer_id));
5341            }
5342        }
5343        self.collaborators = collaborators;
5344        Ok(())
5345    }
5346
5347    pub fn supplementary_language_servers<'a>(
5348        &'a self,
5349        cx: &'a App,
5350    ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
5351        self.lsp_store.read(cx).supplementary_language_servers()
5352    }
5353
5354    pub fn any_language_server_supports_inlay_hints(&self, buffer: &Buffer, cx: &mut App) -> bool {
5355        let Some(language) = buffer.language().cloned() else {
5356            return false;
5357        };
5358        self.lsp_store.update(cx, |lsp_store, _| {
5359            let relevant_language_servers = lsp_store
5360                .languages
5361                .lsp_adapters(&language.name())
5362                .into_iter()
5363                .map(|lsp_adapter| lsp_adapter.name())
5364                .collect::<HashSet<_>>();
5365            lsp_store
5366                .language_server_statuses()
5367                .filter_map(|(server_id, server_status)| {
5368                    relevant_language_servers
5369                        .contains(&server_status.name)
5370                        .then_some(server_id)
5371                })
5372                .filter_map(|server_id| lsp_store.lsp_server_capabilities.get(&server_id))
5373                .any(InlayHints::check_capabilities)
5374        })
5375    }
5376
5377    pub fn language_server_id_for_name(
5378        &self,
5379        buffer: &Buffer,
5380        name: &LanguageServerName,
5381        cx: &App,
5382    ) -> Option<LanguageServerId> {
5383        let language = buffer.language()?;
5384        let relevant_language_servers = self
5385            .languages
5386            .lsp_adapters(&language.name())
5387            .into_iter()
5388            .map(|lsp_adapter| lsp_adapter.name())
5389            .collect::<HashSet<_>>();
5390        if !relevant_language_servers.contains(name) {
5391            return None;
5392        }
5393        self.language_server_statuses(cx)
5394            .filter(|(_, server_status)| relevant_language_servers.contains(&server_status.name))
5395            .find_map(|(server_id, server_status)| {
5396                if &server_status.name == name {
5397                    Some(server_id)
5398                } else {
5399                    None
5400                }
5401            })
5402    }
5403
5404    #[cfg(any(test, feature = "test-support"))]
5405    pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
5406        self.lsp_store.update(cx, |this, cx| {
5407            this.running_language_servers_for_local_buffer(buffer, cx)
5408                .next()
5409                .is_some()
5410        })
5411    }
5412
5413    pub fn git_init(
5414        &self,
5415        path: Arc<Path>,
5416        fallback_branch_name: String,
5417        cx: &App,
5418    ) -> Task<Result<()>> {
5419        self.git_store
5420            .read(cx)
5421            .git_init(path, fallback_branch_name, cx)
5422    }
5423
5424    pub fn buffer_store(&self) -> &Entity<BufferStore> {
5425        &self.buffer_store
5426    }
5427
5428    pub fn git_store(&self) -> &Entity<GitStore> {
5429        &self.git_store
5430    }
5431
5432    pub fn agent_server_store(&self) -> &Entity<AgentServerStore> {
5433        &self.agent_server_store
5434    }
5435
5436    #[cfg(test)]
5437    fn git_scans_complete(&self, cx: &Context<Self>) -> Task<()> {
5438        cx.spawn(async move |this, cx| {
5439            let scans_complete = this
5440                .read_with(cx, |this, cx| {
5441                    this.worktrees(cx)
5442                        .filter_map(|worktree| Some(worktree.read(cx).as_local()?.scan_complete()))
5443                        .collect::<Vec<_>>()
5444                })
5445                .unwrap();
5446            join_all(scans_complete).await;
5447            let barriers = this
5448                .update(cx, |this, cx| {
5449                    let repos = this.repositories(cx).values().cloned().collect::<Vec<_>>();
5450                    repos
5451                        .into_iter()
5452                        .map(|repo| repo.update(cx, |repo, _| repo.barrier()))
5453                        .collect::<Vec<_>>()
5454                })
5455                .unwrap();
5456            join_all(barriers).await;
5457        })
5458    }
5459
5460    pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
5461        self.git_store.read(cx).active_repository()
5462    }
5463
5464    pub fn repositories<'a>(&self, cx: &'a App) -> &'a HashMap<RepositoryId, Entity<Repository>> {
5465        self.git_store.read(cx).repositories()
5466    }
5467
5468    pub fn status_for_buffer_id(&self, buffer_id: BufferId, cx: &App) -> Option<FileStatus> {
5469        self.git_store.read(cx).status_for_buffer_id(buffer_id, cx)
5470    }
5471
5472    pub fn set_agent_location(
5473        &mut self,
5474        new_location: Option<AgentLocation>,
5475        cx: &mut Context<Self>,
5476    ) {
5477        if let Some(old_location) = self.agent_location.as_ref() {
5478            old_location
5479                .buffer
5480                .update(cx, |buffer, cx| buffer.remove_agent_selections(cx))
5481                .ok();
5482        }
5483
5484        if let Some(location) = new_location.as_ref() {
5485            location
5486                .buffer
5487                .update(cx, |buffer, cx| {
5488                    buffer.set_agent_selections(
5489                        Arc::from([language::Selection {
5490                            id: 0,
5491                            start: location.position,
5492                            end: location.position,
5493                            reversed: false,
5494                            goal: language::SelectionGoal::None,
5495                        }]),
5496                        false,
5497                        CursorShape::Hollow,
5498                        cx,
5499                    )
5500                })
5501                .ok();
5502        }
5503
5504        self.agent_location = new_location;
5505        cx.emit(Event::AgentLocationChanged);
5506    }
5507
5508    pub fn agent_location(&self) -> Option<AgentLocation> {
5509        self.agent_location.clone()
5510    }
5511
5512    pub fn path_style(&self, cx: &App) -> PathStyle {
5513        self.worktree_store.read(cx).path_style()
5514    }
5515
5516    pub fn contains_local_settings_file(
5517        &self,
5518        worktree_id: WorktreeId,
5519        rel_path: &RelPath,
5520        cx: &App,
5521    ) -> bool {
5522        self.worktree_for_id(worktree_id, cx)
5523            .map_or(false, |worktree| {
5524                worktree.read(cx).entry_for_path(rel_path).is_some()
5525            })
5526    }
5527
5528    pub fn update_local_settings_file(
5529        &self,
5530        worktree_id: WorktreeId,
5531        rel_path: Arc<RelPath>,
5532        cx: &mut App,
5533        update: impl 'static + Send + FnOnce(&mut settings::SettingsContent, &App),
5534    ) {
5535        let Some(worktree) = self.worktree_for_id(worktree_id, cx) else {
5536            // todo(settings_ui) error?
5537            return;
5538        };
5539        cx.spawn(async move |cx| {
5540            let file = worktree
5541                .update(cx, |worktree, cx| worktree.load_file(&rel_path, cx))
5542                .await
5543                .context("Failed to load settings file")?;
5544
5545            let has_bom = file.has_bom;
5546
5547            let new_text = cx.read_global::<SettingsStore, _>(|store, cx| {
5548                store.new_text_for_update(file.text, move |settings| update(settings, cx))
5549            });
5550            worktree
5551                .update(cx, |worktree, cx| {
5552                    let line_ending = text::LineEnding::detect(&new_text);
5553                    worktree.write_file(
5554                        rel_path.clone(),
5555                        new_text.into(),
5556                        line_ending,
5557                        encoding_rs::UTF_8,
5558                        has_bom,
5559                        cx,
5560                    )
5561                })
5562                .await
5563                .context("Failed to write settings file")?;
5564
5565            anyhow::Ok(())
5566        })
5567        .detach_and_log_err(cx);
5568    }
5569}
5570
5571pub struct PathMatchCandidateSet {
5572    pub snapshot: Snapshot,
5573    pub include_ignored: bool,
5574    pub include_root_name: bool,
5575    pub candidates: Candidates,
5576}
5577
5578pub enum Candidates {
5579    /// Only consider directories.
5580    Directories,
5581    /// Only consider files.
5582    Files,
5583    /// Consider directories and files.
5584    Entries,
5585}
5586
5587impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
5588    type Candidates = PathMatchCandidateSetIter<'a>;
5589
5590    fn id(&self) -> usize {
5591        self.snapshot.id().to_usize()
5592    }
5593
5594    fn len(&self) -> usize {
5595        match self.candidates {
5596            Candidates::Files => {
5597                if self.include_ignored {
5598                    self.snapshot.file_count()
5599                } else {
5600                    self.snapshot.visible_file_count()
5601                }
5602            }
5603
5604            Candidates::Directories => {
5605                if self.include_ignored {
5606                    self.snapshot.dir_count()
5607                } else {
5608                    self.snapshot.visible_dir_count()
5609                }
5610            }
5611
5612            Candidates::Entries => {
5613                if self.include_ignored {
5614                    self.snapshot.entry_count()
5615                } else {
5616                    self.snapshot.visible_entry_count()
5617                }
5618            }
5619        }
5620    }
5621
5622    fn prefix(&self) -> Arc<RelPath> {
5623        if self.snapshot.root_entry().is_some_and(|e| e.is_file()) || self.include_root_name {
5624            self.snapshot.root_name().into()
5625        } else {
5626            RelPath::empty().into()
5627        }
5628    }
5629
5630    fn root_is_file(&self) -> bool {
5631        self.snapshot.root_entry().is_some_and(|f| f.is_file())
5632    }
5633
5634    fn path_style(&self) -> PathStyle {
5635        self.snapshot.path_style()
5636    }
5637
5638    fn candidates(&'a self, start: usize) -> Self::Candidates {
5639        PathMatchCandidateSetIter {
5640            traversal: match self.candidates {
5641                Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
5642                Candidates::Files => self.snapshot.files(self.include_ignored, start),
5643                Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
5644            },
5645        }
5646    }
5647}
5648
5649pub struct PathMatchCandidateSetIter<'a> {
5650    traversal: Traversal<'a>,
5651}
5652
5653impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
5654    type Item = fuzzy::PathMatchCandidate<'a>;
5655
5656    fn next(&mut self) -> Option<Self::Item> {
5657        self.traversal
5658            .next()
5659            .map(|entry| fuzzy::PathMatchCandidate {
5660                is_dir: entry.kind.is_dir(),
5661                path: &entry.path,
5662                char_bag: entry.char_bag,
5663            })
5664    }
5665}
5666
5667impl EventEmitter<Event> for Project {}
5668
5669impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
5670    fn from(val: &'a ProjectPath) -> Self {
5671        SettingsLocation {
5672            worktree_id: val.worktree_id,
5673            path: val.path.as_ref(),
5674        }
5675    }
5676}
5677
5678impl<P: Into<Arc<RelPath>>> From<(WorktreeId, P)> for ProjectPath {
5679    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
5680        Self {
5681            worktree_id,
5682            path: path.into(),
5683        }
5684    }
5685}
5686
5687/// ResolvedPath is a path that has been resolved to either a ProjectPath
5688/// or an AbsPath and that *exists*.
5689#[derive(Debug, Clone)]
5690pub enum ResolvedPath {
5691    ProjectPath {
5692        project_path: ProjectPath,
5693        is_dir: bool,
5694    },
5695    AbsPath {
5696        path: String,
5697        is_dir: bool,
5698    },
5699}
5700
5701impl ResolvedPath {
5702    pub fn abs_path(&self) -> Option<&str> {
5703        match self {
5704            Self::AbsPath { path, .. } => Some(path),
5705            _ => None,
5706        }
5707    }
5708
5709    pub fn into_abs_path(self) -> Option<String> {
5710        match self {
5711            Self::AbsPath { path, .. } => Some(path),
5712            _ => None,
5713        }
5714    }
5715
5716    pub fn project_path(&self) -> Option<&ProjectPath> {
5717        match self {
5718            Self::ProjectPath { project_path, .. } => Some(project_path),
5719            _ => None,
5720        }
5721    }
5722
5723    pub fn is_file(&self) -> bool {
5724        !self.is_dir()
5725    }
5726
5727    pub fn is_dir(&self) -> bool {
5728        match self {
5729            Self::ProjectPath { is_dir, .. } => *is_dir,
5730            Self::AbsPath { is_dir, .. } => *is_dir,
5731        }
5732    }
5733}
5734
5735impl ProjectItem for Buffer {
5736    fn try_open(
5737        project: &Entity<Project>,
5738        path: &ProjectPath,
5739        cx: &mut App,
5740    ) -> Option<Task<Result<Entity<Self>>>> {
5741        Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
5742    }
5743
5744    fn entry_id(&self, _cx: &App) -> Option<ProjectEntryId> {
5745        File::from_dyn(self.file()).and_then(|file| file.project_entry_id())
5746    }
5747
5748    fn project_path(&self, cx: &App) -> Option<ProjectPath> {
5749        let file = self.file()?;
5750
5751        (!matches!(file.disk_state(), DiskState::Historic { .. })).then(|| ProjectPath {
5752            worktree_id: file.worktree_id(cx),
5753            path: file.path().clone(),
5754        })
5755    }
5756
5757    fn is_dirty(&self) -> bool {
5758        self.is_dirty()
5759    }
5760}
5761
5762impl Completion {
5763    pub fn kind(&self) -> Option<CompletionItemKind> {
5764        self.source
5765            // `lsp::CompletionListItemDefaults` has no `kind` field
5766            .lsp_completion(false)
5767            .and_then(|lsp_completion| lsp_completion.kind)
5768    }
5769
5770    pub fn label(&self) -> Option<String> {
5771        self.source
5772            .lsp_completion(false)
5773            .map(|lsp_completion| lsp_completion.label.clone())
5774    }
5775
5776    /// A key that can be used to sort completions when displaying
5777    /// them to the user.
5778    pub fn sort_key(&self) -> (usize, &str) {
5779        const DEFAULT_KIND_KEY: usize = 4;
5780        let kind_key = self
5781            .kind()
5782            .and_then(|lsp_completion_kind| match lsp_completion_kind {
5783                lsp::CompletionItemKind::KEYWORD => Some(0),
5784                lsp::CompletionItemKind::VARIABLE => Some(1),
5785                lsp::CompletionItemKind::CONSTANT => Some(2),
5786                lsp::CompletionItemKind::PROPERTY => Some(3),
5787                _ => None,
5788            })
5789            .unwrap_or(DEFAULT_KIND_KEY);
5790        (kind_key, self.label.filter_text())
5791    }
5792
5793    /// Whether this completion is a snippet.
5794    pub fn is_snippet_kind(&self) -> bool {
5795        matches!(
5796            &self.source,
5797            CompletionSource::Lsp { lsp_completion, .. }
5798            if lsp_completion.kind == Some(CompletionItemKind::SNIPPET)
5799        )
5800    }
5801
5802    /// Whether this completion is a snippet or snippet-style LSP completion.
5803    pub fn is_snippet(&self) -> bool {
5804        self.source
5805            // `lsp::CompletionListItemDefaults` has `insert_text_format` field
5806            .lsp_completion(true)
5807            .is_some_and(|lsp_completion| {
5808                lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
5809            })
5810    }
5811
5812    /// Returns the corresponding color for this completion.
5813    ///
5814    /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
5815    pub fn color(&self) -> Option<Hsla> {
5816        // `lsp::CompletionListItemDefaults` has no `kind` field
5817        let lsp_completion = self.source.lsp_completion(false)?;
5818        if lsp_completion.kind? == CompletionItemKind::COLOR {
5819            return color_extractor::extract_color(&lsp_completion);
5820        }
5821        None
5822    }
5823}
5824
5825fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
5826    match level {
5827        proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
5828        proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
5829        proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
5830    }
5831}
5832
5833fn provide_inline_values(
5834    captures: impl Iterator<Item = (Range<usize>, language::DebuggerTextObject)>,
5835    snapshot: &language::BufferSnapshot,
5836    max_row: usize,
5837) -> Vec<InlineValueLocation> {
5838    let mut variables = Vec::new();
5839    let mut variable_position = HashSet::default();
5840    let mut scopes = Vec::new();
5841
5842    let active_debug_line_offset = snapshot.point_to_offset(Point::new(max_row as u32, 0));
5843
5844    for (capture_range, capture_kind) in captures {
5845        match capture_kind {
5846            language::DebuggerTextObject::Variable => {
5847                let variable_name = snapshot
5848                    .text_for_range(capture_range.clone())
5849                    .collect::<String>();
5850                let point = snapshot.offset_to_point(capture_range.end);
5851
5852                while scopes
5853                    .last()
5854                    .is_some_and(|scope: &Range<_>| !scope.contains(&capture_range.start))
5855                {
5856                    scopes.pop();
5857                }
5858
5859                if point.row as usize > max_row {
5860                    break;
5861                }
5862
5863                let scope = if scopes
5864                    .last()
5865                    .is_none_or(|scope| !scope.contains(&active_debug_line_offset))
5866                {
5867                    VariableScope::Global
5868                } else {
5869                    VariableScope::Local
5870                };
5871
5872                if variable_position.insert(capture_range.end) {
5873                    variables.push(InlineValueLocation {
5874                        variable_name,
5875                        scope,
5876                        lookup: VariableLookupKind::Variable,
5877                        row: point.row as usize,
5878                        column: point.column as usize,
5879                    });
5880                }
5881            }
5882            language::DebuggerTextObject::Scope => {
5883                while scopes.last().map_or_else(
5884                    || false,
5885                    |scope: &Range<usize>| {
5886                        !(scope.contains(&capture_range.start)
5887                            && scope.contains(&capture_range.end))
5888                    },
5889                ) {
5890                    scopes.pop();
5891                }
5892                scopes.push(capture_range);
5893            }
5894        }
5895    }
5896
5897    variables
5898}
5899
5900#[cfg(test)]
5901mod disable_ai_settings_tests {
5902    use super::*;
5903    use gpui::TestAppContext;
5904    use settings::Settings;
5905
5906    #[gpui::test]
5907    async fn test_disable_ai_settings_security(cx: &mut TestAppContext) {
5908        cx.update(|cx| {
5909            settings::init(cx);
5910
5911            // Test 1: Default is false (AI enabled)
5912            assert!(
5913                !DisableAiSettings::get_global(cx).disable_ai,
5914                "Default should allow AI"
5915            );
5916        });
5917
5918        let disable_true = serde_json::json!({
5919            "disable_ai": true
5920        })
5921        .to_string();
5922        let disable_false = serde_json::json!({
5923            "disable_ai": false
5924        })
5925        .to_string();
5926
5927        cx.update_global::<SettingsStore, _>(|store, cx| {
5928            store.set_user_settings(&disable_false, cx).unwrap();
5929            store.set_global_settings(&disable_true, cx).unwrap();
5930        });
5931        cx.update(|cx| {
5932            assert!(
5933                DisableAiSettings::get_global(cx).disable_ai,
5934                "Local false cannot override global true"
5935            );
5936        });
5937
5938        cx.update_global::<SettingsStore, _>(|store, cx| {
5939            store.set_global_settings(&disable_false, cx).unwrap();
5940            store.set_user_settings(&disable_true, cx).unwrap();
5941        });
5942
5943        cx.update(|cx| {
5944            assert!(
5945                DisableAiSettings::get_global(cx).disable_ai,
5946                "Local false cannot override global true"
5947            );
5948        });
5949    }
5950}