project.rs

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