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