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