project.rs

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