project.rs

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