project.rs

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