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