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