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