project.rs

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