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