project.rs

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