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