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