project.rs

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