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