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 delete_file(
2565        &mut self,
2566        path: ProjectPath,
2567        trash: bool,
2568        cx: &mut Context<Self>,
2569    ) -> Option<Task<Result<Option<TrashedEntry>>>> {
2570        let entry = self.entry_for_path(&path, cx)?;
2571        self.delete_entry(entry.id, trash, cx)
2572    }
2573
2574    #[inline]
2575    pub fn delete_entry(
2576        &mut self,
2577        entry_id: ProjectEntryId,
2578        trash: bool,
2579        cx: &mut Context<Self>,
2580    ) -> Option<Task<Result<Option<TrashedEntry>>>> {
2581        dbg!("Project::delete_entry");
2582        let worktree = self.worktree_for_entry(entry_id, cx)?;
2583        cx.emit(Event::DeletedEntry(worktree.read(cx).id(), entry_id));
2584        worktree.update(cx, |worktree, cx| {
2585            worktree.delete_entry(entry_id, trash, cx)
2586        })
2587    }
2588
2589    #[inline]
2590    pub fn restore_entry(
2591        &self,
2592        worktree_id: WorktreeId,
2593        trash_entry: TrashedEntry,
2594        cx: &mut Context<'_, Self>,
2595    ) -> Task<Result<ProjectPath>> {
2596        let Some(worktree) = self.worktree_for_id(worktree_id, cx) else {
2597            return Task::ready(Err(anyhow!("No worktree for id {worktree_id:?}")));
2598        };
2599
2600        cx.spawn(async move |_, cx| {
2601            Worktree::restore_entry(trash_entry, worktree, cx)
2602                .await
2603                .map(|rel_path_buf| ProjectPath {
2604                    worktree_id: worktree_id,
2605                    path: Arc::from(rel_path_buf.as_rel_path()),
2606                })
2607        })
2608    }
2609
2610    #[inline]
2611    pub fn expand_entry(
2612        &mut self,
2613        worktree_id: WorktreeId,
2614        entry_id: ProjectEntryId,
2615        cx: &mut Context<Self>,
2616    ) -> Option<Task<Result<()>>> {
2617        let worktree = self.worktree_for_id(worktree_id, cx)?;
2618        worktree.update(cx, |worktree, cx| worktree.expand_entry(entry_id, cx))
2619    }
2620
2621    pub fn expand_all_for_entry(
2622        &mut self,
2623        worktree_id: WorktreeId,
2624        entry_id: ProjectEntryId,
2625        cx: &mut Context<Self>,
2626    ) -> Option<Task<Result<()>>> {
2627        let worktree = self.worktree_for_id(worktree_id, cx)?;
2628        let task = worktree.update(cx, |worktree, cx| {
2629            worktree.expand_all_for_entry(entry_id, cx)
2630        });
2631        Some(cx.spawn(async move |this, cx| {
2632            task.context("no task")?.await?;
2633            this.update(cx, |_, cx| {
2634                cx.emit(Event::ExpandedAllForEntry(worktree_id, entry_id));
2635            })?;
2636            Ok(())
2637        }))
2638    }
2639
2640    pub fn shared(&mut self, project_id: u64, cx: &mut Context<Self>) -> Result<()> {
2641        anyhow::ensure!(
2642            matches!(self.client_state, ProjectClientState::Local),
2643            "project was already shared"
2644        );
2645
2646        self.client_subscriptions.extend([
2647            self.collab_client
2648                .subscribe_to_entity(project_id)?
2649                .set_entity(&cx.entity(), &cx.to_async()),
2650            self.collab_client
2651                .subscribe_to_entity(project_id)?
2652                .set_entity(&self.worktree_store, &cx.to_async()),
2653            self.collab_client
2654                .subscribe_to_entity(project_id)?
2655                .set_entity(&self.buffer_store, &cx.to_async()),
2656            self.collab_client
2657                .subscribe_to_entity(project_id)?
2658                .set_entity(&self.lsp_store, &cx.to_async()),
2659            self.collab_client
2660                .subscribe_to_entity(project_id)?
2661                .set_entity(&self.settings_observer, &cx.to_async()),
2662            self.collab_client
2663                .subscribe_to_entity(project_id)?
2664                .set_entity(&self.dap_store, &cx.to_async()),
2665            self.collab_client
2666                .subscribe_to_entity(project_id)?
2667                .set_entity(&self.breakpoint_store, &cx.to_async()),
2668            self.collab_client
2669                .subscribe_to_entity(project_id)?
2670                .set_entity(&self.git_store, &cx.to_async()),
2671        ]);
2672
2673        self.buffer_store.update(cx, |buffer_store, cx| {
2674            buffer_store.shared(project_id, self.collab_client.clone().into(), cx)
2675        });
2676        self.worktree_store.update(cx, |worktree_store, cx| {
2677            worktree_store.shared(project_id, self.collab_client.clone().into(), cx);
2678        });
2679        self.lsp_store.update(cx, |lsp_store, cx| {
2680            lsp_store.shared(project_id, self.collab_client.clone().into(), cx)
2681        });
2682        self.breakpoint_store.update(cx, |breakpoint_store, _| {
2683            breakpoint_store.shared(project_id, self.collab_client.clone().into())
2684        });
2685        self.dap_store.update(cx, |dap_store, cx| {
2686            dap_store.shared(project_id, self.collab_client.clone().into(), cx);
2687        });
2688        self.task_store.update(cx, |task_store, cx| {
2689            task_store.shared(project_id, self.collab_client.clone().into(), cx);
2690        });
2691        self.settings_observer.update(cx, |settings_observer, cx| {
2692            settings_observer.shared(project_id, self.collab_client.clone().into(), cx)
2693        });
2694        self.git_store.update(cx, |git_store, cx| {
2695            git_store.shared(project_id, self.collab_client.clone().into(), cx)
2696        });
2697
2698        self.client_state = ProjectClientState::Shared {
2699            remote_id: project_id,
2700        };
2701
2702        cx.emit(Event::RemoteIdChanged(Some(project_id)));
2703        Ok(())
2704    }
2705
2706    pub fn reshared(
2707        &mut self,
2708        message: proto::ResharedProject,
2709        cx: &mut Context<Self>,
2710    ) -> Result<()> {
2711        self.buffer_store
2712            .update(cx, |buffer_store, _| buffer_store.forget_shared_buffers());
2713        self.set_collaborators_from_proto(message.collaborators, cx)?;
2714
2715        self.worktree_store.update(cx, |worktree_store, cx| {
2716            worktree_store.send_project_updates(cx);
2717        });
2718        if let Some(remote_id) = self.remote_id() {
2719            self.git_store.update(cx, |git_store, cx| {
2720                git_store.shared(remote_id, self.collab_client.clone().into(), cx)
2721            });
2722        }
2723        cx.emit(Event::Reshared);
2724        Ok(())
2725    }
2726
2727    pub fn rejoined(
2728        &mut self,
2729        message: proto::RejoinedProject,
2730        message_id: u32,
2731        cx: &mut Context<Self>,
2732    ) -> Result<()> {
2733        cx.update_global::<SettingsStore, _>(|store, cx| {
2734            for worktree_metadata in &message.worktrees {
2735                store
2736                    .clear_local_settings(WorktreeId::from_proto(worktree_metadata.id), cx)
2737                    .log_err();
2738            }
2739        });
2740
2741        self.join_project_response_message_id = message_id;
2742        self.set_worktrees_from_proto(message.worktrees, cx)?;
2743        self.set_collaborators_from_proto(message.collaborators, cx)?;
2744
2745        let project = cx.weak_entity();
2746        self.lsp_store.update(cx, |lsp_store, cx| {
2747            lsp_store.set_language_server_statuses_from_proto(
2748                project,
2749                message.language_servers,
2750                message.language_server_capabilities,
2751                cx,
2752            )
2753        });
2754        self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
2755            .unwrap();
2756        cx.emit(Event::Rejoined);
2757        Ok(())
2758    }
2759
2760    #[inline]
2761    pub fn unshare(&mut self, cx: &mut Context<Self>) -> Result<()> {
2762        self.unshare_internal(cx)?;
2763        cx.emit(Event::RemoteIdChanged(None));
2764        Ok(())
2765    }
2766
2767    fn unshare_internal(&mut self, cx: &mut App) -> Result<()> {
2768        anyhow::ensure!(
2769            !self.is_via_collab(),
2770            "attempted to unshare a remote project"
2771        );
2772
2773        if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
2774            self.client_state = ProjectClientState::Local;
2775            self.collaborators.clear();
2776            self.client_subscriptions.clear();
2777            self.worktree_store.update(cx, |store, cx| {
2778                store.unshared(cx);
2779            });
2780            self.buffer_store.update(cx, |buffer_store, cx| {
2781                buffer_store.forget_shared_buffers();
2782                buffer_store.unshared(cx)
2783            });
2784            self.task_store.update(cx, |task_store, cx| {
2785                task_store.unshared(cx);
2786            });
2787            self.breakpoint_store.update(cx, |breakpoint_store, cx| {
2788                breakpoint_store.unshared(cx);
2789            });
2790            self.dap_store.update(cx, |dap_store, cx| {
2791                dap_store.unshared(cx);
2792            });
2793            self.settings_observer.update(cx, |settings_observer, cx| {
2794                settings_observer.unshared(cx);
2795            });
2796            self.git_store.update(cx, |git_store, cx| {
2797                git_store.unshared(cx);
2798            });
2799
2800            self.collab_client
2801                .send(proto::UnshareProject {
2802                    project_id: remote_id,
2803                })
2804                .ok();
2805            Ok(())
2806        } else {
2807            anyhow::bail!("attempted to unshare an unshared project");
2808        }
2809    }
2810
2811    pub fn disconnected_from_host(&mut self, cx: &mut Context<Self>) {
2812        if self.is_disconnected(cx) {
2813            return;
2814        }
2815        self.disconnected_from_host_internal(cx);
2816        cx.emit(Event::DisconnectedFromHost);
2817    }
2818
2819    pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut Context<Self>) {
2820        let new_capability =
2821            if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
2822                Capability::ReadWrite
2823            } else {
2824                Capability::ReadOnly
2825            };
2826        if let ProjectClientState::Collab { capability, .. } = &mut self.client_state {
2827            if *capability == new_capability {
2828                return;
2829            }
2830
2831            *capability = new_capability;
2832            for buffer in self.opened_buffers(cx) {
2833                buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
2834            }
2835        }
2836    }
2837
2838    fn disconnected_from_host_internal(&mut self, cx: &mut App) {
2839        if let ProjectClientState::Collab {
2840            sharing_has_stopped,
2841            ..
2842        } = &mut self.client_state
2843        {
2844            *sharing_has_stopped = true;
2845            self.client_subscriptions.clear();
2846            self.collaborators.clear();
2847            self.worktree_store.update(cx, |store, cx| {
2848                store.disconnected_from_host(cx);
2849            });
2850            self.buffer_store.update(cx, |buffer_store, cx| {
2851                buffer_store.disconnected_from_host(cx)
2852            });
2853            self.lsp_store
2854                .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
2855        }
2856    }
2857
2858    #[inline]
2859    pub fn close(&mut self, cx: &mut Context<Self>) {
2860        cx.emit(Event::Closed);
2861    }
2862
2863    #[inline]
2864    pub fn is_disconnected(&self, cx: &App) -> bool {
2865        match &self.client_state {
2866            ProjectClientState::Collab {
2867                sharing_has_stopped,
2868                ..
2869            } => *sharing_has_stopped,
2870            ProjectClientState::Local if self.is_via_remote_server() => {
2871                self.remote_client_is_disconnected(cx)
2872            }
2873            _ => false,
2874        }
2875    }
2876
2877    #[inline]
2878    fn remote_client_is_disconnected(&self, cx: &App) -> bool {
2879        self.remote_client
2880            .as_ref()
2881            .map(|remote| remote.read(cx).is_disconnected())
2882            .unwrap_or(false)
2883    }
2884
2885    #[inline]
2886    pub fn capability(&self) -> Capability {
2887        match &self.client_state {
2888            ProjectClientState::Collab { capability, .. } => *capability,
2889            ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
2890        }
2891    }
2892
2893    #[inline]
2894    pub fn is_read_only(&self, cx: &App) -> bool {
2895        self.is_disconnected(cx) || !self.capability().editable()
2896    }
2897
2898    #[inline]
2899    pub fn is_local(&self) -> bool {
2900        match &self.client_state {
2901            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2902                self.remote_client.is_none()
2903            }
2904            ProjectClientState::Collab { .. } => false,
2905        }
2906    }
2907
2908    /// Whether this project is a remote server (not counting collab).
2909    #[inline]
2910    pub fn is_via_remote_server(&self) -> bool {
2911        match &self.client_state {
2912            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2913                self.remote_client.is_some()
2914            }
2915            ProjectClientState::Collab { .. } => false,
2916        }
2917    }
2918
2919    /// Whether this project is from collab (not counting remote servers).
2920    #[inline]
2921    pub fn is_via_collab(&self) -> bool {
2922        match &self.client_state {
2923            ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
2924            ProjectClientState::Collab { .. } => true,
2925        }
2926    }
2927
2928    /// `!self.is_local()`
2929    #[inline]
2930    pub fn is_remote(&self) -> bool {
2931        debug_assert_eq!(
2932            !self.is_local(),
2933            self.is_via_collab() || self.is_via_remote_server()
2934        );
2935        !self.is_local()
2936    }
2937
2938    #[inline]
2939    pub fn is_via_wsl_with_host_interop(&self, cx: &App) -> bool {
2940        match &self.client_state {
2941            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2942                matches!(
2943                    &self.remote_client, Some(remote_client)
2944                    if remote_client.read(cx).has_wsl_interop()
2945                )
2946            }
2947            _ => false,
2948        }
2949    }
2950
2951    pub fn disable_worktree_scanner(&mut self, cx: &mut Context<Self>) {
2952        self.worktree_store.update(cx, |worktree_store, _cx| {
2953            worktree_store.disable_scanner();
2954        });
2955    }
2956
2957    #[inline]
2958    pub fn create_buffer(
2959        &mut self,
2960        language: Option<Arc<Language>>,
2961        project_searchable: bool,
2962        cx: &mut Context<Self>,
2963    ) -> Task<Result<Entity<Buffer>>> {
2964        self.buffer_store.update(cx, |buffer_store, cx| {
2965            buffer_store.create_buffer(language, project_searchable, cx)
2966        })
2967    }
2968
2969    #[inline]
2970    pub fn create_local_buffer(
2971        &mut self,
2972        text: &str,
2973        language: Option<Arc<Language>>,
2974        project_searchable: bool,
2975        cx: &mut Context<Self>,
2976    ) -> Entity<Buffer> {
2977        if self.is_remote() {
2978            panic!("called create_local_buffer on a remote project")
2979        }
2980        self.buffer_store.update(cx, |buffer_store, cx| {
2981            buffer_store.create_local_buffer(text, language, project_searchable, cx)
2982        })
2983    }
2984
2985    pub fn open_path(
2986        &mut self,
2987        path: ProjectPath,
2988        cx: &mut Context<Self>,
2989    ) -> Task<Result<(Option<ProjectEntryId>, Entity<Buffer>)>> {
2990        let task = self.open_buffer(path, cx);
2991        cx.spawn(async move |_project, cx| {
2992            let buffer = task.await?;
2993            let project_entry_id = buffer.read_with(cx, |buffer, _cx| {
2994                File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id())
2995            });
2996
2997            Ok((project_entry_id, buffer))
2998        })
2999    }
3000
3001    pub fn open_local_buffer(
3002        &mut self,
3003        abs_path: impl AsRef<Path>,
3004        cx: &mut Context<Self>,
3005    ) -> Task<Result<Entity<Buffer>>> {
3006        let worktree_task = self.find_or_create_worktree(abs_path.as_ref(), false, cx);
3007        cx.spawn(async move |this, cx| {
3008            let (worktree, relative_path) = worktree_task.await?;
3009            this.update(cx, |this, cx| {
3010                this.open_buffer((worktree.read(cx).id(), relative_path), cx)
3011            })?
3012            .await
3013        })
3014    }
3015
3016    #[cfg(feature = "test-support")]
3017    pub fn open_local_buffer_with_lsp(
3018        &mut self,
3019        abs_path: impl AsRef<Path>,
3020        cx: &mut Context<Self>,
3021    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
3022        if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
3023            self.open_buffer_with_lsp((worktree.read(cx).id(), relative_path), cx)
3024        } else {
3025            Task::ready(Err(anyhow!("no such path")))
3026        }
3027    }
3028
3029    pub fn download_file(
3030        &mut self,
3031        worktree_id: WorktreeId,
3032        path: Arc<RelPath>,
3033        destination_path: PathBuf,
3034        cx: &mut Context<Self>,
3035    ) -> Task<Result<()>> {
3036        log::debug!(
3037            "download_file called: worktree_id={:?}, path={:?}, destination={:?}",
3038            worktree_id,
3039            path,
3040            destination_path
3041        );
3042
3043        let Some(remote_client) = &self.remote_client else {
3044            log::error!("download_file: not a remote project");
3045            return Task::ready(Err(anyhow!("not a remote project")));
3046        };
3047
3048        let proto_client = remote_client.read(cx).proto_client();
3049        // For SSH remote projects, use REMOTE_SERVER_PROJECT_ID instead of remote_id()
3050        // because SSH projects have client_state: Local but still need to communicate with remote server
3051        let project_id = self.remote_id().unwrap_or(REMOTE_SERVER_PROJECT_ID);
3052        let downloading_files = self.downloading_files.clone();
3053        let path_str = path.to_proto();
3054
3055        static NEXT_FILE_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
3056        let file_id = NEXT_FILE_ID.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
3057
3058        // Register BEFORE sending request to avoid race condition
3059        let key = (worktree_id, path_str.clone());
3060        log::debug!(
3061            "download_file: pre-registering download with key={:?}, file_id={}",
3062            key,
3063            file_id
3064        );
3065        downloading_files.lock().insert(
3066            key,
3067            DownloadingFile {
3068                destination_path: destination_path,
3069                chunks: Vec::new(),
3070                total_size: 0,
3071                file_id: Some(file_id),
3072            },
3073        );
3074        log::debug!(
3075            "download_file: sending DownloadFileByPath request, path_str={}",
3076            path_str
3077        );
3078
3079        cx.spawn(async move |_this, _cx| {
3080            log::debug!("download_file: sending request with file_id={}...", file_id);
3081            let response = proto_client
3082                .request(proto::DownloadFileByPath {
3083                    project_id,
3084                    worktree_id: worktree_id.to_proto(),
3085                    path: path_str.clone(),
3086                    file_id,
3087                })
3088                .await?;
3089
3090            log::debug!("download_file: got response, file_id={}", response.file_id);
3091            // The file_id is set from the State message, we just confirm the request succeeded
3092            Ok(())
3093        })
3094    }
3095
3096    #[ztracing::instrument(skip_all)]
3097    pub fn open_buffer(
3098        &mut self,
3099        path: impl Into<ProjectPath>,
3100        cx: &mut App,
3101    ) -> Task<Result<Entity<Buffer>>> {
3102        if self.is_disconnected(cx) {
3103            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
3104        }
3105
3106        self.buffer_store.update(cx, |buffer_store, cx| {
3107            buffer_store.open_buffer(path.into(), cx)
3108        })
3109    }
3110
3111    #[cfg(feature = "test-support")]
3112    pub fn open_buffer_with_lsp(
3113        &mut self,
3114        path: impl Into<ProjectPath>,
3115        cx: &mut Context<Self>,
3116    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
3117        let buffer = self.open_buffer(path, cx);
3118        cx.spawn(async move |this, cx| {
3119            let buffer = buffer.await?;
3120            let handle = this.update(cx, |project, cx| {
3121                project.register_buffer_with_language_servers(&buffer, cx)
3122            })?;
3123            Ok((buffer, handle))
3124        })
3125    }
3126
3127    pub fn register_buffer_with_language_servers(
3128        &self,
3129        buffer: &Entity<Buffer>,
3130        cx: &mut App,
3131    ) -> OpenLspBufferHandle {
3132        self.lsp_store.update(cx, |lsp_store, cx| {
3133            lsp_store.register_buffer_with_language_servers(buffer, HashSet::default(), false, cx)
3134        })
3135    }
3136
3137    pub fn open_unstaged_diff(
3138        &mut self,
3139        buffer: Entity<Buffer>,
3140        cx: &mut Context<Self>,
3141    ) -> Task<Result<Entity<BufferDiff>>> {
3142        if self.is_disconnected(cx) {
3143            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
3144        }
3145        self.git_store
3146            .update(cx, |git_store, cx| git_store.open_unstaged_diff(buffer, cx))
3147    }
3148
3149    #[ztracing::instrument(skip_all)]
3150    pub fn open_uncommitted_diff(
3151        &mut self,
3152        buffer: Entity<Buffer>,
3153        cx: &mut Context<Self>,
3154    ) -> Task<Result<Entity<BufferDiff>>> {
3155        if self.is_disconnected(cx) {
3156            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
3157        }
3158        self.git_store.update(cx, |git_store, cx| {
3159            git_store.open_uncommitted_diff(buffer, cx)
3160        })
3161    }
3162
3163    pub fn open_buffer_by_id(
3164        &mut self,
3165        id: BufferId,
3166        cx: &mut Context<Self>,
3167    ) -> Task<Result<Entity<Buffer>>> {
3168        if let Some(buffer) = self.buffer_for_id(id, cx) {
3169            Task::ready(Ok(buffer))
3170        } else if self.is_local() || self.is_via_remote_server() {
3171            Task::ready(Err(anyhow!("buffer {id} does not exist")))
3172        } else if let Some(project_id) = self.remote_id() {
3173            let request = self.collab_client.request(proto::OpenBufferById {
3174                project_id,
3175                id: id.into(),
3176            });
3177            cx.spawn(async move |project, cx| {
3178                let buffer_id = BufferId::new(request.await?.buffer_id)?;
3179                project
3180                    .update(cx, |project, cx| {
3181                        project.buffer_store.update(cx, |buffer_store, cx| {
3182                            buffer_store.wait_for_remote_buffer(buffer_id, cx)
3183                        })
3184                    })?
3185                    .await
3186            })
3187        } else {
3188            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
3189        }
3190    }
3191
3192    pub fn save_buffers(
3193        &self,
3194        buffers: HashSet<Entity<Buffer>>,
3195        cx: &mut Context<Self>,
3196    ) -> Task<Result<()>> {
3197        cx.spawn(async move |this, cx| {
3198            let save_tasks = buffers.into_iter().filter_map(|buffer| {
3199                this.update(cx, |this, cx| this.save_buffer(buffer, cx))
3200                    .ok()
3201            });
3202            try_join_all(save_tasks).await?;
3203            Ok(())
3204        })
3205    }
3206
3207    pub fn save_buffer(&self, buffer: Entity<Buffer>, cx: &mut Context<Self>) -> Task<Result<()>> {
3208        self.buffer_store
3209            .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
3210    }
3211
3212    pub fn save_buffer_as(
3213        &mut self,
3214        buffer: Entity<Buffer>,
3215        path: ProjectPath,
3216        cx: &mut Context<Self>,
3217    ) -> Task<Result<()>> {
3218        self.buffer_store.update(cx, |buffer_store, cx| {
3219            buffer_store.save_buffer_as(buffer.clone(), path, cx)
3220        })
3221    }
3222
3223    pub fn get_open_buffer(&self, path: &ProjectPath, cx: &App) -> Option<Entity<Buffer>> {
3224        self.buffer_store.read(cx).get_by_path(path)
3225    }
3226
3227    fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
3228        {
3229            let mut remotely_created_models = self.remotely_created_models.lock();
3230            if remotely_created_models.retain_count > 0 {
3231                remotely_created_models.buffers.push(buffer.clone())
3232            }
3233        }
3234
3235        self.request_buffer_diff_recalculation(buffer, cx);
3236
3237        cx.subscribe(buffer, |this, buffer, event, cx| {
3238            this.on_buffer_event(buffer, event, cx);
3239        })
3240        .detach();
3241
3242        Ok(())
3243    }
3244
3245    pub fn open_image(
3246        &mut self,
3247        path: impl Into<ProjectPath>,
3248        cx: &mut Context<Self>,
3249    ) -> Task<Result<Entity<ImageItem>>> {
3250        if self.is_disconnected(cx) {
3251            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
3252        }
3253
3254        let open_image_task = self.image_store.update(cx, |image_store, cx| {
3255            image_store.open_image(path.into(), cx)
3256        });
3257
3258        let weak_project = cx.entity().downgrade();
3259        cx.spawn(async move |_, cx| {
3260            let image_item = open_image_task.await?;
3261
3262            // Check if metadata already exists (e.g., for remote images)
3263            let needs_metadata =
3264                cx.read_entity(&image_item, |item, _| item.image_metadata.is_none());
3265
3266            if needs_metadata {
3267                let project = weak_project.upgrade().context("Project dropped")?;
3268                let metadata =
3269                    ImageItem::load_image_metadata(image_item.clone(), project, cx).await?;
3270                image_item.update(cx, |image_item, cx| {
3271                    image_item.image_metadata = Some(metadata);
3272                    cx.emit(ImageItemEvent::MetadataUpdated);
3273                });
3274            }
3275
3276            Ok(image_item)
3277        })
3278    }
3279
3280    async fn send_buffer_ordered_messages(
3281        project: WeakEntity<Self>,
3282        rx: UnboundedReceiver<BufferOrderedMessage>,
3283        cx: &mut AsyncApp,
3284    ) -> Result<()> {
3285        const MAX_BATCH_SIZE: usize = 128;
3286
3287        let mut operations_by_buffer_id = HashMap::default();
3288        async fn flush_operations(
3289            this: &WeakEntity<Project>,
3290            operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
3291            needs_resync_with_host: &mut bool,
3292            is_local: bool,
3293            cx: &mut AsyncApp,
3294        ) -> Result<()> {
3295            for (buffer_id, operations) in operations_by_buffer_id.drain() {
3296                let request = this.read_with(cx, |this, _| {
3297                    let project_id = this.remote_id()?;
3298                    Some(this.collab_client.request(proto::UpdateBuffer {
3299                        buffer_id: buffer_id.into(),
3300                        project_id,
3301                        operations,
3302                    }))
3303                })?;
3304                if let Some(request) = request
3305                    && request.await.is_err()
3306                    && !is_local
3307                {
3308                    *needs_resync_with_host = true;
3309                    break;
3310                }
3311            }
3312            Ok(())
3313        }
3314
3315        let mut needs_resync_with_host = false;
3316        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
3317
3318        while let Some(changes) = changes.next().await {
3319            let is_local = project.read_with(cx, |this, _| this.is_local())?;
3320
3321            for change in changes {
3322                match change {
3323                    BufferOrderedMessage::Operation {
3324                        buffer_id,
3325                        operation,
3326                    } => {
3327                        if needs_resync_with_host {
3328                            continue;
3329                        }
3330
3331                        operations_by_buffer_id
3332                            .entry(buffer_id)
3333                            .or_insert(Vec::new())
3334                            .push(operation);
3335                    }
3336
3337                    BufferOrderedMessage::Resync => {
3338                        operations_by_buffer_id.clear();
3339                        if project
3340                            .update(cx, |this, cx| this.synchronize_remote_buffers(cx))?
3341                            .await
3342                            .is_ok()
3343                        {
3344                            needs_resync_with_host = false;
3345                        }
3346                    }
3347
3348                    BufferOrderedMessage::LanguageServerUpdate {
3349                        language_server_id,
3350                        message,
3351                        name,
3352                    } => {
3353                        flush_operations(
3354                            &project,
3355                            &mut operations_by_buffer_id,
3356                            &mut needs_resync_with_host,
3357                            is_local,
3358                            cx,
3359                        )
3360                        .await?;
3361
3362                        project.read_with(cx, |project, _| {
3363                            if let Some(project_id) = project.remote_id() {
3364                                project
3365                                    .collab_client
3366                                    .send(proto::UpdateLanguageServer {
3367                                        project_id,
3368                                        server_name: name.map(|name| String::from(name.0)),
3369                                        language_server_id: language_server_id.to_proto(),
3370                                        variant: Some(message),
3371                                    })
3372                                    .log_err();
3373                            }
3374                        })?;
3375                    }
3376                }
3377            }
3378
3379            flush_operations(
3380                &project,
3381                &mut operations_by_buffer_id,
3382                &mut needs_resync_with_host,
3383                is_local,
3384                cx,
3385            )
3386            .await?;
3387        }
3388
3389        Ok(())
3390    }
3391
3392    fn on_buffer_store_event(
3393        &mut self,
3394        _: Entity<BufferStore>,
3395        event: &BufferStoreEvent,
3396        cx: &mut Context<Self>,
3397    ) {
3398        match event {
3399            BufferStoreEvent::BufferAdded(buffer) => {
3400                self.register_buffer(buffer, cx).log_err();
3401            }
3402            BufferStoreEvent::BufferDropped(buffer_id) => {
3403                if let Some(ref remote_client) = self.remote_client {
3404                    remote_client
3405                        .read(cx)
3406                        .proto_client()
3407                        .send(proto::CloseBuffer {
3408                            project_id: 0,
3409                            buffer_id: buffer_id.to_proto(),
3410                        })
3411                        .log_err();
3412                }
3413            }
3414            _ => {}
3415        }
3416    }
3417
3418    fn on_image_store_event(
3419        &mut self,
3420        _: Entity<ImageStore>,
3421        event: &ImageStoreEvent,
3422        cx: &mut Context<Self>,
3423    ) {
3424        match event {
3425            ImageStoreEvent::ImageAdded(image) => {
3426                cx.subscribe(image, |this, image, event, cx| {
3427                    this.on_image_event(image, event, cx);
3428                })
3429                .detach();
3430            }
3431        }
3432    }
3433
3434    fn on_dap_store_event(
3435        &mut self,
3436        _: Entity<DapStore>,
3437        event: &DapStoreEvent,
3438        cx: &mut Context<Self>,
3439    ) {
3440        if let DapStoreEvent::Notification(message) = event {
3441            cx.emit(Event::Toast {
3442                notification_id: "dap".into(),
3443                message: message.clone(),
3444                link: None,
3445            });
3446        }
3447    }
3448
3449    fn on_lsp_store_event(
3450        &mut self,
3451        _: Entity<LspStore>,
3452        event: &LspStoreEvent,
3453        cx: &mut Context<Self>,
3454    ) {
3455        match event {
3456            LspStoreEvent::DiagnosticsUpdated { server_id, paths } => {
3457                cx.emit(Event::DiagnosticsUpdated {
3458                    paths: paths.clone(),
3459                    language_server_id: *server_id,
3460                })
3461            }
3462            LspStoreEvent::LanguageServerAdded(server_id, name, worktree_id) => cx.emit(
3463                Event::LanguageServerAdded(*server_id, name.clone(), *worktree_id),
3464            ),
3465            LspStoreEvent::LanguageServerRemoved(server_id) => {
3466                cx.emit(Event::LanguageServerRemoved(*server_id))
3467            }
3468            LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
3469                Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
3470            ),
3471            LspStoreEvent::LanguageDetected {
3472                buffer,
3473                new_language,
3474            } => {
3475                let Some(_) = new_language else {
3476                    cx.emit(Event::LanguageNotFound(buffer.clone()));
3477                    return;
3478                };
3479            }
3480            LspStoreEvent::RefreshInlayHints {
3481                server_id,
3482                request_id,
3483            } => cx.emit(Event::RefreshInlayHints {
3484                server_id: *server_id,
3485                request_id: *request_id,
3486            }),
3487            LspStoreEvent::RefreshSemanticTokens {
3488                server_id,
3489                request_id,
3490            } => cx.emit(Event::RefreshSemanticTokens {
3491                server_id: *server_id,
3492                request_id: *request_id,
3493            }),
3494            LspStoreEvent::RefreshCodeLens => cx.emit(Event::RefreshCodeLens),
3495            LspStoreEvent::LanguageServerPrompt(prompt) => {
3496                cx.emit(Event::LanguageServerPrompt(prompt.clone()))
3497            }
3498            LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
3499                cx.emit(Event::DiskBasedDiagnosticsStarted {
3500                    language_server_id: *language_server_id,
3501                });
3502            }
3503            LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
3504                cx.emit(Event::DiskBasedDiagnosticsFinished {
3505                    language_server_id: *language_server_id,
3506                });
3507            }
3508            LspStoreEvent::LanguageServerUpdate {
3509                language_server_id,
3510                name,
3511                message,
3512            } => {
3513                if self.is_local() {
3514                    self.enqueue_buffer_ordered_message(
3515                        BufferOrderedMessage::LanguageServerUpdate {
3516                            language_server_id: *language_server_id,
3517                            message: message.clone(),
3518                            name: name.clone(),
3519                        },
3520                    )
3521                    .ok();
3522                }
3523
3524                match message {
3525                    proto::update_language_server::Variant::MetadataUpdated(update) => {
3526                        self.lsp_store.update(cx, |lsp_store, _| {
3527                            if let Some(capabilities) = update
3528                                .capabilities
3529                                .as_ref()
3530                                .and_then(|capabilities| serde_json::from_str(capabilities).ok())
3531                            {
3532                                lsp_store
3533                                    .lsp_server_capabilities
3534                                    .insert(*language_server_id, capabilities);
3535                            }
3536
3537                            if let Some(language_server_status) = lsp_store
3538                                .language_server_statuses
3539                                .get_mut(language_server_id)
3540                            {
3541                                if let Some(binary) = &update.binary {
3542                                    language_server_status.binary = Some(LanguageServerBinary {
3543                                        path: PathBuf::from(&binary.path),
3544                                        arguments: binary
3545                                            .arguments
3546                                            .iter()
3547                                            .map(OsString::from)
3548                                            .collect(),
3549                                        env: None,
3550                                    });
3551                                }
3552
3553                                language_server_status.configuration = update
3554                                    .configuration
3555                                    .as_ref()
3556                                    .and_then(|config_str| serde_json::from_str(config_str).ok());
3557
3558                                language_server_status.workspace_folders = update
3559                                    .workspace_folders
3560                                    .iter()
3561                                    .filter_map(|uri_str| lsp::Uri::from_str(uri_str).ok())
3562                                    .collect();
3563                            }
3564                        });
3565                    }
3566                    proto::update_language_server::Variant::RegisteredForBuffer(update) => {
3567                        if let Some(buffer_id) = BufferId::new(update.buffer_id).ok() {
3568                            cx.emit(Event::LanguageServerBufferRegistered {
3569                                buffer_id,
3570                                server_id: *language_server_id,
3571                                buffer_abs_path: PathBuf::from(&update.buffer_abs_path),
3572                                name: name.clone(),
3573                            });
3574                        }
3575                    }
3576                    _ => (),
3577                }
3578            }
3579            LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
3580                notification_id: "lsp".into(),
3581                message: message.clone(),
3582                link: None,
3583            }),
3584            LspStoreEvent::SnippetEdit {
3585                buffer_id,
3586                edits,
3587                most_recent_edit,
3588            } => {
3589                if most_recent_edit.replica_id == self.replica_id() {
3590                    cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
3591                }
3592            }
3593            LspStoreEvent::WorkspaceEditApplied(transaction) => {
3594                cx.emit(Event::WorkspaceEditApplied(transaction.clone()))
3595            }
3596        }
3597    }
3598
3599    fn on_remote_client_event(
3600        &mut self,
3601        _: Entity<RemoteClient>,
3602        event: &remote::RemoteClientEvent,
3603        cx: &mut Context<Self>,
3604    ) {
3605        match event {
3606            &remote::RemoteClientEvent::Disconnected { server_not_running } => {
3607                self.worktree_store.update(cx, |store, cx| {
3608                    store.disconnected_from_host(cx);
3609                });
3610                self.buffer_store.update(cx, |buffer_store, cx| {
3611                    buffer_store.disconnected_from_host(cx)
3612                });
3613                self.lsp_store.update(cx, |lsp_store, _cx| {
3614                    lsp_store.disconnected_from_ssh_remote()
3615                });
3616                cx.emit(Event::DisconnectedFromRemote { server_not_running });
3617            }
3618        }
3619    }
3620
3621    fn on_settings_observer_event(
3622        &mut self,
3623        _: Entity<SettingsObserver>,
3624        event: &SettingsObserverEvent,
3625        cx: &mut Context<Self>,
3626    ) {
3627        match event {
3628            SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
3629                Err(InvalidSettingsError::LocalSettings { message, path }) => {
3630                    let message = format!("Failed to set local settings in {path:?}:\n{message}");
3631                    cx.emit(Event::Toast {
3632                        notification_id: format!("local-settings-{path:?}").into(),
3633                        link: None,
3634                        message,
3635                    });
3636                }
3637                Ok(path) => cx.emit(Event::HideToast {
3638                    notification_id: format!("local-settings-{path:?}").into(),
3639                }),
3640                Err(_) => {}
3641            },
3642            SettingsObserverEvent::LocalTasksUpdated(result) => match result {
3643                Err(InvalidSettingsError::Tasks { message, path }) => {
3644                    let message = format!("Failed to set local tasks in {path:?}:\n{message}");
3645                    cx.emit(Event::Toast {
3646                        notification_id: format!("local-tasks-{path:?}").into(),
3647                        link: Some(ToastLink {
3648                            label: "Open Tasks Documentation",
3649                            url: "https://zed.dev/docs/tasks",
3650                        }),
3651                        message,
3652                    });
3653                }
3654                Ok(path) => cx.emit(Event::HideToast {
3655                    notification_id: format!("local-tasks-{path:?}").into(),
3656                }),
3657                Err(_) => {}
3658            },
3659            SettingsObserverEvent::LocalDebugScenariosUpdated(result) => match result {
3660                Err(InvalidSettingsError::Debug { message, path }) => {
3661                    let message =
3662                        format!("Failed to set local debug scenarios in {path:?}:\n{message}");
3663                    cx.emit(Event::Toast {
3664                        notification_id: format!("local-debug-scenarios-{path:?}").into(),
3665                        link: None,
3666                        message,
3667                    });
3668                }
3669                Ok(path) => cx.emit(Event::HideToast {
3670                    notification_id: format!("local-debug-scenarios-{path:?}").into(),
3671                }),
3672                Err(_) => {}
3673            },
3674        }
3675    }
3676
3677    fn on_worktree_store_event(
3678        &mut self,
3679        _: Entity<WorktreeStore>,
3680        event: &WorktreeStoreEvent,
3681        cx: &mut Context<Self>,
3682    ) {
3683        match event {
3684            WorktreeStoreEvent::WorktreeAdded(worktree) => {
3685                self.on_worktree_added(worktree, cx);
3686                cx.emit(Event::WorktreeAdded(worktree.read(cx).id()));
3687            }
3688            WorktreeStoreEvent::WorktreeRemoved(_, id) => {
3689                cx.emit(Event::WorktreeRemoved(*id));
3690            }
3691            WorktreeStoreEvent::WorktreeReleased(_, id) => {
3692                self.on_worktree_released(*id, cx);
3693            }
3694            WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
3695            WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
3696            WorktreeStoreEvent::WorktreeUpdatedEntries(worktree_id, changes) => {
3697                self.client()
3698                    .telemetry()
3699                    .report_discovered_project_type_events(*worktree_id, changes);
3700                cx.emit(Event::WorktreeUpdatedEntries(*worktree_id, changes.clone()))
3701            }
3702            WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, id) => {
3703                cx.emit(Event::DeletedEntry(*worktree_id, *id))
3704            }
3705            // Listen to the GitStore instead.
3706            WorktreeStoreEvent::WorktreeUpdatedGitRepositories(_, _) => {}
3707            WorktreeStoreEvent::WorktreeUpdatedRootRepoCommonDir(worktree_id) => {
3708                cx.emit(Event::WorktreeUpdatedRootRepoCommonDir(*worktree_id));
3709            }
3710        }
3711    }
3712
3713    fn on_worktree_added(&mut self, worktree: &Entity<Worktree>, _: &mut Context<Self>) {
3714        let mut remotely_created_models = self.remotely_created_models.lock();
3715        if remotely_created_models.retain_count > 0 {
3716            remotely_created_models.worktrees.push(worktree.clone())
3717        }
3718    }
3719
3720    fn on_worktree_released(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
3721        if let Some(remote) = &self.remote_client {
3722            remote
3723                .read(cx)
3724                .proto_client()
3725                .send(proto::RemoveWorktree {
3726                    worktree_id: id_to_remove.to_proto(),
3727                })
3728                .log_err();
3729        }
3730    }
3731
3732    fn on_buffer_event(
3733        &mut self,
3734        buffer: Entity<Buffer>,
3735        event: &BufferEvent,
3736        cx: &mut Context<Self>,
3737    ) -> Option<()> {
3738        if matches!(event, BufferEvent::Edited { .. } | BufferEvent::Reloaded) {
3739            self.request_buffer_diff_recalculation(&buffer, cx);
3740        }
3741
3742        if matches!(event, BufferEvent::Edited { .. }) {
3743            cx.emit(Event::BufferEdited);
3744        }
3745
3746        let buffer_id = buffer.read(cx).remote_id();
3747        match event {
3748            BufferEvent::ReloadNeeded => {
3749                if !self.is_via_collab() {
3750                    self.reload_buffers([buffer.clone()].into_iter().collect(), true, cx)
3751                        .detach_and_log_err(cx);
3752                }
3753            }
3754            BufferEvent::Operation {
3755                operation,
3756                is_local: true,
3757            } => {
3758                let operation = language::proto::serialize_operation(operation);
3759
3760                if let Some(remote) = &self.remote_client {
3761                    remote
3762                        .read(cx)
3763                        .proto_client()
3764                        .send(proto::UpdateBuffer {
3765                            project_id: 0,
3766                            buffer_id: buffer_id.to_proto(),
3767                            operations: vec![operation.clone()],
3768                        })
3769                        .ok();
3770                }
3771
3772                self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
3773                    buffer_id,
3774                    operation,
3775                })
3776                .ok();
3777            }
3778
3779            _ => {}
3780        }
3781
3782        None
3783    }
3784
3785    fn on_image_event(
3786        &mut self,
3787        image: Entity<ImageItem>,
3788        event: &ImageItemEvent,
3789        cx: &mut Context<Self>,
3790    ) -> Option<()> {
3791        // TODO: handle image events from remote
3792        if let ImageItemEvent::ReloadNeeded = event
3793            && !self.is_via_collab()
3794        {
3795            self.reload_images([image].into_iter().collect(), cx)
3796                .detach_and_log_err(cx);
3797        }
3798
3799        None
3800    }
3801
3802    fn request_buffer_diff_recalculation(
3803        &mut self,
3804        buffer: &Entity<Buffer>,
3805        cx: &mut Context<Self>,
3806    ) {
3807        self.buffers_needing_diff.insert(buffer.downgrade());
3808        let first_insertion = self.buffers_needing_diff.len() == 1;
3809        let settings = ProjectSettings::get_global(cx);
3810        let delay = settings.git.gutter_debounce;
3811
3812        if delay == 0 {
3813            if first_insertion {
3814                let this = cx.weak_entity();
3815                cx.defer(move |cx| {
3816                    if let Some(this) = this.upgrade() {
3817                        this.update(cx, |this, cx| {
3818                            this.recalculate_buffer_diffs(cx).detach();
3819                        });
3820                    }
3821                });
3822            }
3823            return;
3824        }
3825
3826        const MIN_DELAY: u64 = 50;
3827        let delay = delay.max(MIN_DELAY);
3828        let duration = Duration::from_millis(delay);
3829
3830        self.git_diff_debouncer
3831            .fire_new(duration, cx, move |this, cx| {
3832                this.recalculate_buffer_diffs(cx)
3833            });
3834    }
3835
3836    fn recalculate_buffer_diffs(&mut self, cx: &mut Context<Self>) -> Task<()> {
3837        cx.spawn(async move |this, cx| {
3838            loop {
3839                let task = this
3840                    .update(cx, |this, cx| {
3841                        let buffers = this
3842                            .buffers_needing_diff
3843                            .drain()
3844                            .filter_map(|buffer| buffer.upgrade())
3845                            .collect::<Vec<_>>();
3846                        if buffers.is_empty() {
3847                            None
3848                        } else {
3849                            Some(this.git_store.update(cx, |git_store, cx| {
3850                                git_store.recalculate_buffer_diffs(buffers, cx)
3851                            }))
3852                        }
3853                    })
3854                    .ok()
3855                    .flatten();
3856
3857                if let Some(task) = task {
3858                    task.await;
3859                } else {
3860                    break;
3861                }
3862            }
3863        })
3864    }
3865
3866    pub fn set_language_for_buffer(
3867        &mut self,
3868        buffer: &Entity<Buffer>,
3869        new_language: Arc<Language>,
3870        cx: &mut Context<Self>,
3871    ) {
3872        self.lsp_store.update(cx, |lsp_store, cx| {
3873            lsp_store.set_language_for_buffer(buffer, new_language, cx)
3874        })
3875    }
3876
3877    pub fn restart_language_servers_for_buffers(
3878        &mut self,
3879        buffers: Vec<Entity<Buffer>>,
3880        only_restart_servers: HashSet<LanguageServerSelector>,
3881        cx: &mut Context<Self>,
3882    ) {
3883        self.lsp_store.update(cx, |lsp_store, cx| {
3884            lsp_store.restart_language_servers_for_buffers(buffers, only_restart_servers, cx)
3885        })
3886    }
3887
3888    pub fn stop_language_servers_for_buffers(
3889        &mut self,
3890        buffers: Vec<Entity<Buffer>>,
3891        also_restart_servers: HashSet<LanguageServerSelector>,
3892        cx: &mut Context<Self>,
3893    ) {
3894        self.lsp_store
3895            .update(cx, |lsp_store, cx| {
3896                lsp_store.stop_language_servers_for_buffers(buffers, also_restart_servers, cx)
3897            })
3898            .detach_and_log_err(cx);
3899    }
3900
3901    pub fn cancel_language_server_work_for_buffers(
3902        &mut self,
3903        buffers: impl IntoIterator<Item = Entity<Buffer>>,
3904        cx: &mut Context<Self>,
3905    ) {
3906        self.lsp_store.update(cx, |lsp_store, cx| {
3907            lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
3908        })
3909    }
3910
3911    pub fn cancel_language_server_work(
3912        &mut self,
3913        server_id: LanguageServerId,
3914        token_to_cancel: Option<ProgressToken>,
3915        cx: &mut Context<Self>,
3916    ) {
3917        self.lsp_store.update(cx, |lsp_store, cx| {
3918            lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
3919        })
3920    }
3921
3922    fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
3923        self.buffer_ordered_messages_tx
3924            .unbounded_send(message)
3925            .map_err(|e| anyhow!(e))
3926    }
3927
3928    pub fn available_toolchains(
3929        &self,
3930        path: ProjectPath,
3931        language_name: LanguageName,
3932        cx: &App,
3933    ) -> Task<Option<Toolchains>> {
3934        if let Some(toolchain_store) = self.toolchain_store.as_ref().map(Entity::downgrade) {
3935            cx.spawn(async move |cx| {
3936                toolchain_store
3937                    .update(cx, |this, cx| this.list_toolchains(path, language_name, cx))
3938                    .ok()?
3939                    .await
3940            })
3941        } else {
3942            Task::ready(None)
3943        }
3944    }
3945
3946    pub async fn toolchain_metadata(
3947        languages: Arc<LanguageRegistry>,
3948        language_name: LanguageName,
3949    ) -> Option<ToolchainMetadata> {
3950        languages
3951            .language_for_name(language_name.as_ref())
3952            .await
3953            .ok()?
3954            .toolchain_lister()
3955            .map(|lister| lister.meta())
3956    }
3957
3958    pub fn add_toolchain(
3959        &self,
3960        toolchain: Toolchain,
3961        scope: ToolchainScope,
3962        cx: &mut Context<Self>,
3963    ) {
3964        maybe!({
3965            self.toolchain_store.as_ref()?.update(cx, |this, cx| {
3966                this.add_toolchain(toolchain, scope, cx);
3967            });
3968            Some(())
3969        });
3970    }
3971
3972    pub fn remove_toolchain(
3973        &self,
3974        toolchain: Toolchain,
3975        scope: ToolchainScope,
3976        cx: &mut Context<Self>,
3977    ) {
3978        maybe!({
3979            self.toolchain_store.as_ref()?.update(cx, |this, cx| {
3980                this.remove_toolchain(toolchain, scope, cx);
3981            });
3982            Some(())
3983        });
3984    }
3985
3986    pub fn user_toolchains(
3987        &self,
3988        cx: &App,
3989    ) -> Option<BTreeMap<ToolchainScope, IndexSet<Toolchain>>> {
3990        Some(self.toolchain_store.as_ref()?.read(cx).user_toolchains())
3991    }
3992
3993    pub fn resolve_toolchain(
3994        &self,
3995        path: PathBuf,
3996        language_name: LanguageName,
3997        cx: &App,
3998    ) -> Task<Result<Toolchain>> {
3999        if let Some(toolchain_store) = self.toolchain_store.as_ref().map(Entity::downgrade) {
4000            cx.spawn(async move |cx| {
4001                toolchain_store
4002                    .update(cx, |this, cx| {
4003                        this.resolve_toolchain(path, language_name, cx)
4004                    })?
4005                    .await
4006            })
4007        } else {
4008            Task::ready(Err(anyhow!("This project does not support toolchains")))
4009        }
4010    }
4011
4012    pub fn toolchain_store(&self) -> Option<Entity<ToolchainStore>> {
4013        self.toolchain_store.clone()
4014    }
4015    pub fn activate_toolchain(
4016        &self,
4017        path: ProjectPath,
4018        toolchain: Toolchain,
4019        cx: &mut App,
4020    ) -> Task<Option<()>> {
4021        let Some(toolchain_store) = self.toolchain_store.clone() else {
4022            return Task::ready(None);
4023        };
4024        toolchain_store.update(cx, |this, cx| this.activate_toolchain(path, toolchain, cx))
4025    }
4026    pub fn active_toolchain(
4027        &self,
4028        path: ProjectPath,
4029        language_name: LanguageName,
4030        cx: &App,
4031    ) -> Task<Option<Toolchain>> {
4032        let Some(toolchain_store) = self.toolchain_store.clone() else {
4033            return Task::ready(None);
4034        };
4035        toolchain_store
4036            .read(cx)
4037            .active_toolchain(path, language_name, cx)
4038    }
4039    pub fn language_server_statuses<'a>(
4040        &'a self,
4041        cx: &'a App,
4042    ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
4043        self.lsp_store.read(cx).language_server_statuses()
4044    }
4045
4046    pub fn last_formatting_failure<'a>(&self, cx: &'a App) -> Option<&'a str> {
4047        self.lsp_store.read(cx).last_formatting_failure()
4048    }
4049
4050    pub fn reset_last_formatting_failure(&self, cx: &mut App) {
4051        self.lsp_store
4052            .update(cx, |store, _| store.reset_last_formatting_failure());
4053    }
4054
4055    pub fn reload_buffers(
4056        &self,
4057        buffers: HashSet<Entity<Buffer>>,
4058        push_to_history: bool,
4059        cx: &mut Context<Self>,
4060    ) -> Task<Result<ProjectTransaction>> {
4061        self.buffer_store.update(cx, |buffer_store, cx| {
4062            buffer_store.reload_buffers(buffers, push_to_history, cx)
4063        })
4064    }
4065
4066    pub fn reload_images(
4067        &self,
4068        images: HashSet<Entity<ImageItem>>,
4069        cx: &mut Context<Self>,
4070    ) -> Task<Result<()>> {
4071        self.image_store
4072            .update(cx, |image_store, cx| image_store.reload_images(images, cx))
4073    }
4074
4075    pub fn format(
4076        &mut self,
4077        buffers: HashSet<Entity<Buffer>>,
4078        target: LspFormatTarget,
4079        push_to_history: bool,
4080        trigger: lsp_store::FormatTrigger,
4081        cx: &mut Context<Project>,
4082    ) -> Task<anyhow::Result<ProjectTransaction>> {
4083        self.lsp_store.update(cx, |lsp_store, cx| {
4084            lsp_store.format(buffers, target, push_to_history, trigger, cx)
4085        })
4086    }
4087
4088    pub fn definitions<T: ToPointUtf16>(
4089        &mut self,
4090        buffer: &Entity<Buffer>,
4091        position: T,
4092        cx: &mut Context<Self>,
4093    ) -> Task<Result<Option<Vec<LocationLink>>>> {
4094        let position = position.to_point_utf16(buffer.read(cx));
4095        let guard = self.retain_remotely_created_models(cx);
4096        let task = self.lsp_store.update(cx, |lsp_store, cx| {
4097            lsp_store.definitions(buffer, position, cx)
4098        });
4099        cx.background_spawn(async move {
4100            let result = task.await;
4101            drop(guard);
4102            result
4103        })
4104    }
4105
4106    pub fn declarations<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.declarations(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 type_definitions<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.type_definitions(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 implementations<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.implementations(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 references<T: ToPointUtf16>(
4161        &mut self,
4162        buffer: &Entity<Buffer>,
4163        position: T,
4164        cx: &mut Context<Self>,
4165    ) -> Task<Result<Option<Vec<Location>>>> {
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.references(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 document_highlights<T: ToPointUtf16>(
4179        &mut self,
4180        buffer: &Entity<Buffer>,
4181        position: T,
4182        cx: &mut Context<Self>,
4183    ) -> Task<Result<Vec<DocumentHighlight>>> {
4184        let position = position.to_point_utf16(buffer.read(cx));
4185        self.request_lsp(
4186            buffer.clone(),
4187            LanguageServerToQuery::FirstCapable,
4188            GetDocumentHighlights { position },
4189            cx,
4190        )
4191    }
4192
4193    pub fn document_symbols(
4194        &mut self,
4195        buffer: &Entity<Buffer>,
4196        cx: &mut Context<Self>,
4197    ) -> Task<Result<Vec<DocumentSymbol>>> {
4198        self.request_lsp(
4199            buffer.clone(),
4200            LanguageServerToQuery::FirstCapable,
4201            GetDocumentSymbols,
4202            cx,
4203        )
4204    }
4205
4206    pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
4207        self.lsp_store
4208            .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
4209    }
4210
4211    pub fn open_buffer_for_symbol(
4212        &mut self,
4213        symbol: &Symbol,
4214        cx: &mut Context<Self>,
4215    ) -> Task<Result<Entity<Buffer>>> {
4216        self.lsp_store.update(cx, |lsp_store, cx| {
4217            lsp_store.open_buffer_for_symbol(symbol, cx)
4218        })
4219    }
4220
4221    pub fn open_server_settings(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
4222        let guard = self.retain_remotely_created_models(cx);
4223        let Some(remote) = self.remote_client.as_ref() else {
4224            return Task::ready(Err(anyhow!("not an ssh project")));
4225        };
4226
4227        let proto_client = remote.read(cx).proto_client();
4228
4229        cx.spawn(async move |project, cx| {
4230            let buffer = proto_client
4231                .request(proto::OpenServerSettings {
4232                    project_id: REMOTE_SERVER_PROJECT_ID,
4233                })
4234                .await?;
4235
4236            let buffer = project
4237                .update(cx, |project, cx| {
4238                    project.buffer_store.update(cx, |buffer_store, cx| {
4239                        anyhow::Ok(
4240                            buffer_store
4241                                .wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx),
4242                        )
4243                    })
4244                })??
4245                .await;
4246
4247            drop(guard);
4248            buffer
4249        })
4250    }
4251
4252    pub fn open_local_buffer_via_lsp(
4253        &mut self,
4254        abs_path: lsp::Uri,
4255        language_server_id: LanguageServerId,
4256        cx: &mut Context<Self>,
4257    ) -> Task<Result<Entity<Buffer>>> {
4258        self.lsp_store.update(cx, |lsp_store, cx| {
4259            lsp_store.open_local_buffer_via_lsp(abs_path, language_server_id, cx)
4260        })
4261    }
4262
4263    pub fn hover<T: ToPointUtf16>(
4264        &self,
4265        buffer: &Entity<Buffer>,
4266        position: T,
4267        cx: &mut Context<Self>,
4268    ) -> Task<Option<Vec<Hover>>> {
4269        let position = position.to_point_utf16(buffer.read(cx));
4270        self.lsp_store
4271            .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
4272    }
4273
4274    pub fn linked_edits(
4275        &self,
4276        buffer: &Entity<Buffer>,
4277        position: Anchor,
4278        cx: &mut Context<Self>,
4279    ) -> Task<Result<Vec<Range<Anchor>>>> {
4280        self.lsp_store.update(cx, |lsp_store, cx| {
4281            lsp_store.linked_edits(buffer, position, cx)
4282        })
4283    }
4284
4285    pub fn completions<T: ToOffset + ToPointUtf16>(
4286        &self,
4287        buffer: &Entity<Buffer>,
4288        position: T,
4289        context: CompletionContext,
4290        cx: &mut Context<Self>,
4291    ) -> Task<Result<Vec<CompletionResponse>>> {
4292        let position = position.to_point_utf16(buffer.read(cx));
4293        self.lsp_store.update(cx, |lsp_store, cx| {
4294            lsp_store.completions(buffer, position, context, cx)
4295        })
4296    }
4297
4298    pub fn code_actions<T: Clone + ToOffset>(
4299        &mut self,
4300        buffer_handle: &Entity<Buffer>,
4301        range: Range<T>,
4302        kinds: Option<Vec<CodeActionKind>>,
4303        cx: &mut Context<Self>,
4304    ) -> Task<Result<Option<Vec<CodeAction>>>> {
4305        let buffer = buffer_handle.read(cx);
4306        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
4307        self.lsp_store.update(cx, |lsp_store, cx| {
4308            lsp_store.code_actions(buffer_handle, range, kinds, cx)
4309        })
4310    }
4311
4312    pub fn code_lens_actions<T: Clone + ToOffset>(
4313        &mut self,
4314        buffer: &Entity<Buffer>,
4315        range: Range<T>,
4316        cx: &mut Context<Self>,
4317    ) -> Task<Result<Option<Vec<CodeAction>>>> {
4318        let snapshot = buffer.read(cx).snapshot();
4319        let range = range.to_point(&snapshot);
4320        let range_start = snapshot.anchor_before(range.start);
4321        let range_end = if range.start == range.end {
4322            range_start
4323        } else {
4324            snapshot.anchor_after(range.end)
4325        };
4326        let range = range_start..range_end;
4327        let code_lens_actions = self
4328            .lsp_store
4329            .update(cx, |lsp_store, cx| lsp_store.code_lens_actions(buffer, cx));
4330
4331        cx.background_spawn(async move {
4332            let mut code_lens_actions = code_lens_actions
4333                .await
4334                .map_err(|e| anyhow!("code lens fetch failed: {e:#}"))?;
4335            if let Some(code_lens_actions) = &mut code_lens_actions {
4336                code_lens_actions.retain(|code_lens_action| {
4337                    range
4338                        .start
4339                        .cmp(&code_lens_action.range.start, &snapshot)
4340                        .is_ge()
4341                        && range
4342                            .end
4343                            .cmp(&code_lens_action.range.end, &snapshot)
4344                            .is_le()
4345                });
4346            }
4347            Ok(code_lens_actions)
4348        })
4349    }
4350
4351    pub fn apply_code_action(
4352        &self,
4353        buffer_handle: Entity<Buffer>,
4354        action: CodeAction,
4355        push_to_history: bool,
4356        cx: &mut Context<Self>,
4357    ) -> Task<Result<ProjectTransaction>> {
4358        self.lsp_store.update(cx, |lsp_store, cx| {
4359            lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
4360        })
4361    }
4362
4363    pub fn apply_code_action_kind(
4364        &self,
4365        buffers: HashSet<Entity<Buffer>>,
4366        kind: CodeActionKind,
4367        push_to_history: bool,
4368        cx: &mut Context<Self>,
4369    ) -> Task<Result<ProjectTransaction>> {
4370        self.lsp_store.update(cx, |lsp_store, cx| {
4371            lsp_store.apply_code_action_kind(buffers, kind, push_to_history, cx)
4372        })
4373    }
4374
4375    pub fn prepare_rename<T: ToPointUtf16>(
4376        &mut self,
4377        buffer: Entity<Buffer>,
4378        position: T,
4379        cx: &mut Context<Self>,
4380    ) -> Task<Result<PrepareRenameResponse>> {
4381        let position = position.to_point_utf16(buffer.read(cx));
4382        self.request_lsp(
4383            buffer,
4384            LanguageServerToQuery::FirstCapable,
4385            PrepareRename { position },
4386            cx,
4387        )
4388    }
4389
4390    pub fn perform_rename<T: ToPointUtf16>(
4391        &mut self,
4392        buffer: Entity<Buffer>,
4393        position: T,
4394        new_name: String,
4395        cx: &mut Context<Self>,
4396    ) -> Task<Result<ProjectTransaction>> {
4397        let push_to_history = true;
4398        let position = position.to_point_utf16(buffer.read(cx));
4399        self.request_lsp(
4400            buffer,
4401            LanguageServerToQuery::FirstCapable,
4402            PerformRename {
4403                position,
4404                new_name,
4405                push_to_history,
4406            },
4407            cx,
4408        )
4409    }
4410
4411    pub fn on_type_format<T: ToPointUtf16>(
4412        &mut self,
4413        buffer: Entity<Buffer>,
4414        position: T,
4415        trigger: String,
4416        push_to_history: bool,
4417        cx: &mut Context<Self>,
4418    ) -> Task<Result<Option<Transaction>>> {
4419        self.lsp_store.update(cx, |lsp_store, cx| {
4420            lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
4421        })
4422    }
4423
4424    pub fn inline_values(
4425        &mut self,
4426        session: Entity<Session>,
4427        active_stack_frame: ActiveStackFrame,
4428        buffer_handle: Entity<Buffer>,
4429        range: Range<text::Anchor>,
4430        cx: &mut Context<Self>,
4431    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
4432        let snapshot = buffer_handle.read(cx).snapshot();
4433
4434        let captures =
4435            snapshot.debug_variables_query(Anchor::min_for_buffer(snapshot.remote_id())..range.end);
4436
4437        let row = snapshot
4438            .summary_for_anchor::<text::PointUtf16>(&range.end)
4439            .row as usize;
4440
4441        let inline_value_locations = provide_inline_values(captures, &snapshot, row);
4442
4443        let stack_frame_id = active_stack_frame.stack_frame_id;
4444        cx.spawn(async move |this, cx| {
4445            this.update(cx, |project, cx| {
4446                project.dap_store().update(cx, |dap_store, cx| {
4447                    dap_store.resolve_inline_value_locations(
4448                        session,
4449                        stack_frame_id,
4450                        buffer_handle,
4451                        inline_value_locations,
4452                        cx,
4453                    )
4454                })
4455            })?
4456            .await
4457        })
4458    }
4459
4460    fn search_impl(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> SearchResultsHandle {
4461        let client: Option<(AnyProtoClient, _)> = if let Some(ssh_client) = &self.remote_client {
4462            Some((ssh_client.read(cx).proto_client(), 0))
4463        } else if let Some(remote_id) = self.remote_id() {
4464            self.is_local()
4465                .not()
4466                .then(|| (self.collab_client.clone().into(), remote_id))
4467        } else {
4468            None
4469        };
4470        let searcher = if query.is_opened_only() {
4471            project_search::Search::open_buffers_only(
4472                self.buffer_store.clone(),
4473                self.worktree_store.clone(),
4474                project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4475            )
4476        } else {
4477            match client {
4478                Some((client, remote_id)) => project_search::Search::remote(
4479                    self.buffer_store.clone(),
4480                    self.worktree_store.clone(),
4481                    project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4482                    (client, remote_id, self.remotely_created_models.clone()),
4483                ),
4484                None => project_search::Search::local(
4485                    self.fs.clone(),
4486                    self.buffer_store.clone(),
4487                    self.worktree_store.clone(),
4488                    project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4489                    cx,
4490                ),
4491            }
4492        };
4493        searcher.into_handle(query, cx)
4494    }
4495
4496    pub fn search(
4497        &mut self,
4498        query: SearchQuery,
4499        cx: &mut Context<Self>,
4500    ) -> SearchResults<SearchResult> {
4501        self.search_impl(query, cx).results(cx)
4502    }
4503
4504    pub fn request_lsp<R: LspCommand>(
4505        &mut self,
4506        buffer_handle: Entity<Buffer>,
4507        server: LanguageServerToQuery,
4508        request: R,
4509        cx: &mut Context<Self>,
4510    ) -> Task<Result<R::Response>>
4511    where
4512        <R::LspRequest as lsp::request::Request>::Result: Send,
4513        <R::LspRequest as lsp::request::Request>::Params: Send,
4514    {
4515        let guard = self.retain_remotely_created_models(cx);
4516        let task = self.lsp_store.update(cx, |lsp_store, cx| {
4517            lsp_store.request_lsp(buffer_handle, server, request, cx)
4518        });
4519        cx.background_spawn(async move {
4520            let result = task.await;
4521            drop(guard);
4522            result
4523        })
4524    }
4525
4526    /// Move a worktree to a new position in the worktree order.
4527    ///
4528    /// The worktree will moved to the opposite side of the destination worktree.
4529    ///
4530    /// # Example
4531    ///
4532    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
4533    /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
4534    ///
4535    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
4536    /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
4537    ///
4538    /// # Errors
4539    ///
4540    /// An error will be returned if the worktree or destination worktree are not found.
4541    pub fn move_worktree(
4542        &mut self,
4543        source: WorktreeId,
4544        destination: WorktreeId,
4545        cx: &mut Context<Self>,
4546    ) -> Result<()> {
4547        self.worktree_store.update(cx, |worktree_store, cx| {
4548            worktree_store.move_worktree(source, destination, cx)
4549        })
4550    }
4551
4552    /// 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.
4553    pub fn try_windows_path_to_wsl(
4554        &self,
4555        abs_path: &Path,
4556        cx: &App,
4557    ) -> impl Future<Output = Result<PathBuf>> + use<> {
4558        let fut = if cfg!(windows)
4559            && let (
4560                ProjectClientState::Local | ProjectClientState::Shared { .. },
4561                Some(remote_client),
4562            ) = (&self.client_state, &self.remote_client)
4563            && let RemoteConnectionOptions::Wsl(wsl) = remote_client.read(cx).connection_options()
4564        {
4565            Either::Left(wsl.abs_windows_path_to_wsl_path(abs_path))
4566        } else {
4567            Either::Right(abs_path.to_owned())
4568        };
4569        async move {
4570            match fut {
4571                Either::Left(fut) => fut.await.map(Into::into),
4572                Either::Right(path) => Ok(path),
4573            }
4574        }
4575    }
4576
4577    pub fn find_or_create_worktree(
4578        &mut self,
4579        abs_path: impl AsRef<Path>,
4580        visible: bool,
4581        cx: &mut Context<Self>,
4582    ) -> Task<Result<(Entity<Worktree>, Arc<RelPath>)>> {
4583        self.worktree_store.update(cx, |worktree_store, cx| {
4584            worktree_store.find_or_create_worktree(abs_path, visible, cx)
4585        })
4586    }
4587
4588    pub fn find_worktree(
4589        &self,
4590        abs_path: &Path,
4591        cx: &App,
4592    ) -> Option<(Entity<Worktree>, Arc<RelPath>)> {
4593        self.worktree_store.read(cx).find_worktree(abs_path, cx)
4594    }
4595
4596    pub fn is_shared(&self) -> bool {
4597        match &self.client_state {
4598            ProjectClientState::Shared { .. } => true,
4599            ProjectClientState::Local => false,
4600            ProjectClientState::Collab { .. } => true,
4601        }
4602    }
4603
4604    /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
4605    pub fn resolve_path_in_buffer(
4606        &self,
4607        path: &str,
4608        buffer: &Entity<Buffer>,
4609        cx: &mut Context<Self>,
4610    ) -> Task<Option<ResolvedPath>> {
4611        if util::paths::is_absolute(path, self.path_style(cx)) || path.starts_with("~") {
4612            self.resolve_abs_path(path, cx)
4613        } else {
4614            self.resolve_path_in_worktrees(path, buffer, cx)
4615        }
4616    }
4617
4618    pub fn resolve_abs_file_path(
4619        &self,
4620        path: &str,
4621        cx: &mut Context<Self>,
4622    ) -> Task<Option<ResolvedPath>> {
4623        let resolve_task = self.resolve_abs_path(path, cx);
4624        cx.background_spawn(async move {
4625            let resolved_path = resolve_task.await;
4626            resolved_path.filter(|path| path.is_file())
4627        })
4628    }
4629
4630    pub fn resolve_abs_path(&self, path: &str, cx: &App) -> Task<Option<ResolvedPath>> {
4631        if self.is_local() {
4632            let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
4633            let fs = self.fs.clone();
4634            cx.background_spawn(async move {
4635                let metadata = fs.metadata(&expanded).await.ok().flatten();
4636
4637                metadata.map(|metadata| ResolvedPath::AbsPath {
4638                    path: expanded.to_string_lossy().into_owned(),
4639                    is_dir: metadata.is_dir,
4640                })
4641            })
4642        } else if let Some(ssh_client) = self.remote_client.as_ref() {
4643            let request = ssh_client
4644                .read(cx)
4645                .proto_client()
4646                .request(proto::GetPathMetadata {
4647                    project_id: REMOTE_SERVER_PROJECT_ID,
4648                    path: path.into(),
4649                });
4650            cx.background_spawn(async move {
4651                let response = request.await.log_err()?;
4652                if response.exists {
4653                    Some(ResolvedPath::AbsPath {
4654                        path: response.path,
4655                        is_dir: response.is_dir,
4656                    })
4657                } else {
4658                    None
4659                }
4660            })
4661        } else {
4662            Task::ready(None)
4663        }
4664    }
4665
4666    fn resolve_path_in_worktrees(
4667        &self,
4668        path: &str,
4669        buffer: &Entity<Buffer>,
4670        cx: &mut Context<Self>,
4671    ) -> Task<Option<ResolvedPath>> {
4672        let mut candidates = vec![];
4673        let path_style = self.path_style(cx);
4674        if let Ok(path) = RelPath::new(path.as_ref(), path_style) {
4675            candidates.push(path.into_arc());
4676        }
4677
4678        if let Some(file) = buffer.read(cx).file()
4679            && let Some(dir) = file.path().parent()
4680        {
4681            if let Some(joined) = path_style.join(&*dir.display(path_style), path)
4682                && let Some(joined) = RelPath::new(joined.as_ref(), path_style).ok()
4683            {
4684                candidates.push(joined.into_arc());
4685            }
4686        }
4687
4688        let buffer_worktree_id = buffer.read(cx).file().map(|file| file.worktree_id(cx));
4689        let worktrees_with_ids: Vec<_> = self
4690            .worktrees(cx)
4691            .map(|worktree| {
4692                let id = worktree.read(cx).id();
4693                (worktree, id)
4694            })
4695            .collect();
4696
4697        cx.spawn(async move |_, cx| {
4698            if let Some(buffer_worktree_id) = buffer_worktree_id
4699                && let Some((worktree, _)) = worktrees_with_ids
4700                    .iter()
4701                    .find(|(_, id)| *id == buffer_worktree_id)
4702            {
4703                for candidate in candidates.iter() {
4704                    if let Some(path) = Self::resolve_path_in_worktree(worktree, candidate, cx) {
4705                        return Some(path);
4706                    }
4707                }
4708            }
4709            for (worktree, id) in worktrees_with_ids {
4710                if Some(id) == buffer_worktree_id {
4711                    continue;
4712                }
4713                for candidate in candidates.iter() {
4714                    if let Some(path) = Self::resolve_path_in_worktree(&worktree, candidate, cx) {
4715                        return Some(path);
4716                    }
4717                }
4718            }
4719            None
4720        })
4721    }
4722
4723    fn resolve_path_in_worktree(
4724        worktree: &Entity<Worktree>,
4725        path: &RelPath,
4726        cx: &mut AsyncApp,
4727    ) -> Option<ResolvedPath> {
4728        worktree.read_with(cx, |worktree, _| {
4729            worktree.entry_for_path(path).map(|entry| {
4730                let project_path = ProjectPath {
4731                    worktree_id: worktree.id(),
4732                    path: entry.path.clone(),
4733                };
4734                ResolvedPath::ProjectPath {
4735                    project_path,
4736                    is_dir: entry.is_dir(),
4737                }
4738            })
4739        })
4740    }
4741
4742    pub fn list_directory(
4743        &self,
4744        query: String,
4745        cx: &mut Context<Self>,
4746    ) -> Task<Result<Vec<DirectoryItem>>> {
4747        if self.is_local() {
4748            DirectoryLister::Local(cx.entity(), self.fs.clone()).list_directory(query, cx)
4749        } else if let Some(session) = self.remote_client.as_ref() {
4750            let request = proto::ListRemoteDirectory {
4751                dev_server_id: REMOTE_SERVER_PROJECT_ID,
4752                path: query,
4753                config: Some(proto::ListRemoteDirectoryConfig { is_dir: true }),
4754            };
4755
4756            let response = session.read(cx).proto_client().request(request);
4757            cx.background_spawn(async move {
4758                let proto::ListRemoteDirectoryResponse {
4759                    entries,
4760                    entry_info,
4761                } = response.await?;
4762                Ok(entries
4763                    .into_iter()
4764                    .zip(entry_info)
4765                    .map(|(entry, info)| DirectoryItem {
4766                        path: PathBuf::from(entry),
4767                        is_dir: info.is_dir,
4768                    })
4769                    .collect())
4770            })
4771        } else {
4772            Task::ready(Err(anyhow!("cannot list directory in remote project")))
4773        }
4774    }
4775
4776    pub fn create_worktree(
4777        &mut self,
4778        abs_path: impl AsRef<Path>,
4779        visible: bool,
4780        cx: &mut Context<Self>,
4781    ) -> Task<Result<Entity<Worktree>>> {
4782        self.worktree_store.update(cx, |worktree_store, cx| {
4783            worktree_store.create_worktree(abs_path, visible, cx)
4784        })
4785    }
4786
4787    /// Returns a task that resolves when the given worktree's `Entity` is
4788    /// fully dropped (all strong references released), not merely when
4789    /// `remove_worktree` is called. `remove_worktree` drops the store's
4790    /// reference and emits `WorktreeRemoved`, but other code may still
4791    /// hold a strong handle — the worktree isn't safe to delete from
4792    /// disk until every handle is gone.
4793    ///
4794    /// We use `observe_release` on the specific entity rather than
4795    /// listening for `WorktreeReleased` events because it's simpler at
4796    /// the call site (one awaitable task, no subscription / channel /
4797    /// ID filtering).
4798    pub fn wait_for_worktree_release(
4799        &mut self,
4800        worktree_id: WorktreeId,
4801        cx: &mut Context<Self>,
4802    ) -> Task<Result<()>> {
4803        let Some(worktree) = self.worktree_for_id(worktree_id, cx) else {
4804            return Task::ready(Ok(()));
4805        };
4806
4807        let (released_tx, released_rx) = futures::channel::oneshot::channel();
4808        let released_tx = std::sync::Arc::new(Mutex::new(Some(released_tx)));
4809        let release_subscription =
4810            cx.observe_release(&worktree, move |_project, _released_worktree, _cx| {
4811                if let Some(released_tx) = released_tx.lock().take() {
4812                    let _ = released_tx.send(());
4813                }
4814            });
4815
4816        cx.spawn(async move |_project, _cx| {
4817            let _release_subscription = release_subscription;
4818            released_rx
4819                .await
4820                .map_err(|_| anyhow!("worktree release observer dropped before release"))?;
4821            Ok(())
4822        })
4823    }
4824
4825    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
4826        self.worktree_store.update(cx, |worktree_store, cx| {
4827            worktree_store.remove_worktree(id_to_remove, cx);
4828        });
4829    }
4830
4831    pub fn remove_worktree_for_main_worktree_path(
4832        &mut self,
4833        path: impl AsRef<Path>,
4834        cx: &mut Context<Self>,
4835    ) {
4836        let path = path.as_ref();
4837        self.worktree_store.update(cx, |worktree_store, cx| {
4838            if let Some(worktree) = worktree_store.worktree_for_main_worktree_path(path, cx) {
4839                worktree_store.remove_worktree(worktree.read(cx).id(), cx);
4840            }
4841        });
4842    }
4843
4844    fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
4845        self.worktree_store.update(cx, |worktree_store, cx| {
4846            worktree_store.add(worktree, cx);
4847        });
4848    }
4849
4850    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
4851        let new_active_entry = entry.and_then(|project_path| {
4852            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4853            let entry = worktree.read(cx).entry_for_path(&project_path.path)?;
4854            Some(entry.id)
4855        });
4856        if new_active_entry != self.active_entry {
4857            self.active_entry = new_active_entry;
4858            self.lsp_store.update(cx, |lsp_store, _| {
4859                lsp_store.set_active_entry(new_active_entry);
4860            });
4861            cx.emit(Event::ActiveEntryChanged(new_active_entry));
4862        }
4863    }
4864
4865    pub fn language_servers_running_disk_based_diagnostics<'a>(
4866        &'a self,
4867        cx: &'a App,
4868    ) -> impl Iterator<Item = LanguageServerId> + 'a {
4869        self.lsp_store
4870            .read(cx)
4871            .language_servers_running_disk_based_diagnostics()
4872    }
4873
4874    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
4875        self.lsp_store
4876            .read(cx)
4877            .diagnostic_summary(include_ignored, cx)
4878    }
4879
4880    /// Returns a summary of the diagnostics for the provided project path only.
4881    pub fn diagnostic_summary_for_path(&self, path: &ProjectPath, cx: &App) -> DiagnosticSummary {
4882        self.lsp_store
4883            .read(cx)
4884            .diagnostic_summary_for_path(path, cx)
4885    }
4886
4887    pub fn diagnostic_summaries<'a>(
4888        &'a self,
4889        include_ignored: bool,
4890        cx: &'a App,
4891    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4892        self.lsp_store
4893            .read(cx)
4894            .diagnostic_summaries(include_ignored, cx)
4895    }
4896
4897    pub fn active_entry(&self) -> Option<ProjectEntryId> {
4898        self.active_entry
4899    }
4900
4901    pub fn entry_for_path<'a>(&'a self, path: &ProjectPath, cx: &'a App) -> Option<&'a Entry> {
4902        self.worktree_store.read(cx).entry_for_path(path, cx)
4903    }
4904
4905    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
4906        let worktree = self.worktree_for_entry(entry_id, cx)?;
4907        let worktree = worktree.read(cx);
4908        let worktree_id = worktree.id();
4909        let path = worktree.entry_for_id(entry_id)?.path.clone();
4910        Some(ProjectPath { worktree_id, path })
4911    }
4912
4913    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4914        Some(
4915            self.worktree_for_id(project_path.worktree_id, cx)?
4916                .read(cx)
4917                .absolutize(&project_path.path),
4918        )
4919    }
4920
4921    /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
4922    /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
4923    /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
4924    /// the first visible worktree that has an entry for that relative path.
4925    ///
4926    /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
4927    /// root name from paths.
4928    ///
4929    /// # Arguments
4930    ///
4931    /// * `path` - An absolute path, or a full path that starts with a worktree root name, or a
4932    ///   relative path within a visible worktree.
4933    /// * `cx` - A reference to the `AppContext`.
4934    ///
4935    /// # Returns
4936    ///
4937    /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
4938    pub fn find_project_path(&self, path: impl AsRef<Path>, cx: &App) -> Option<ProjectPath> {
4939        let path_style = self.path_style(cx);
4940        let path = path.as_ref();
4941        let worktree_store = self.worktree_store.read(cx);
4942
4943        if is_absolute(&path.to_string_lossy(), path_style) {
4944            for worktree in worktree_store.visible_worktrees(cx) {
4945                let worktree_abs_path = worktree.read(cx).abs_path();
4946
4947                if let Ok(relative_path) = path.strip_prefix(worktree_abs_path)
4948                    && let Ok(path) = RelPath::new(relative_path, path_style)
4949                {
4950                    return Some(ProjectPath {
4951                        worktree_id: worktree.read(cx).id(),
4952                        path: path.into_arc(),
4953                    });
4954                }
4955            }
4956        } else {
4957            for worktree in worktree_store.visible_worktrees(cx) {
4958                let worktree = worktree.read(cx);
4959                if let Ok(rel_path) = RelPath::new(path, path_style) {
4960                    if let Some(entry) = worktree.entry_for_path(&rel_path) {
4961                        return Some(ProjectPath {
4962                            worktree_id: worktree.id(),
4963                            path: entry.path.clone(),
4964                        });
4965                    }
4966                }
4967            }
4968
4969            for worktree in worktree_store.visible_worktrees(cx) {
4970                let worktree_root_name = worktree.read(cx).root_name();
4971                if let Ok(relative_path) = path.strip_prefix(worktree_root_name.as_std_path())
4972                    && let Ok(path) = RelPath::new(relative_path, path_style)
4973                {
4974                    return Some(ProjectPath {
4975                        worktree_id: worktree.read(cx).id(),
4976                        path: path.into_arc(),
4977                    });
4978                }
4979            }
4980        }
4981
4982        None
4983    }
4984
4985    /// If there's only one visible worktree, returns the given worktree-relative path with no prefix.
4986    ///
4987    /// Otherwise, returns the full path for the project path (obtained by prefixing the worktree-relative path with the name of the worktree).
4988    pub fn short_full_path_for_project_path(
4989        &self,
4990        project_path: &ProjectPath,
4991        cx: &App,
4992    ) -> Option<String> {
4993        let path_style = self.path_style(cx);
4994        if self.visible_worktrees(cx).take(2).count() < 2 {
4995            return Some(project_path.path.display(path_style).to_string());
4996        }
4997        self.worktree_for_id(project_path.worktree_id, cx)
4998            .map(|worktree| {
4999                let worktree_name = worktree.read(cx).root_name();
5000                worktree_name
5001                    .join(&project_path.path)
5002                    .display(path_style)
5003                    .to_string()
5004            })
5005    }
5006
5007    pub fn project_path_for_absolute_path(&self, abs_path: &Path, cx: &App) -> Option<ProjectPath> {
5008        self.worktree_store
5009            .read(cx)
5010            .project_path_for_absolute_path(abs_path, cx)
5011    }
5012
5013    pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
5014        Some(
5015            self.worktree_for_id(project_path.worktree_id, cx)?
5016                .read(cx)
5017                .abs_path()
5018                .to_path_buf(),
5019        )
5020    }
5021
5022    pub fn blame_buffer(
5023        &self,
5024        buffer: &Entity<Buffer>,
5025        version: Option<clock::Global>,
5026        cx: &mut App,
5027    ) -> Task<Result<Option<Blame>>> {
5028        self.git_store.update(cx, |git_store, cx| {
5029            git_store.blame_buffer(buffer, version, cx)
5030        })
5031    }
5032
5033    pub fn get_permalink_to_line(
5034        &self,
5035        buffer: &Entity<Buffer>,
5036        selection: Range<u32>,
5037        cx: &mut App,
5038    ) -> Task<Result<url::Url>> {
5039        self.git_store.update(cx, |git_store, cx| {
5040            git_store.get_permalink_to_line(buffer, selection, cx)
5041        })
5042    }
5043
5044    // RPC message handlers
5045
5046    async fn handle_unshare_project(
5047        this: Entity<Self>,
5048        _: TypedEnvelope<proto::UnshareProject>,
5049        mut cx: AsyncApp,
5050    ) -> Result<()> {
5051        this.update(&mut cx, |this, cx| {
5052            if this.is_local() || this.is_via_remote_server() {
5053                this.unshare(cx)?;
5054            } else {
5055                this.disconnected_from_host(cx);
5056            }
5057            Ok(())
5058        })
5059    }
5060
5061    async fn handle_add_collaborator(
5062        this: Entity<Self>,
5063        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
5064        mut cx: AsyncApp,
5065    ) -> Result<()> {
5066        let collaborator = envelope
5067            .payload
5068            .collaborator
5069            .take()
5070            .context("empty collaborator")?;
5071
5072        let collaborator = Collaborator::from_proto(collaborator)?;
5073        this.update(&mut cx, |this, cx| {
5074            this.buffer_store.update(cx, |buffer_store, _| {
5075                buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
5076            });
5077            this.breakpoint_store.read(cx).broadcast();
5078            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
5079            this.collaborators
5080                .insert(collaborator.peer_id, collaborator);
5081        });
5082
5083        Ok(())
5084    }
5085
5086    async fn handle_update_project_collaborator(
5087        this: Entity<Self>,
5088        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
5089        mut cx: AsyncApp,
5090    ) -> Result<()> {
5091        let old_peer_id = envelope
5092            .payload
5093            .old_peer_id
5094            .context("missing old peer id")?;
5095        let new_peer_id = envelope
5096            .payload
5097            .new_peer_id
5098            .context("missing new peer id")?;
5099        this.update(&mut cx, |this, cx| {
5100            let collaborator = this
5101                .collaborators
5102                .remove(&old_peer_id)
5103                .context("received UpdateProjectCollaborator for unknown peer")?;
5104            let is_host = collaborator.is_host;
5105            this.collaborators.insert(new_peer_id, collaborator);
5106
5107            log::info!("peer {} became {}", old_peer_id, new_peer_id,);
5108            this.buffer_store.update(cx, |buffer_store, _| {
5109                buffer_store.update_peer_id(&old_peer_id, new_peer_id)
5110            });
5111
5112            if is_host {
5113                this.buffer_store
5114                    .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
5115                this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
5116                    .unwrap();
5117                cx.emit(Event::HostReshared);
5118            }
5119
5120            cx.emit(Event::CollaboratorUpdated {
5121                old_peer_id,
5122                new_peer_id,
5123            });
5124            Ok(())
5125        })
5126    }
5127
5128    async fn handle_remove_collaborator(
5129        this: Entity<Self>,
5130        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
5131        mut cx: AsyncApp,
5132    ) -> Result<()> {
5133        this.update(&mut cx, |this, cx| {
5134            let peer_id = envelope.payload.peer_id.context("invalid peer id")?;
5135            let replica_id = this
5136                .collaborators
5137                .remove(&peer_id)
5138                .with_context(|| format!("unknown peer {peer_id:?}"))?
5139                .replica_id;
5140            this.buffer_store.update(cx, |buffer_store, cx| {
5141                buffer_store.forget_shared_buffers_for(&peer_id);
5142                for buffer in buffer_store.buffers() {
5143                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
5144                }
5145            });
5146            this.git_store.update(cx, |git_store, _| {
5147                git_store.forget_shared_diffs_for(&peer_id);
5148            });
5149
5150            cx.emit(Event::CollaboratorLeft(peer_id));
5151            Ok(())
5152        })
5153    }
5154
5155    async fn handle_update_project(
5156        this: Entity<Self>,
5157        envelope: TypedEnvelope<proto::UpdateProject>,
5158        mut cx: AsyncApp,
5159    ) -> Result<()> {
5160        this.update(&mut cx, |this, cx| {
5161            // Don't handle messages that were sent before the response to us joining the project
5162            if envelope.message_id > this.join_project_response_message_id {
5163                cx.update_global::<SettingsStore, _>(|store, cx| {
5164                    for worktree_metadata in &envelope.payload.worktrees {
5165                        store
5166                            .clear_local_settings(WorktreeId::from_proto(worktree_metadata.id), cx)
5167                            .log_err();
5168                    }
5169                });
5170
5171                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
5172            }
5173            Ok(())
5174        })
5175    }
5176
5177    async fn handle_toast(
5178        this: Entity<Self>,
5179        envelope: TypedEnvelope<proto::Toast>,
5180        mut cx: AsyncApp,
5181    ) -> Result<()> {
5182        this.update(&mut cx, |_, cx| {
5183            cx.emit(Event::Toast {
5184                notification_id: envelope.payload.notification_id.into(),
5185                message: envelope.payload.message,
5186                link: None,
5187            });
5188            Ok(())
5189        })
5190    }
5191
5192    async fn handle_language_server_prompt_request(
5193        this: Entity<Self>,
5194        envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
5195        mut cx: AsyncApp,
5196    ) -> Result<proto::LanguageServerPromptResponse> {
5197        let (tx, rx) = smol::channel::bounded(1);
5198        let actions: Vec<_> = envelope
5199            .payload
5200            .actions
5201            .into_iter()
5202            .map(|action| MessageActionItem {
5203                title: action,
5204                properties: Default::default(),
5205            })
5206            .collect();
5207        this.update(&mut cx, |_, cx| {
5208            cx.emit(Event::LanguageServerPrompt(
5209                LanguageServerPromptRequest::new(
5210                    proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
5211                    envelope.payload.message,
5212                    actions.clone(),
5213                    envelope.payload.lsp_name,
5214                    tx,
5215                ),
5216            ));
5217
5218            anyhow::Ok(())
5219        })?;
5220
5221        // We drop `this` to avoid holding a reference in this future for too
5222        // long.
5223        // If we keep the reference, we might not drop the `Project` early
5224        // enough when closing a window and it will only get releases on the
5225        // next `flush_effects()` call.
5226        drop(this);
5227
5228        let mut rx = pin!(rx);
5229        let answer = rx.next().await;
5230
5231        Ok(LanguageServerPromptResponse {
5232            action_response: answer.and_then(|answer| {
5233                actions
5234                    .iter()
5235                    .position(|action| *action == answer)
5236                    .map(|index| index as u64)
5237            }),
5238        })
5239    }
5240
5241    async fn handle_hide_toast(
5242        this: Entity<Self>,
5243        envelope: TypedEnvelope<proto::HideToast>,
5244        mut cx: AsyncApp,
5245    ) -> Result<()> {
5246        this.update(&mut cx, |_, cx| {
5247            cx.emit(Event::HideToast {
5248                notification_id: envelope.payload.notification_id.into(),
5249            });
5250            Ok(())
5251        })
5252    }
5253
5254    // Collab sends UpdateWorktree protos as messages
5255    async fn handle_update_worktree(
5256        this: Entity<Self>,
5257        envelope: TypedEnvelope<proto::UpdateWorktree>,
5258        mut cx: AsyncApp,
5259    ) -> Result<()> {
5260        this.update(&mut cx, |project, cx| {
5261            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5262            if let Some(worktree) = project.worktree_for_id(worktree_id, cx) {
5263                worktree.update(cx, |worktree, _| {
5264                    let worktree = worktree.as_remote_mut().unwrap();
5265                    worktree.update_from_remote(envelope.payload);
5266                });
5267            }
5268            Ok(())
5269        })
5270    }
5271
5272    async fn handle_update_buffer_from_remote_server(
5273        this: Entity<Self>,
5274        envelope: TypedEnvelope<proto::UpdateBuffer>,
5275        cx: AsyncApp,
5276    ) -> Result<proto::Ack> {
5277        let buffer_store = this.read_with(&cx, |this, cx| {
5278            if let Some(remote_id) = this.remote_id() {
5279                let mut payload = envelope.payload.clone();
5280                payload.project_id = remote_id;
5281                cx.background_spawn(this.collab_client.request(payload))
5282                    .detach_and_log_err(cx);
5283            }
5284            this.buffer_store.clone()
5285        });
5286        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
5287    }
5288
5289    async fn handle_trust_worktrees(
5290        this: Entity<Self>,
5291        envelope: TypedEnvelope<proto::TrustWorktrees>,
5292        mut cx: AsyncApp,
5293    ) -> Result<proto::Ack> {
5294        if this.read_with(&cx, |project, _| project.is_via_collab()) {
5295            return Ok(proto::Ack {});
5296        }
5297
5298        let trusted_worktrees = cx
5299            .update(|cx| TrustedWorktrees::try_get_global(cx))
5300            .context("missing trusted worktrees")?;
5301        trusted_worktrees.update(&mut cx, |trusted_worktrees, cx| {
5302            trusted_worktrees.trust(
5303                &this.read(cx).worktree_store(),
5304                envelope
5305                    .payload
5306                    .trusted_paths
5307                    .into_iter()
5308                    .filter_map(|proto_path| PathTrust::from_proto(proto_path))
5309                    .collect(),
5310                cx,
5311            );
5312        });
5313        Ok(proto::Ack {})
5314    }
5315
5316    async fn handle_restrict_worktrees(
5317        this: Entity<Self>,
5318        envelope: TypedEnvelope<proto::RestrictWorktrees>,
5319        mut cx: AsyncApp,
5320    ) -> Result<proto::Ack> {
5321        if this.read_with(&cx, |project, _| project.is_via_collab()) {
5322            return Ok(proto::Ack {});
5323        }
5324
5325        let trusted_worktrees = cx
5326            .update(|cx| TrustedWorktrees::try_get_global(cx))
5327            .context("missing trusted worktrees")?;
5328        trusted_worktrees.update(&mut cx, |trusted_worktrees, cx| {
5329            let worktree_store = this.read(cx).worktree_store().downgrade();
5330            let restricted_paths = envelope
5331                .payload
5332                .worktree_ids
5333                .into_iter()
5334                .map(WorktreeId::from_proto)
5335                .map(PathTrust::Worktree)
5336                .collect::<HashSet<_>>();
5337            trusted_worktrees.restrict(worktree_store, restricted_paths, cx);
5338        });
5339        Ok(proto::Ack {})
5340    }
5341
5342    // Goes from host to client.
5343    async fn handle_find_search_candidates_chunk(
5344        this: Entity<Self>,
5345        envelope: TypedEnvelope<proto::FindSearchCandidatesChunk>,
5346        mut cx: AsyncApp,
5347    ) -> Result<proto::Ack> {
5348        let buffer_store = this.read_with(&mut cx, |this, _| this.buffer_store.clone());
5349        BufferStore::handle_find_search_candidates_chunk(buffer_store, envelope, cx).await
5350    }
5351
5352    // Goes from client to host.
5353    async fn handle_find_search_candidates_cancel(
5354        this: Entity<Self>,
5355        envelope: TypedEnvelope<proto::FindSearchCandidatesCancelled>,
5356        mut cx: AsyncApp,
5357    ) -> Result<()> {
5358        let buffer_store = this.read_with(&mut cx, |this, _| this.buffer_store.clone());
5359        BufferStore::handle_find_search_candidates_cancel(buffer_store, envelope, cx).await
5360    }
5361
5362    async fn handle_update_buffer(
5363        this: Entity<Self>,
5364        envelope: TypedEnvelope<proto::UpdateBuffer>,
5365        cx: AsyncApp,
5366    ) -> Result<proto::Ack> {
5367        let buffer_store = this.read_with(&cx, |this, cx| {
5368            if let Some(ssh) = &this.remote_client {
5369                let mut payload = envelope.payload.clone();
5370                payload.project_id = REMOTE_SERVER_PROJECT_ID;
5371                cx.background_spawn(ssh.read(cx).proto_client().request(payload))
5372                    .detach_and_log_err(cx);
5373            }
5374            this.buffer_store.clone()
5375        });
5376        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
5377    }
5378
5379    fn retain_remotely_created_models(
5380        &mut self,
5381        cx: &mut Context<Self>,
5382    ) -> RemotelyCreatedModelGuard {
5383        Self::retain_remotely_created_models_impl(
5384            &self.remotely_created_models,
5385            &self.buffer_store,
5386            &self.worktree_store,
5387            cx,
5388        )
5389    }
5390
5391    fn retain_remotely_created_models_impl(
5392        models: &Arc<Mutex<RemotelyCreatedModels>>,
5393        buffer_store: &Entity<BufferStore>,
5394        worktree_store: &Entity<WorktreeStore>,
5395        cx: &mut App,
5396    ) -> RemotelyCreatedModelGuard {
5397        {
5398            let mut remotely_create_models = models.lock();
5399            if remotely_create_models.retain_count == 0 {
5400                remotely_create_models.buffers = buffer_store.read(cx).buffers().collect();
5401                remotely_create_models.worktrees = worktree_store.read(cx).worktrees().collect();
5402            }
5403            remotely_create_models.retain_count += 1;
5404        }
5405        RemotelyCreatedModelGuard {
5406            remote_models: Arc::downgrade(&models),
5407        }
5408    }
5409
5410    async fn handle_create_buffer_for_peer(
5411        this: Entity<Self>,
5412        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
5413        mut cx: AsyncApp,
5414    ) -> Result<()> {
5415        this.update(&mut cx, |this, cx| {
5416            this.buffer_store.update(cx, |buffer_store, cx| {
5417                buffer_store.handle_create_buffer_for_peer(
5418                    envelope,
5419                    this.replica_id(),
5420                    this.capability(),
5421                    cx,
5422                )
5423            })
5424        })
5425    }
5426
5427    async fn handle_toggle_lsp_logs(
5428        project: Entity<Self>,
5429        envelope: TypedEnvelope<proto::ToggleLspLogs>,
5430        mut cx: AsyncApp,
5431    ) -> Result<()> {
5432        let toggled_log_kind =
5433            match proto::toggle_lsp_logs::LogType::from_i32(envelope.payload.log_type)
5434                .context("invalid log type")?
5435            {
5436                proto::toggle_lsp_logs::LogType::Log => LogKind::Logs,
5437                proto::toggle_lsp_logs::LogType::Trace => LogKind::Trace,
5438                proto::toggle_lsp_logs::LogType::Rpc => LogKind::Rpc,
5439            };
5440        project.update(&mut cx, |_, cx| {
5441            cx.emit(Event::ToggleLspLogs {
5442                server_id: LanguageServerId::from_proto(envelope.payload.server_id),
5443                enabled: envelope.payload.enabled,
5444                toggled_log_kind,
5445            })
5446        });
5447        Ok(())
5448    }
5449
5450    async fn handle_synchronize_buffers(
5451        this: Entity<Self>,
5452        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
5453        mut cx: AsyncApp,
5454    ) -> Result<proto::SynchronizeBuffersResponse> {
5455        let response = this.update(&mut cx, |this, cx| {
5456            let client = this.collab_client.clone();
5457            this.buffer_store.update(cx, |this, cx| {
5458                this.handle_synchronize_buffers(envelope, cx, client)
5459            })
5460        })?;
5461
5462        Ok(response)
5463    }
5464
5465    // Goes from client to host.
5466    async fn handle_search_candidate_buffers(
5467        this: Entity<Self>,
5468        envelope: TypedEnvelope<proto::FindSearchCandidates>,
5469        mut cx: AsyncApp,
5470    ) -> Result<proto::Ack> {
5471        let peer_id = envelope.original_sender_id.unwrap_or(envelope.sender_id);
5472        let message = envelope.payload;
5473        let project_id = message.project_id;
5474        let path_style = this.read_with(&cx, |this, cx| this.path_style(cx));
5475        let query =
5476            SearchQuery::from_proto(message.query.context("missing query field")?, path_style)?;
5477
5478        let handle = message.handle;
5479        let buffer_store = this.read_with(&cx, |this, _| this.buffer_store().clone());
5480        let client = this.read_with(&cx, |this, _| this.client());
5481        let task = cx.spawn(async move |cx| {
5482            let results = this.update(cx, |this, cx| {
5483                this.search_impl(query, cx).matching_buffers(cx)
5484            });
5485            let (batcher, batches) = project_search::AdaptiveBatcher::new(cx.background_executor());
5486            let mut new_matches = Box::pin(results.rx);
5487
5488            let sender_task = cx.background_executor().spawn({
5489                let client = client.clone();
5490                async move {
5491                    let mut batches = std::pin::pin!(batches);
5492                    while let Some(buffer_ids) = batches.next().await {
5493                        client
5494                            .request(proto::FindSearchCandidatesChunk {
5495                                handle,
5496                                peer_id: Some(peer_id),
5497                                project_id,
5498                                variant: Some(
5499                                    proto::find_search_candidates_chunk::Variant::Matches(
5500                                        proto::FindSearchCandidatesMatches { buffer_ids },
5501                                    ),
5502                                ),
5503                            })
5504                            .await?;
5505                    }
5506                    anyhow::Ok(())
5507                }
5508            });
5509
5510            while let Some(buffer) = new_matches.next().await {
5511                let buffer_id = this.update(cx, |this, cx| {
5512                    this.create_buffer_for_peer(&buffer, peer_id, cx).to_proto()
5513                });
5514                batcher.push(buffer_id).await;
5515            }
5516            batcher.flush().await;
5517
5518            sender_task.await?;
5519
5520            let _ = client
5521                .request(proto::FindSearchCandidatesChunk {
5522                    handle,
5523                    peer_id: Some(peer_id),
5524                    project_id,
5525                    variant: Some(proto::find_search_candidates_chunk::Variant::Done(
5526                        proto::FindSearchCandidatesDone {},
5527                    )),
5528                })
5529                .await?;
5530            anyhow::Ok(())
5531        });
5532        buffer_store.update(&mut cx, |this, _| {
5533            this.register_ongoing_project_search((peer_id, handle), task);
5534        });
5535
5536        Ok(proto::Ack {})
5537    }
5538
5539    async fn handle_open_buffer_by_id(
5540        this: Entity<Self>,
5541        envelope: TypedEnvelope<proto::OpenBufferById>,
5542        mut cx: AsyncApp,
5543    ) -> Result<proto::OpenBufferResponse> {
5544        let peer_id = envelope.original_sender_id()?;
5545        let buffer_id = BufferId::new(envelope.payload.id)?;
5546        let buffer = this
5547            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))
5548            .await?;
5549        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
5550    }
5551
5552    async fn handle_open_buffer_by_path(
5553        this: Entity<Self>,
5554        envelope: TypedEnvelope<proto::OpenBufferByPath>,
5555        mut cx: AsyncApp,
5556    ) -> Result<proto::OpenBufferResponse> {
5557        let peer_id = envelope.original_sender_id()?;
5558        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5559        let path = RelPath::from_proto(&envelope.payload.path)?;
5560        let open_buffer = this
5561            .update(&mut cx, |this, cx| {
5562                this.open_buffer(ProjectPath { worktree_id, path }, cx)
5563            })
5564            .await?;
5565        Project::respond_to_open_buffer_request(this, open_buffer, peer_id, &mut cx)
5566    }
5567
5568    async fn handle_open_new_buffer(
5569        this: Entity<Self>,
5570        envelope: TypedEnvelope<proto::OpenNewBuffer>,
5571        mut cx: AsyncApp,
5572    ) -> Result<proto::OpenBufferResponse> {
5573        let buffer = this
5574            .update(&mut cx, |this, cx| this.create_buffer(None, true, cx))
5575            .await?;
5576        let peer_id = envelope.original_sender_id()?;
5577
5578        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
5579    }
5580
5581    fn respond_to_open_buffer_request(
5582        this: Entity<Self>,
5583        buffer: Entity<Buffer>,
5584        peer_id: proto::PeerId,
5585        cx: &mut AsyncApp,
5586    ) -> Result<proto::OpenBufferResponse> {
5587        this.update(cx, |this, cx| {
5588            let is_private = buffer
5589                .read(cx)
5590                .file()
5591                .map(|f| f.is_private())
5592                .unwrap_or_default();
5593            anyhow::ensure!(!is_private, ErrorCode::UnsharedItem);
5594            Ok(proto::OpenBufferResponse {
5595                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
5596            })
5597        })
5598    }
5599
5600    fn create_buffer_for_peer(
5601        &mut self,
5602        buffer: &Entity<Buffer>,
5603        peer_id: proto::PeerId,
5604        cx: &mut App,
5605    ) -> BufferId {
5606        self.buffer_store
5607            .update(cx, |buffer_store, cx| {
5608                buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
5609            })
5610            .detach_and_log_err(cx);
5611        buffer.read(cx).remote_id()
5612    }
5613
5614    async fn handle_create_image_for_peer(
5615        this: Entity<Self>,
5616        envelope: TypedEnvelope<proto::CreateImageForPeer>,
5617        mut cx: AsyncApp,
5618    ) -> Result<()> {
5619        this.update(&mut cx, |this, cx| {
5620            this.image_store.update(cx, |image_store, cx| {
5621                image_store.handle_create_image_for_peer(envelope, cx)
5622            })
5623        })
5624    }
5625
5626    async fn handle_create_file_for_peer(
5627        this: Entity<Self>,
5628        envelope: TypedEnvelope<proto::CreateFileForPeer>,
5629        mut cx: AsyncApp,
5630    ) -> Result<()> {
5631        use proto::create_file_for_peer::Variant;
5632        log::debug!("handle_create_file_for_peer: received message");
5633
5634        let downloading_files: Arc<Mutex<HashMap<(WorktreeId, String), DownloadingFile>>> =
5635            this.update(&mut cx, |this, _| this.downloading_files.clone());
5636
5637        match &envelope.payload.variant {
5638            Some(Variant::State(state)) => {
5639                log::debug!(
5640                    "handle_create_file_for_peer: got State: id={}, content_size={}",
5641                    state.id,
5642                    state.content_size
5643                );
5644
5645                // Extract worktree_id and path from the File field
5646                if let Some(ref file) = state.file {
5647                    let worktree_id = WorktreeId::from_proto(file.worktree_id);
5648                    let path = file.path.clone();
5649                    let key = (worktree_id, path);
5650                    log::debug!("handle_create_file_for_peer: looking up key={:?}", key);
5651
5652                    let empty_file_destination: Option<PathBuf> = {
5653                        let mut files = downloading_files.lock();
5654                        log::trace!(
5655                            "handle_create_file_for_peer: current downloading_files keys: {:?}",
5656                            files.keys().collect::<Vec<_>>()
5657                        );
5658
5659                        if let Some(file_entry) = files.get_mut(&key) {
5660                            file_entry.total_size = state.content_size;
5661                            file_entry.file_id = Some(state.id);
5662                            log::debug!(
5663                                "handle_create_file_for_peer: updated file entry: total_size={}, file_id={}",
5664                                state.content_size,
5665                                state.id
5666                            );
5667                        } else {
5668                            log::warn!(
5669                                "handle_create_file_for_peer: key={:?} not found in downloading_files",
5670                                key
5671                            );
5672                        }
5673
5674                        if state.content_size == 0 {
5675                            // No chunks will arrive for an empty file; write it now.
5676                            files.remove(&key).map(|entry| entry.destination_path)
5677                        } else {
5678                            None
5679                        }
5680                    };
5681
5682                    if let Some(destination) = empty_file_destination {
5683                        log::debug!(
5684                            "handle_create_file_for_peer: writing empty file to {:?}",
5685                            destination
5686                        );
5687                        match smol::fs::write(&destination, &[] as &[u8]).await {
5688                            Ok(_) => log::info!(
5689                                "handle_create_file_for_peer: successfully wrote file to {:?}",
5690                                destination
5691                            ),
5692                            Err(e) => log::error!(
5693                                "handle_create_file_for_peer: failed to write empty file: {:?}",
5694                                e
5695                            ),
5696                        }
5697                    }
5698                } else {
5699                    log::warn!("handle_create_file_for_peer: State has no file field");
5700                }
5701            }
5702            Some(Variant::Chunk(chunk)) => {
5703                log::debug!(
5704                    "handle_create_file_for_peer: got Chunk: file_id={}, data_len={}",
5705                    chunk.file_id,
5706                    chunk.data.len()
5707                );
5708
5709                // Extract data while holding the lock, then release it before await
5710                let (key_to_remove, write_info): (
5711                    Option<(WorktreeId, String)>,
5712                    Option<(PathBuf, Vec<u8>)>,
5713                ) = {
5714                    let mut files = downloading_files.lock();
5715                    let mut found_key: Option<(WorktreeId, String)> = None;
5716                    let mut write_data: Option<(PathBuf, Vec<u8>)> = None;
5717
5718                    for (key, file_entry) in files.iter_mut() {
5719                        if file_entry.file_id == Some(chunk.file_id) {
5720                            file_entry.chunks.extend_from_slice(&chunk.data);
5721                            log::debug!(
5722                                "handle_create_file_for_peer: accumulated {} bytes, total_size={}",
5723                                file_entry.chunks.len(),
5724                                file_entry.total_size
5725                            );
5726
5727                            if file_entry.chunks.len() as u64 >= file_entry.total_size
5728                                && file_entry.total_size > 0
5729                            {
5730                                let destination = file_entry.destination_path.clone();
5731                                let content = std::mem::take(&mut file_entry.chunks);
5732                                found_key = Some(key.clone());
5733                                write_data = Some((destination, content));
5734                            }
5735                            break;
5736                        }
5737                    }
5738                    (found_key, write_data)
5739                }; // MutexGuard is dropped here
5740
5741                // Perform the async write outside the lock
5742                if let Some((destination, content)) = write_info {
5743                    log::debug!(
5744                        "handle_create_file_for_peer: writing {} bytes to {:?}",
5745                        content.len(),
5746                        destination
5747                    );
5748                    match smol::fs::write(&destination, &content).await {
5749                        Ok(_) => log::info!(
5750                            "handle_create_file_for_peer: successfully wrote file to {:?}",
5751                            destination
5752                        ),
5753                        Err(e) => log::error!(
5754                            "handle_create_file_for_peer: failed to write file: {:?}",
5755                            e
5756                        ),
5757                    }
5758                }
5759
5760                // Remove the completed entry
5761                if let Some(key) = key_to_remove {
5762                    downloading_files.lock().remove(&key);
5763                    log::debug!("handle_create_file_for_peer: removed completed download entry");
5764                }
5765            }
5766            None => {
5767                log::warn!("handle_create_file_for_peer: got None variant");
5768            }
5769        }
5770
5771        Ok(())
5772    }
5773
5774    fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
5775        let project_id = match self.client_state {
5776            ProjectClientState::Collab {
5777                sharing_has_stopped,
5778                remote_id,
5779                ..
5780            } => {
5781                if sharing_has_stopped {
5782                    return Task::ready(Err(anyhow!(
5783                        "can't synchronize remote buffers on a readonly project"
5784                    )));
5785                } else {
5786                    remote_id
5787                }
5788            }
5789            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
5790                return Task::ready(Err(anyhow!(
5791                    "can't synchronize remote buffers on a local project"
5792                )));
5793            }
5794        };
5795
5796        let client = self.collab_client.clone();
5797        cx.spawn(async move |this, cx| {
5798            let (buffers, incomplete_buffer_ids) = this.update(cx, |this, cx| {
5799                this.buffer_store.read(cx).buffer_version_info(cx)
5800            })?;
5801            let response = client
5802                .request(proto::SynchronizeBuffers {
5803                    project_id,
5804                    buffers,
5805                })
5806                .await?;
5807
5808            let send_updates_for_buffers = this.update(cx, |this, cx| {
5809                response
5810                    .buffers
5811                    .into_iter()
5812                    .map(|buffer| {
5813                        let client = client.clone();
5814                        let buffer_id = match BufferId::new(buffer.id) {
5815                            Ok(id) => id,
5816                            Err(e) => {
5817                                return Task::ready(Err(e));
5818                            }
5819                        };
5820                        let remote_version = language::proto::deserialize_version(&buffer.version);
5821                        if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5822                            let operations =
5823                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
5824                            cx.background_spawn(async move {
5825                                let operations = operations.await;
5826                                for chunk in split_operations(operations) {
5827                                    client
5828                                        .request(proto::UpdateBuffer {
5829                                            project_id,
5830                                            buffer_id: buffer_id.into(),
5831                                            operations: chunk,
5832                                        })
5833                                        .await?;
5834                                }
5835                                anyhow::Ok(())
5836                            })
5837                        } else {
5838                            Task::ready(Ok(()))
5839                        }
5840                    })
5841                    .collect::<Vec<_>>()
5842            })?;
5843
5844            // Any incomplete buffers have open requests waiting. Request that the host sends
5845            // creates these buffers for us again to unblock any waiting futures.
5846            for id in incomplete_buffer_ids {
5847                cx.background_spawn(client.request(proto::OpenBufferById {
5848                    project_id,
5849                    id: id.into(),
5850                }))
5851                .detach();
5852            }
5853
5854            futures::future::join_all(send_updates_for_buffers)
5855                .await
5856                .into_iter()
5857                .collect()
5858        })
5859    }
5860
5861    pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
5862        self.worktree_store.read(cx).worktree_metadata_protos(cx)
5863    }
5864
5865    /// Iterator of all open buffers that have unsaved changes
5866    pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
5867        self.buffer_store.read(cx).buffers().filter_map(|buf| {
5868            let buf = buf.read(cx);
5869            if buf.is_dirty() {
5870                buf.project_path(cx)
5871            } else {
5872                None
5873            }
5874        })
5875    }
5876
5877    fn set_worktrees_from_proto(
5878        &mut self,
5879        worktrees: Vec<proto::WorktreeMetadata>,
5880        cx: &mut Context<Project>,
5881    ) -> Result<()> {
5882        self.worktree_store.update(cx, |worktree_store, cx| {
5883            worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
5884        })
5885    }
5886
5887    fn set_collaborators_from_proto(
5888        &mut self,
5889        messages: Vec<proto::Collaborator>,
5890        cx: &mut Context<Self>,
5891    ) -> Result<()> {
5892        let mut collaborators = HashMap::default();
5893        for message in messages {
5894            let collaborator = Collaborator::from_proto(message)?;
5895            collaborators.insert(collaborator.peer_id, collaborator);
5896        }
5897        for old_peer_id in self.collaborators.keys() {
5898            if !collaborators.contains_key(old_peer_id) {
5899                cx.emit(Event::CollaboratorLeft(*old_peer_id));
5900            }
5901        }
5902        self.collaborators = collaborators;
5903        Ok(())
5904    }
5905
5906    pub fn supplementary_language_servers<'a>(
5907        &'a self,
5908        cx: &'a App,
5909    ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
5910        self.lsp_store.read(cx).supplementary_language_servers()
5911    }
5912
5913    pub fn any_language_server_supports_inlay_hints(&self, buffer: &Buffer, cx: &mut App) -> bool {
5914        let Some(language) = buffer.language().cloned() else {
5915            return false;
5916        };
5917        self.lsp_store.update(cx, |lsp_store, _| {
5918            let relevant_language_servers = lsp_store
5919                .languages
5920                .lsp_adapters(&language.name())
5921                .into_iter()
5922                .map(|lsp_adapter| lsp_adapter.name())
5923                .collect::<HashSet<_>>();
5924            lsp_store
5925                .language_server_statuses()
5926                .filter_map(|(server_id, server_status)| {
5927                    relevant_language_servers
5928                        .contains(&server_status.name)
5929                        .then_some(server_id)
5930                })
5931                .filter_map(|server_id| lsp_store.lsp_server_capabilities.get(&server_id))
5932                .any(InlayHints::check_capabilities)
5933        })
5934    }
5935
5936    pub fn any_language_server_supports_semantic_tokens(
5937        &self,
5938        buffer: &Buffer,
5939        cx: &mut App,
5940    ) -> bool {
5941        let Some(language) = buffer.language().cloned() else {
5942            return false;
5943        };
5944        let lsp_store = self.lsp_store.read(cx);
5945        let relevant_language_servers = lsp_store
5946            .languages
5947            .lsp_adapters(&language.name())
5948            .into_iter()
5949            .map(|lsp_adapter| lsp_adapter.name())
5950            .collect::<HashSet<_>>();
5951        lsp_store
5952            .language_server_statuses()
5953            .filter_map(|(server_id, server_status)| {
5954                relevant_language_servers
5955                    .contains(&server_status.name)
5956                    .then_some(server_id)
5957            })
5958            .filter_map(|server_id| lsp_store.lsp_server_capabilities.get(&server_id))
5959            .any(|capabilities| capabilities.semantic_tokens_provider.is_some())
5960    }
5961
5962    pub fn language_server_id_for_name(
5963        &self,
5964        buffer: &Buffer,
5965        name: &LanguageServerName,
5966        cx: &App,
5967    ) -> Option<LanguageServerId> {
5968        let language = buffer.language()?;
5969        let relevant_language_servers = self
5970            .languages
5971            .lsp_adapters(&language.name())
5972            .into_iter()
5973            .map(|lsp_adapter| lsp_adapter.name())
5974            .collect::<HashSet<_>>();
5975        if !relevant_language_servers.contains(name) {
5976            return None;
5977        }
5978        self.language_server_statuses(cx)
5979            .filter(|(_, server_status)| relevant_language_servers.contains(&server_status.name))
5980            .find_map(|(server_id, server_status)| {
5981                if &server_status.name == name {
5982                    Some(server_id)
5983                } else {
5984                    None
5985                }
5986            })
5987    }
5988
5989    #[cfg(feature = "test-support")]
5990    pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
5991        self.lsp_store.update(cx, |this, cx| {
5992            this.running_language_servers_for_local_buffer(buffer, cx)
5993                .next()
5994                .is_some()
5995        })
5996    }
5997
5998    pub fn git_init(
5999        &self,
6000        path: Arc<Path>,
6001        fallback_branch_name: String,
6002        cx: &App,
6003    ) -> Task<Result<()>> {
6004        self.git_store
6005            .read(cx)
6006            .git_init(path, fallback_branch_name, cx)
6007    }
6008
6009    pub fn buffer_store(&self) -> &Entity<BufferStore> {
6010        &self.buffer_store
6011    }
6012
6013    pub fn git_store(&self) -> &Entity<GitStore> {
6014        &self.git_store
6015    }
6016
6017    pub fn agent_server_store(&self) -> &Entity<AgentServerStore> {
6018        &self.agent_server_store
6019    }
6020
6021    #[cfg(feature = "test-support")]
6022    pub fn git_scans_complete(&self, cx: &Context<Self>) -> Task<()> {
6023        use futures::future::join_all;
6024        cx.spawn(async move |this, cx| {
6025            let scans_complete = this
6026                .read_with(cx, |this, cx| {
6027                    this.worktrees(cx)
6028                        .filter_map(|worktree| Some(worktree.read(cx).as_local()?.scan_complete()))
6029                        .collect::<Vec<_>>()
6030                })
6031                .unwrap();
6032            join_all(scans_complete).await;
6033            let barriers = this
6034                .update(cx, |this, cx| {
6035                    let repos = this.repositories(cx).values().cloned().collect::<Vec<_>>();
6036                    repos
6037                        .into_iter()
6038                        .map(|repo| repo.update(cx, |repo, _| repo.barrier()))
6039                        .collect::<Vec<_>>()
6040                })
6041                .unwrap();
6042            join_all(barriers).await;
6043        })
6044    }
6045
6046    pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
6047        self.git_store.read(cx).active_repository()
6048    }
6049
6050    pub fn repositories<'a>(&self, cx: &'a App) -> &'a HashMap<RepositoryId, Entity<Repository>> {
6051        self.git_store.read(cx).repositories()
6052    }
6053
6054    pub fn status_for_buffer_id(&self, buffer_id: BufferId, cx: &App) -> Option<FileStatus> {
6055        self.git_store.read(cx).status_for_buffer_id(buffer_id, cx)
6056    }
6057
6058    pub fn set_agent_location(
6059        &mut self,
6060        new_location: Option<AgentLocation>,
6061        cx: &mut Context<Self>,
6062    ) {
6063        if let Some(old_location) = self.agent_location.as_ref() {
6064            old_location
6065                .buffer
6066                .update(cx, |buffer, cx| buffer.remove_agent_selections(cx))
6067                .ok();
6068        }
6069
6070        if let Some(location) = new_location.as_ref() {
6071            location
6072                .buffer
6073                .update(cx, |buffer, cx| {
6074                    buffer.set_agent_selections(
6075                        Arc::from([language::Selection {
6076                            id: 0,
6077                            start: location.position,
6078                            end: location.position,
6079                            reversed: false,
6080                            goal: language::SelectionGoal::None,
6081                        }]),
6082                        false,
6083                        CursorShape::Hollow,
6084                        cx,
6085                    )
6086                })
6087                .ok();
6088        }
6089
6090        self.agent_location = new_location;
6091        cx.emit(Event::AgentLocationChanged);
6092    }
6093
6094    pub fn agent_location(&self) -> Option<AgentLocation> {
6095        self.agent_location.clone()
6096    }
6097
6098    pub fn path_style(&self, cx: &App) -> PathStyle {
6099        self.worktree_store.read(cx).path_style()
6100    }
6101
6102    pub fn contains_local_settings_file(
6103        &self,
6104        worktree_id: WorktreeId,
6105        rel_path: &RelPath,
6106        cx: &App,
6107    ) -> bool {
6108        self.worktree_for_id(worktree_id, cx)
6109            .map_or(false, |worktree| {
6110                worktree.read(cx).entry_for_path(rel_path).is_some()
6111            })
6112    }
6113}
6114
6115/// Identifies a project group by a set of paths the workspaces in this group
6116/// have.
6117///
6118/// Paths are mapped to their main worktree path first so we can group
6119/// workspaces by main repos.
6120#[derive(PartialEq, Eq, Hash, Clone, Debug)]
6121pub struct ProjectGroupKey {
6122    /// The paths of the main worktrees for this project group.
6123    paths: PathList,
6124    host: Option<RemoteConnectionOptions>,
6125}
6126
6127impl ProjectGroupKey {
6128    /// Creates a new `ProjectGroupKey` with the given path list.
6129    ///
6130    /// The path list should point to the git main worktree paths for a project.
6131    pub fn new(host: Option<RemoteConnectionOptions>, paths: PathList) -> Self {
6132        Self { paths, host }
6133    }
6134
6135    pub fn path_list(&self) -> &PathList {
6136        &self.paths
6137    }
6138
6139    pub fn display_name(
6140        &self,
6141        path_detail_map: &std::collections::HashMap<PathBuf, usize>,
6142    ) -> SharedString {
6143        let mut names = Vec::with_capacity(self.paths.paths().len());
6144        for abs_path in self.paths.paths() {
6145            let detail = path_detail_map.get(abs_path).copied().unwrap_or(0);
6146            let suffix = path_suffix(abs_path, detail);
6147            if !suffix.is_empty() {
6148                names.push(suffix);
6149            }
6150        }
6151        if names.is_empty() {
6152            "Empty Workspace".into()
6153        } else {
6154            names.join(", ").into()
6155        }
6156    }
6157
6158    pub fn host(&self) -> Option<RemoteConnectionOptions> {
6159        self.host.clone()
6160    }
6161}
6162
6163pub fn path_suffix(path: &Path, detail: usize) -> String {
6164    let mut components: Vec<_> = path
6165        .components()
6166        .rev()
6167        .filter_map(|component| match component {
6168            std::path::Component::Normal(s) => Some(s.to_string_lossy()),
6169            _ => None,
6170        })
6171        .take(detail + 1)
6172        .collect();
6173    components.reverse();
6174    components.join("/")
6175}
6176
6177pub struct PathMatchCandidateSet {
6178    pub snapshot: Snapshot,
6179    pub include_ignored: bool,
6180    pub include_root_name: bool,
6181    pub candidates: Candidates,
6182}
6183
6184pub enum Candidates {
6185    /// Only consider directories.
6186    Directories,
6187    /// Only consider files.
6188    Files,
6189    /// Consider directories and files.
6190    Entries,
6191}
6192
6193impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
6194    type Candidates = PathMatchCandidateSetIter<'a>;
6195
6196    fn id(&self) -> usize {
6197        self.snapshot.id().to_usize()
6198    }
6199
6200    fn len(&self) -> usize {
6201        match self.candidates {
6202            Candidates::Files => {
6203                if self.include_ignored {
6204                    self.snapshot.file_count()
6205                } else {
6206                    self.snapshot.visible_file_count()
6207                }
6208            }
6209
6210            Candidates::Directories => {
6211                if self.include_ignored {
6212                    self.snapshot.dir_count()
6213                } else {
6214                    self.snapshot.visible_dir_count()
6215                }
6216            }
6217
6218            Candidates::Entries => {
6219                if self.include_ignored {
6220                    self.snapshot.entry_count()
6221                } else {
6222                    self.snapshot.visible_entry_count()
6223                }
6224            }
6225        }
6226    }
6227
6228    fn prefix(&self) -> Arc<RelPath> {
6229        if self.snapshot.root_entry().is_some_and(|e| e.is_file()) || self.include_root_name {
6230            self.snapshot.root_name().into()
6231        } else {
6232            RelPath::empty().into()
6233        }
6234    }
6235
6236    fn root_is_file(&self) -> bool {
6237        self.snapshot.root_entry().is_some_and(|f| f.is_file())
6238    }
6239
6240    fn path_style(&self) -> PathStyle {
6241        self.snapshot.path_style()
6242    }
6243
6244    fn candidates(&'a self, start: usize) -> Self::Candidates {
6245        PathMatchCandidateSetIter {
6246            traversal: match self.candidates {
6247                Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
6248                Candidates::Files => self.snapshot.files(self.include_ignored, start),
6249                Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
6250            },
6251        }
6252    }
6253}
6254
6255pub struct PathMatchCandidateSetIter<'a> {
6256    traversal: Traversal<'a>,
6257}
6258
6259impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
6260    type Item = fuzzy::PathMatchCandidate<'a>;
6261
6262    fn next(&mut self) -> Option<Self::Item> {
6263        self.traversal
6264            .next()
6265            .map(|entry| fuzzy::PathMatchCandidate {
6266                is_dir: entry.kind.is_dir(),
6267                path: &entry.path,
6268                char_bag: entry.char_bag,
6269            })
6270    }
6271}
6272
6273impl<'a> fuzzy_nucleo::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
6274    type Candidates = PathMatchCandidateSetNucleoIter<'a>;
6275    fn id(&self) -> usize {
6276        self.snapshot.id().to_usize()
6277    }
6278    fn len(&self) -> usize {
6279        match self.candidates {
6280            Candidates::Files => {
6281                if self.include_ignored {
6282                    self.snapshot.file_count()
6283                } else {
6284                    self.snapshot.visible_file_count()
6285                }
6286            }
6287            Candidates::Directories => {
6288                if self.include_ignored {
6289                    self.snapshot.dir_count()
6290                } else {
6291                    self.snapshot.visible_dir_count()
6292                }
6293            }
6294            Candidates::Entries => {
6295                if self.include_ignored {
6296                    self.snapshot.entry_count()
6297                } else {
6298                    self.snapshot.visible_entry_count()
6299                }
6300            }
6301        }
6302    }
6303    fn prefix(&self) -> Arc<RelPath> {
6304        if self.snapshot.root_entry().is_some_and(|e| e.is_file()) || self.include_root_name {
6305            self.snapshot.root_name().into()
6306        } else {
6307            RelPath::empty().into()
6308        }
6309    }
6310    fn root_is_file(&self) -> bool {
6311        self.snapshot.root_entry().is_some_and(|f| f.is_file())
6312    }
6313    fn path_style(&self) -> PathStyle {
6314        self.snapshot.path_style()
6315    }
6316    fn candidates(&'a self, start: usize) -> Self::Candidates {
6317        PathMatchCandidateSetNucleoIter {
6318            traversal: match self.candidates {
6319                Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
6320                Candidates::Files => self.snapshot.files(self.include_ignored, start),
6321                Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
6322            },
6323        }
6324    }
6325}
6326
6327pub struct PathMatchCandidateSetNucleoIter<'a> {
6328    traversal: Traversal<'a>,
6329}
6330
6331impl<'a> Iterator for PathMatchCandidateSetNucleoIter<'a> {
6332    type Item = fuzzy_nucleo::PathMatchCandidate<'a>;
6333    fn next(&mut self) -> Option<Self::Item> {
6334        self.traversal
6335            .next()
6336            .map(|entry| fuzzy_nucleo::PathMatchCandidate {
6337                is_dir: entry.kind.is_dir(),
6338                path: &entry.path,
6339            })
6340    }
6341}
6342
6343impl EventEmitter<Event> for Project {}
6344
6345impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
6346    fn from(val: &'a ProjectPath) -> Self {
6347        SettingsLocation {
6348            worktree_id: val.worktree_id,
6349            path: val.path.as_ref(),
6350        }
6351    }
6352}
6353
6354impl<P: Into<Arc<RelPath>>> From<(WorktreeId, P)> for ProjectPath {
6355    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
6356        Self {
6357            worktree_id,
6358            path: path.into(),
6359        }
6360    }
6361}
6362
6363/// ResolvedPath is a path that has been resolved to either a ProjectPath
6364/// or an AbsPath and that *exists*.
6365#[derive(Debug, Clone)]
6366pub enum ResolvedPath {
6367    ProjectPath {
6368        project_path: ProjectPath,
6369        is_dir: bool,
6370    },
6371    AbsPath {
6372        path: String,
6373        is_dir: bool,
6374    },
6375}
6376
6377impl ResolvedPath {
6378    pub fn abs_path(&self) -> Option<&str> {
6379        match self {
6380            Self::AbsPath { path, .. } => Some(path),
6381            _ => None,
6382        }
6383    }
6384
6385    pub fn into_abs_path(self) -> Option<String> {
6386        match self {
6387            Self::AbsPath { path, .. } => Some(path),
6388            _ => None,
6389        }
6390    }
6391
6392    pub fn project_path(&self) -> Option<&ProjectPath> {
6393        match self {
6394            Self::ProjectPath { project_path, .. } => Some(project_path),
6395            _ => None,
6396        }
6397    }
6398
6399    pub fn is_file(&self) -> bool {
6400        !self.is_dir()
6401    }
6402
6403    pub fn is_dir(&self) -> bool {
6404        match self {
6405            Self::ProjectPath { is_dir, .. } => *is_dir,
6406            Self::AbsPath { is_dir, .. } => *is_dir,
6407        }
6408    }
6409}
6410
6411impl ProjectItem for Buffer {
6412    fn try_open(
6413        project: &Entity<Project>,
6414        path: &ProjectPath,
6415        cx: &mut App,
6416    ) -> Option<Task<Result<Entity<Self>>>> {
6417        Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
6418    }
6419
6420    fn entry_id(&self, _cx: &App) -> Option<ProjectEntryId> {
6421        File::from_dyn(self.file()).and_then(|file| file.project_entry_id())
6422    }
6423
6424    fn project_path(&self, cx: &App) -> Option<ProjectPath> {
6425        let file = self.file()?;
6426
6427        (!matches!(file.disk_state(), DiskState::Historic { .. })).then(|| ProjectPath {
6428            worktree_id: file.worktree_id(cx),
6429            path: file.path().clone(),
6430        })
6431    }
6432
6433    fn is_dirty(&self) -> bool {
6434        self.is_dirty()
6435    }
6436}
6437
6438impl Completion {
6439    pub fn kind(&self) -> Option<CompletionItemKind> {
6440        self.source
6441            // `lsp::CompletionListItemDefaults` has no `kind` field
6442            .lsp_completion(false)
6443            .and_then(|lsp_completion| lsp_completion.kind)
6444    }
6445
6446    pub fn label(&self) -> Option<String> {
6447        self.source
6448            .lsp_completion(false)
6449            .map(|lsp_completion| lsp_completion.label.clone())
6450    }
6451
6452    /// A key that can be used to sort completions when displaying
6453    /// them to the user.
6454    pub fn sort_key(&self) -> (usize, &str) {
6455        const DEFAULT_KIND_KEY: usize = 4;
6456        let kind_key = self
6457            .kind()
6458            .and_then(|lsp_completion_kind| match lsp_completion_kind {
6459                lsp::CompletionItemKind::KEYWORD => Some(0),
6460                lsp::CompletionItemKind::VARIABLE => Some(1),
6461                lsp::CompletionItemKind::CONSTANT => Some(2),
6462                lsp::CompletionItemKind::PROPERTY => Some(3),
6463                _ => None,
6464            })
6465            .unwrap_or(DEFAULT_KIND_KEY);
6466        (kind_key, self.label.filter_text())
6467    }
6468
6469    /// Whether this completion is a snippet.
6470    pub fn is_snippet_kind(&self) -> bool {
6471        matches!(
6472            &self.source,
6473            CompletionSource::Lsp { lsp_completion, .. }
6474            if lsp_completion.kind == Some(CompletionItemKind::SNIPPET)
6475        )
6476    }
6477
6478    /// Whether this completion is a snippet or snippet-style LSP completion.
6479    pub fn is_snippet(&self) -> bool {
6480        self.source
6481            // `lsp::CompletionListItemDefaults` has `insert_text_format` field
6482            .lsp_completion(true)
6483            .is_some_and(|lsp_completion| {
6484                lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
6485            })
6486    }
6487
6488    /// Returns the corresponding color for this completion.
6489    ///
6490    /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
6491    pub fn color(&self) -> Option<Hsla> {
6492        // `lsp::CompletionListItemDefaults` has no `kind` field
6493        let lsp_completion = self.source.lsp_completion(false)?;
6494        if lsp_completion.kind? == CompletionItemKind::COLOR {
6495            return color_extractor::extract_color(&lsp_completion);
6496        }
6497        None
6498    }
6499}
6500
6501fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
6502    match level {
6503        proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
6504        proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
6505        proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
6506    }
6507}
6508
6509fn provide_inline_values(
6510    captures: impl Iterator<Item = (Range<usize>, language::DebuggerTextObject)>,
6511    snapshot: &language::BufferSnapshot,
6512    max_row: usize,
6513) -> Vec<InlineValueLocation> {
6514    let mut variables = Vec::new();
6515    let mut variable_position = HashSet::default();
6516    let mut scopes = Vec::new();
6517
6518    let active_debug_line_offset = snapshot.point_to_offset(Point::new(max_row as u32, 0));
6519
6520    for (capture_range, capture_kind) in captures {
6521        match capture_kind {
6522            language::DebuggerTextObject::Variable => {
6523                let variable_name = snapshot
6524                    .text_for_range(capture_range.clone())
6525                    .collect::<String>();
6526                let point = snapshot.offset_to_point(capture_range.end);
6527
6528                while scopes
6529                    .last()
6530                    .is_some_and(|scope: &Range<_>| !scope.contains(&capture_range.start))
6531                {
6532                    scopes.pop();
6533                }
6534
6535                if point.row as usize > max_row {
6536                    break;
6537                }
6538
6539                let scope = if scopes
6540                    .last()
6541                    .is_none_or(|scope| !scope.contains(&active_debug_line_offset))
6542                {
6543                    VariableScope::Global
6544                } else {
6545                    VariableScope::Local
6546                };
6547
6548                if variable_position.insert(capture_range.end) {
6549                    variables.push(InlineValueLocation {
6550                        variable_name,
6551                        scope,
6552                        lookup: VariableLookupKind::Variable,
6553                        row: point.row as usize,
6554                        column: point.column as usize,
6555                    });
6556                }
6557            }
6558            language::DebuggerTextObject::Scope => {
6559                while scopes.last().map_or_else(
6560                    || false,
6561                    |scope: &Range<usize>| {
6562                        !(scope.contains(&capture_range.start)
6563                            && scope.contains(&capture_range.end))
6564                    },
6565                ) {
6566                    scopes.pop();
6567                }
6568                scopes.push(capture_range);
6569            }
6570        }
6571    }
6572
6573    variables
6574}