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