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