project.rs

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