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