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            self.worktree_store.update(cx, |worktree_store, cx| {
2487                for worktree in worktree_store.worktrees() {
2488                    store
2489                        .clear_local_settings(worktree.read(cx).id(), cx)
2490                        .log_err();
2491                }
2492            });
2493        });
2494
2495        self.join_project_response_message_id = message_id;
2496        self.set_worktrees_from_proto(message.worktrees, cx)?;
2497        self.set_collaborators_from_proto(message.collaborators, cx)?;
2498
2499        let project = cx.weak_entity();
2500        self.lsp_store.update(cx, |lsp_store, cx| {
2501            lsp_store.set_language_server_statuses_from_proto(
2502                project,
2503                message.language_servers,
2504                message.language_server_capabilities,
2505                cx,
2506            )
2507        });
2508        self.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
2509            .unwrap();
2510        cx.emit(Event::Rejoined);
2511        Ok(())
2512    }
2513
2514    #[inline]
2515    pub fn unshare(&mut self, cx: &mut Context<Self>) -> Result<()> {
2516        self.unshare_internal(cx)?;
2517        cx.emit(Event::RemoteIdChanged(None));
2518        Ok(())
2519    }
2520
2521    fn unshare_internal(&mut self, cx: &mut App) -> Result<()> {
2522        anyhow::ensure!(
2523            !self.is_via_collab(),
2524            "attempted to unshare a remote project"
2525        );
2526
2527        if let ProjectClientState::Shared { remote_id, .. } = self.client_state {
2528            self.client_state = ProjectClientState::Local;
2529            self.collaborators.clear();
2530            self.client_subscriptions.clear();
2531            self.worktree_store.update(cx, |store, cx| {
2532                store.unshared(cx);
2533            });
2534            self.buffer_store.update(cx, |buffer_store, cx| {
2535                buffer_store.forget_shared_buffers();
2536                buffer_store.unshared(cx)
2537            });
2538            self.task_store.update(cx, |task_store, cx| {
2539                task_store.unshared(cx);
2540            });
2541            self.breakpoint_store.update(cx, |breakpoint_store, cx| {
2542                breakpoint_store.unshared(cx);
2543            });
2544            self.dap_store.update(cx, |dap_store, cx| {
2545                dap_store.unshared(cx);
2546            });
2547            self.settings_observer.update(cx, |settings_observer, cx| {
2548                settings_observer.unshared(cx);
2549            });
2550            self.git_store.update(cx, |git_store, cx| {
2551                git_store.unshared(cx);
2552            });
2553
2554            self.collab_client
2555                .send(proto::UnshareProject {
2556                    project_id: remote_id,
2557                })
2558                .ok();
2559            Ok(())
2560        } else {
2561            anyhow::bail!("attempted to unshare an unshared project");
2562        }
2563    }
2564
2565    pub fn disconnected_from_host(&mut self, cx: &mut Context<Self>) {
2566        if self.is_disconnected(cx) {
2567            return;
2568        }
2569        self.disconnected_from_host_internal(cx);
2570        cx.emit(Event::DisconnectedFromHost);
2571    }
2572
2573    pub fn set_role(&mut self, role: proto::ChannelRole, cx: &mut Context<Self>) {
2574        let new_capability =
2575            if role == proto::ChannelRole::Member || role == proto::ChannelRole::Admin {
2576                Capability::ReadWrite
2577            } else {
2578                Capability::ReadOnly
2579            };
2580        if let ProjectClientState::Remote { capability, .. } = &mut self.client_state {
2581            if *capability == new_capability {
2582                return;
2583            }
2584
2585            *capability = new_capability;
2586            for buffer in self.opened_buffers(cx) {
2587                buffer.update(cx, |buffer, cx| buffer.set_capability(new_capability, cx));
2588            }
2589        }
2590    }
2591
2592    fn disconnected_from_host_internal(&mut self, cx: &mut App) {
2593        if let ProjectClientState::Remote {
2594            sharing_has_stopped,
2595            ..
2596        } = &mut self.client_state
2597        {
2598            *sharing_has_stopped = true;
2599            self.collaborators.clear();
2600            self.worktree_store.update(cx, |store, cx| {
2601                store.disconnected_from_host(cx);
2602            });
2603            self.buffer_store.update(cx, |buffer_store, cx| {
2604                buffer_store.disconnected_from_host(cx)
2605            });
2606            self.lsp_store
2607                .update(cx, |lsp_store, _cx| lsp_store.disconnected_from_host());
2608        }
2609    }
2610
2611    #[inline]
2612    pub fn close(&mut self, cx: &mut Context<Self>) {
2613        cx.emit(Event::Closed);
2614    }
2615
2616    #[inline]
2617    pub fn is_disconnected(&self, cx: &App) -> bool {
2618        match &self.client_state {
2619            ProjectClientState::Remote {
2620                sharing_has_stopped,
2621                ..
2622            } => *sharing_has_stopped,
2623            ProjectClientState::Local if self.is_via_remote_server() => {
2624                self.remote_client_is_disconnected(cx)
2625            }
2626            _ => false,
2627        }
2628    }
2629
2630    #[inline]
2631    fn remote_client_is_disconnected(&self, cx: &App) -> bool {
2632        self.remote_client
2633            .as_ref()
2634            .map(|remote| remote.read(cx).is_disconnected())
2635            .unwrap_or(false)
2636    }
2637
2638    #[inline]
2639    pub fn capability(&self) -> Capability {
2640        match &self.client_state {
2641            ProjectClientState::Remote { capability, .. } => *capability,
2642            ProjectClientState::Shared { .. } | ProjectClientState::Local => Capability::ReadWrite,
2643        }
2644    }
2645
2646    #[inline]
2647    pub fn is_read_only(&self, cx: &App) -> bool {
2648        self.is_disconnected(cx) || self.capability() == Capability::ReadOnly
2649    }
2650
2651    #[inline]
2652    pub fn is_local(&self) -> bool {
2653        match &self.client_state {
2654            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2655                self.remote_client.is_none()
2656            }
2657            ProjectClientState::Remote { .. } => false,
2658        }
2659    }
2660
2661    /// Whether this project is a remote server (not counting collab).
2662    #[inline]
2663    pub fn is_via_remote_server(&self) -> bool {
2664        match &self.client_state {
2665            ProjectClientState::Local | ProjectClientState::Shared { .. } => {
2666                self.remote_client.is_some()
2667            }
2668            ProjectClientState::Remote { .. } => false,
2669        }
2670    }
2671
2672    /// Whether this project is from collab (not counting remote servers).
2673    #[inline]
2674    pub fn is_via_collab(&self) -> bool {
2675        match &self.client_state {
2676            ProjectClientState::Local | ProjectClientState::Shared { .. } => false,
2677            ProjectClientState::Remote { .. } => true,
2678        }
2679    }
2680
2681    /// `!self.is_local()`
2682    #[inline]
2683    pub fn is_remote(&self) -> bool {
2684        debug_assert_eq!(
2685            !self.is_local(),
2686            self.is_via_collab() || self.is_via_remote_server()
2687        );
2688        !self.is_local()
2689    }
2690
2691    pub fn disable_worktree_scanner(&mut self, cx: &mut Context<Self>) {
2692        self.worktree_store.update(cx, |worktree_store, _cx| {
2693            worktree_store.disable_scanner();
2694        });
2695    }
2696
2697    #[inline]
2698    pub fn create_buffer(
2699        &mut self,
2700        searchable: bool,
2701        cx: &mut Context<Self>,
2702    ) -> Task<Result<Entity<Buffer>>> {
2703        self.buffer_store.update(cx, |buffer_store, cx| {
2704            buffer_store.create_buffer(searchable, cx)
2705        })
2706    }
2707
2708    #[inline]
2709    pub fn create_local_buffer(
2710        &mut self,
2711        text: &str,
2712        language: Option<Arc<Language>>,
2713        project_searchable: bool,
2714        cx: &mut Context<Self>,
2715    ) -> Entity<Buffer> {
2716        if self.is_remote() {
2717            panic!("called create_local_buffer on a remote project")
2718        }
2719        self.buffer_store.update(cx, |buffer_store, cx| {
2720            buffer_store.create_local_buffer(text, language, project_searchable, cx)
2721        })
2722    }
2723
2724    pub fn open_path(
2725        &mut self,
2726        path: ProjectPath,
2727        cx: &mut Context<Self>,
2728    ) -> Task<Result<(Option<ProjectEntryId>, Entity<Buffer>)>> {
2729        let task = self.open_buffer(path, cx);
2730        cx.spawn(async move |_project, cx| {
2731            let buffer = task.await?;
2732            let project_entry_id = buffer.read_with(cx, |buffer, _cx| {
2733                File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id())
2734            })?;
2735
2736            Ok((project_entry_id, buffer))
2737        })
2738    }
2739
2740    pub fn open_local_buffer(
2741        &mut self,
2742        abs_path: impl AsRef<Path>,
2743        cx: &mut Context<Self>,
2744    ) -> Task<Result<Entity<Buffer>>> {
2745        let worktree_task = self.find_or_create_worktree(abs_path.as_ref(), false, cx);
2746        cx.spawn(async move |this, cx| {
2747            let (worktree, relative_path) = worktree_task.await?;
2748            this.update(cx, |this, cx| {
2749                this.open_buffer((worktree.read(cx).id(), relative_path), cx)
2750            })?
2751            .await
2752        })
2753    }
2754
2755    #[cfg(any(test, feature = "test-support"))]
2756    pub fn open_local_buffer_with_lsp(
2757        &mut self,
2758        abs_path: impl AsRef<Path>,
2759        cx: &mut Context<Self>,
2760    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
2761        if let Some((worktree, relative_path)) = self.find_worktree(abs_path.as_ref(), cx) {
2762            self.open_buffer_with_lsp((worktree.read(cx).id(), relative_path), cx)
2763        } else {
2764            Task::ready(Err(anyhow!("no such path")))
2765        }
2766    }
2767
2768    pub fn open_buffer(
2769        &mut self,
2770        path: impl Into<ProjectPath>,
2771        cx: &mut App,
2772    ) -> Task<Result<Entity<Buffer>>> {
2773        if self.is_disconnected(cx) {
2774            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2775        }
2776
2777        self.buffer_store.update(cx, |buffer_store, cx| {
2778            buffer_store.open_buffer(path.into(), cx)
2779        })
2780    }
2781
2782    #[cfg(any(test, feature = "test-support"))]
2783    pub fn open_buffer_with_lsp(
2784        &mut self,
2785        path: impl Into<ProjectPath>,
2786        cx: &mut Context<Self>,
2787    ) -> Task<Result<(Entity<Buffer>, lsp_store::OpenLspBufferHandle)>> {
2788        let buffer = self.open_buffer(path, cx);
2789        cx.spawn(async move |this, cx| {
2790            let buffer = buffer.await?;
2791            let handle = this.update(cx, |project, cx| {
2792                project.register_buffer_with_language_servers(&buffer, cx)
2793            })?;
2794            Ok((buffer, handle))
2795        })
2796    }
2797
2798    pub fn register_buffer_with_language_servers(
2799        &self,
2800        buffer: &Entity<Buffer>,
2801        cx: &mut App,
2802    ) -> OpenLspBufferHandle {
2803        self.lsp_store.update(cx, |lsp_store, cx| {
2804            lsp_store.register_buffer_with_language_servers(buffer, HashSet::default(), false, cx)
2805        })
2806    }
2807
2808    pub fn open_unstaged_diff(
2809        &mut self,
2810        buffer: Entity<Buffer>,
2811        cx: &mut Context<Self>,
2812    ) -> Task<Result<Entity<BufferDiff>>> {
2813        if self.is_disconnected(cx) {
2814            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2815        }
2816        self.git_store
2817            .update(cx, |git_store, cx| git_store.open_unstaged_diff(buffer, cx))
2818    }
2819
2820    pub fn open_uncommitted_diff(
2821        &mut self,
2822        buffer: Entity<Buffer>,
2823        cx: &mut Context<Self>,
2824    ) -> Task<Result<Entity<BufferDiff>>> {
2825        if self.is_disconnected(cx) {
2826            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2827        }
2828        self.git_store.update(cx, |git_store, cx| {
2829            git_store.open_uncommitted_diff(buffer, cx)
2830        })
2831    }
2832
2833    pub fn open_buffer_by_id(
2834        &mut self,
2835        id: BufferId,
2836        cx: &mut Context<Self>,
2837    ) -> Task<Result<Entity<Buffer>>> {
2838        if let Some(buffer) = self.buffer_for_id(id, cx) {
2839            Task::ready(Ok(buffer))
2840        } else if self.is_local() || self.is_via_remote_server() {
2841            Task::ready(Err(anyhow!("buffer {id} does not exist")))
2842        } else if let Some(project_id) = self.remote_id() {
2843            let request = self.collab_client.request(proto::OpenBufferById {
2844                project_id,
2845                id: id.into(),
2846            });
2847            cx.spawn(async move |project, cx| {
2848                let buffer_id = BufferId::new(request.await?.buffer_id)?;
2849                project
2850                    .update(cx, |project, cx| {
2851                        project.buffer_store.update(cx, |buffer_store, cx| {
2852                            buffer_store.wait_for_remote_buffer(buffer_id, cx)
2853                        })
2854                    })?
2855                    .await
2856            })
2857        } else {
2858            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
2859        }
2860    }
2861
2862    pub fn save_buffers(
2863        &self,
2864        buffers: HashSet<Entity<Buffer>>,
2865        cx: &mut Context<Self>,
2866    ) -> Task<Result<()>> {
2867        cx.spawn(async move |this, cx| {
2868            let save_tasks = buffers.into_iter().filter_map(|buffer| {
2869                this.update(cx, |this, cx| this.save_buffer(buffer, cx))
2870                    .ok()
2871            });
2872            try_join_all(save_tasks).await?;
2873            Ok(())
2874        })
2875    }
2876
2877    pub fn save_buffer(&self, buffer: Entity<Buffer>, cx: &mut Context<Self>) -> Task<Result<()>> {
2878        self.buffer_store
2879            .update(cx, |buffer_store, cx| buffer_store.save_buffer(buffer, cx))
2880    }
2881
2882    pub fn save_buffer_as(
2883        &mut self,
2884        buffer: Entity<Buffer>,
2885        path: ProjectPath,
2886        cx: &mut Context<Self>,
2887    ) -> Task<Result<()>> {
2888        self.buffer_store.update(cx, |buffer_store, cx| {
2889            buffer_store.save_buffer_as(buffer.clone(), path, cx)
2890        })
2891    }
2892
2893    pub fn get_open_buffer(&self, path: &ProjectPath, cx: &App) -> Option<Entity<Buffer>> {
2894        self.buffer_store.read(cx).get_by_path(path)
2895    }
2896
2897    fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) -> Result<()> {
2898        {
2899            let mut remotely_created_models = self.remotely_created_models.lock();
2900            if remotely_created_models.retain_count > 0 {
2901                remotely_created_models.buffers.push(buffer.clone())
2902            }
2903        }
2904
2905        self.request_buffer_diff_recalculation(buffer, cx);
2906
2907        cx.subscribe(buffer, |this, buffer, event, cx| {
2908            this.on_buffer_event(buffer, event, cx);
2909        })
2910        .detach();
2911
2912        Ok(())
2913    }
2914
2915    pub fn open_image(
2916        &mut self,
2917        path: impl Into<ProjectPath>,
2918        cx: &mut Context<Self>,
2919    ) -> Task<Result<Entity<ImageItem>>> {
2920        if self.is_disconnected(cx) {
2921            return Task::ready(Err(anyhow!(ErrorCode::Disconnected)));
2922        }
2923
2924        let open_image_task = self.image_store.update(cx, |image_store, cx| {
2925            image_store.open_image(path.into(), cx)
2926        });
2927
2928        let weak_project = cx.entity().downgrade();
2929        cx.spawn(async move |_, cx| {
2930            let image_item = open_image_task.await?;
2931
2932            // Check if metadata already exists (e.g., for remote images)
2933            let needs_metadata =
2934                cx.read_entity(&image_item, |item, _| item.image_metadata.is_none())?;
2935
2936            if needs_metadata {
2937                let project = weak_project.upgrade().context("Project dropped")?;
2938                let metadata =
2939                    ImageItem::load_image_metadata(image_item.clone(), project, cx).await?;
2940                image_item.update(cx, |image_item, cx| {
2941                    image_item.image_metadata = Some(metadata);
2942                    cx.emit(ImageItemEvent::MetadataUpdated);
2943                })?;
2944            }
2945
2946            Ok(image_item)
2947        })
2948    }
2949
2950    async fn send_buffer_ordered_messages(
2951        project: WeakEntity<Self>,
2952        rx: UnboundedReceiver<BufferOrderedMessage>,
2953        cx: &mut AsyncApp,
2954    ) -> Result<()> {
2955        const MAX_BATCH_SIZE: usize = 128;
2956
2957        let mut operations_by_buffer_id = HashMap::default();
2958        async fn flush_operations(
2959            this: &WeakEntity<Project>,
2960            operations_by_buffer_id: &mut HashMap<BufferId, Vec<proto::Operation>>,
2961            needs_resync_with_host: &mut bool,
2962            is_local: bool,
2963            cx: &mut AsyncApp,
2964        ) -> Result<()> {
2965            for (buffer_id, operations) in operations_by_buffer_id.drain() {
2966                let request = this.read_with(cx, |this, _| {
2967                    let project_id = this.remote_id()?;
2968                    Some(this.collab_client.request(proto::UpdateBuffer {
2969                        buffer_id: buffer_id.into(),
2970                        project_id,
2971                        operations,
2972                    }))
2973                })?;
2974                if let Some(request) = request
2975                    && request.await.is_err()
2976                    && !is_local
2977                {
2978                    *needs_resync_with_host = true;
2979                    break;
2980                }
2981            }
2982            Ok(())
2983        }
2984
2985        let mut needs_resync_with_host = false;
2986        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
2987
2988        while let Some(changes) = changes.next().await {
2989            let is_local = project.read_with(cx, |this, _| this.is_local())?;
2990
2991            for change in changes {
2992                match change {
2993                    BufferOrderedMessage::Operation {
2994                        buffer_id,
2995                        operation,
2996                    } => {
2997                        if needs_resync_with_host {
2998                            continue;
2999                        }
3000
3001                        operations_by_buffer_id
3002                            .entry(buffer_id)
3003                            .or_insert(Vec::new())
3004                            .push(operation);
3005                    }
3006
3007                    BufferOrderedMessage::Resync => {
3008                        operations_by_buffer_id.clear();
3009                        if project
3010                            .update(cx, |this, cx| this.synchronize_remote_buffers(cx))?
3011                            .await
3012                            .is_ok()
3013                        {
3014                            needs_resync_with_host = false;
3015                        }
3016                    }
3017
3018                    BufferOrderedMessage::LanguageServerUpdate {
3019                        language_server_id,
3020                        message,
3021                        name,
3022                    } => {
3023                        flush_operations(
3024                            &project,
3025                            &mut operations_by_buffer_id,
3026                            &mut needs_resync_with_host,
3027                            is_local,
3028                            cx,
3029                        )
3030                        .await?;
3031
3032                        project.read_with(cx, |project, _| {
3033                            if let Some(project_id) = project.remote_id() {
3034                                project
3035                                    .collab_client
3036                                    .send(proto::UpdateLanguageServer {
3037                                        project_id,
3038                                        server_name: name.map(|name| String::from(name.0)),
3039                                        language_server_id: language_server_id.to_proto(),
3040                                        variant: Some(message),
3041                                    })
3042                                    .log_err();
3043                            }
3044                        })?;
3045                    }
3046                }
3047            }
3048
3049            flush_operations(
3050                &project,
3051                &mut operations_by_buffer_id,
3052                &mut needs_resync_with_host,
3053                is_local,
3054                cx,
3055            )
3056            .await?;
3057        }
3058
3059        Ok(())
3060    }
3061
3062    fn on_buffer_store_event(
3063        &mut self,
3064        _: Entity<BufferStore>,
3065        event: &BufferStoreEvent,
3066        cx: &mut Context<Self>,
3067    ) {
3068        match event {
3069            BufferStoreEvent::BufferAdded(buffer) => {
3070                self.register_buffer(buffer, cx).log_err();
3071            }
3072            BufferStoreEvent::BufferDropped(buffer_id) => {
3073                if let Some(ref remote_client) = self.remote_client {
3074                    remote_client
3075                        .read(cx)
3076                        .proto_client()
3077                        .send(proto::CloseBuffer {
3078                            project_id: 0,
3079                            buffer_id: buffer_id.to_proto(),
3080                        })
3081                        .log_err();
3082                }
3083            }
3084            _ => {}
3085        }
3086    }
3087
3088    fn on_image_store_event(
3089        &mut self,
3090        _: Entity<ImageStore>,
3091        event: &ImageStoreEvent,
3092        cx: &mut Context<Self>,
3093    ) {
3094        match event {
3095            ImageStoreEvent::ImageAdded(image) => {
3096                cx.subscribe(image, |this, image, event, cx| {
3097                    this.on_image_event(image, event, cx);
3098                })
3099                .detach();
3100            }
3101        }
3102    }
3103
3104    fn on_dap_store_event(
3105        &mut self,
3106        _: Entity<DapStore>,
3107        event: &DapStoreEvent,
3108        cx: &mut Context<Self>,
3109    ) {
3110        if let DapStoreEvent::Notification(message) = event {
3111            cx.emit(Event::Toast {
3112                notification_id: "dap".into(),
3113                message: message.clone(),
3114            });
3115        }
3116    }
3117
3118    fn on_lsp_store_event(
3119        &mut self,
3120        _: Entity<LspStore>,
3121        event: &LspStoreEvent,
3122        cx: &mut Context<Self>,
3123    ) {
3124        match event {
3125            LspStoreEvent::DiagnosticsUpdated { server_id, paths } => {
3126                cx.emit(Event::DiagnosticsUpdated {
3127                    paths: paths.clone(),
3128                    language_server_id: *server_id,
3129                })
3130            }
3131            LspStoreEvent::LanguageServerAdded(server_id, name, worktree_id) => cx.emit(
3132                Event::LanguageServerAdded(*server_id, name.clone(), *worktree_id),
3133            ),
3134            LspStoreEvent::LanguageServerRemoved(server_id) => {
3135                cx.emit(Event::LanguageServerRemoved(*server_id))
3136            }
3137            LspStoreEvent::LanguageServerLog(server_id, log_type, string) => cx.emit(
3138                Event::LanguageServerLog(*server_id, log_type.clone(), string.clone()),
3139            ),
3140            LspStoreEvent::LanguageDetected {
3141                buffer,
3142                new_language,
3143            } => {
3144                let Some(_) = new_language else {
3145                    cx.emit(Event::LanguageNotFound(buffer.clone()));
3146                    return;
3147                };
3148            }
3149            LspStoreEvent::RefreshInlayHints {
3150                server_id,
3151                request_id,
3152            } => cx.emit(Event::RefreshInlayHints {
3153                server_id: *server_id,
3154                request_id: *request_id,
3155            }),
3156            LspStoreEvent::RefreshCodeLens => cx.emit(Event::RefreshCodeLens),
3157            LspStoreEvent::LanguageServerPrompt(prompt) => {
3158                cx.emit(Event::LanguageServerPrompt(prompt.clone()))
3159            }
3160            LspStoreEvent::DiskBasedDiagnosticsStarted { language_server_id } => {
3161                cx.emit(Event::DiskBasedDiagnosticsStarted {
3162                    language_server_id: *language_server_id,
3163                });
3164            }
3165            LspStoreEvent::DiskBasedDiagnosticsFinished { language_server_id } => {
3166                cx.emit(Event::DiskBasedDiagnosticsFinished {
3167                    language_server_id: *language_server_id,
3168                });
3169            }
3170            LspStoreEvent::LanguageServerUpdate {
3171                language_server_id,
3172                name,
3173                message,
3174            } => {
3175                if self.is_local() {
3176                    self.enqueue_buffer_ordered_message(
3177                        BufferOrderedMessage::LanguageServerUpdate {
3178                            language_server_id: *language_server_id,
3179                            message: message.clone(),
3180                            name: name.clone(),
3181                        },
3182                    )
3183                    .ok();
3184                }
3185
3186                match message {
3187                    proto::update_language_server::Variant::MetadataUpdated(update) => {
3188                        self.lsp_store.update(cx, |lsp_store, _| {
3189                            if let Some(capabilities) = update
3190                                .capabilities
3191                                .as_ref()
3192                                .and_then(|capabilities| serde_json::from_str(capabilities).ok())
3193                            {
3194                                lsp_store
3195                                    .lsp_server_capabilities
3196                                    .insert(*language_server_id, capabilities);
3197                            }
3198
3199                            if let Some(language_server_status) = lsp_store
3200                                .language_server_statuses
3201                                .get_mut(language_server_id)
3202                            {
3203                                if let Some(binary) = &update.binary {
3204                                    language_server_status.binary = Some(LanguageServerBinary {
3205                                        path: PathBuf::from(&binary.path),
3206                                        arguments: binary
3207                                            .arguments
3208                                            .iter()
3209                                            .map(OsString::from)
3210                                            .collect(),
3211                                        env: None,
3212                                    });
3213                                }
3214
3215                                language_server_status.configuration = update
3216                                    .configuration
3217                                    .as_ref()
3218                                    .and_then(|config_str| serde_json::from_str(config_str).ok());
3219
3220                                language_server_status.workspace_folders = update
3221                                    .workspace_folders
3222                                    .iter()
3223                                    .filter_map(|uri_str| lsp::Uri::from_str(uri_str).ok())
3224                                    .collect();
3225                            }
3226                        });
3227                    }
3228                    proto::update_language_server::Variant::RegisteredForBuffer(update) => {
3229                        if let Some(buffer_id) = BufferId::new(update.buffer_id).ok() {
3230                            cx.emit(Event::LanguageServerBufferRegistered {
3231                                buffer_id,
3232                                server_id: *language_server_id,
3233                                buffer_abs_path: PathBuf::from(&update.buffer_abs_path),
3234                                name: name.clone(),
3235                            });
3236                        }
3237                    }
3238                    _ => (),
3239                }
3240            }
3241            LspStoreEvent::Notification(message) => cx.emit(Event::Toast {
3242                notification_id: "lsp".into(),
3243                message: message.clone(),
3244            }),
3245            LspStoreEvent::SnippetEdit {
3246                buffer_id,
3247                edits,
3248                most_recent_edit,
3249            } => {
3250                if most_recent_edit.replica_id == self.replica_id() {
3251                    cx.emit(Event::SnippetEdit(*buffer_id, edits.clone()))
3252                }
3253            }
3254        }
3255    }
3256
3257    fn on_remote_client_event(
3258        &mut self,
3259        _: Entity<RemoteClient>,
3260        event: &remote::RemoteClientEvent,
3261        cx: &mut Context<Self>,
3262    ) {
3263        match event {
3264            remote::RemoteClientEvent::Disconnected => {
3265                self.worktree_store.update(cx, |store, cx| {
3266                    store.disconnected_from_host(cx);
3267                });
3268                self.buffer_store.update(cx, |buffer_store, cx| {
3269                    buffer_store.disconnected_from_host(cx)
3270                });
3271                self.lsp_store.update(cx, |lsp_store, _cx| {
3272                    lsp_store.disconnected_from_ssh_remote()
3273                });
3274                cx.emit(Event::DisconnectedFromSshRemote);
3275            }
3276        }
3277    }
3278
3279    fn on_settings_observer_event(
3280        &mut self,
3281        _: Entity<SettingsObserver>,
3282        event: &SettingsObserverEvent,
3283        cx: &mut Context<Self>,
3284    ) {
3285        match event {
3286            SettingsObserverEvent::LocalSettingsUpdated(result) => match result {
3287                Err(InvalidSettingsError::LocalSettings { message, path }) => {
3288                    let message = format!("Failed to set local settings in {path:?}:\n{message}");
3289                    cx.emit(Event::Toast {
3290                        notification_id: format!("local-settings-{path:?}").into(),
3291                        message,
3292                    });
3293                }
3294                Ok(path) => cx.emit(Event::HideToast {
3295                    notification_id: format!("local-settings-{path:?}").into(),
3296                }),
3297                Err(_) => {}
3298            },
3299            SettingsObserverEvent::LocalTasksUpdated(result) => match result {
3300                Err(InvalidSettingsError::Tasks { message, path }) => {
3301                    let message = format!("Failed to set local tasks in {path:?}:\n{message}");
3302                    cx.emit(Event::Toast {
3303                        notification_id: format!("local-tasks-{path:?}").into(),
3304                        message,
3305                    });
3306                }
3307                Ok(path) => cx.emit(Event::HideToast {
3308                    notification_id: format!("local-tasks-{path:?}").into(),
3309                }),
3310                Err(_) => {}
3311            },
3312            SettingsObserverEvent::LocalDebugScenariosUpdated(result) => match result {
3313                Err(InvalidSettingsError::Debug { message, path }) => {
3314                    let message =
3315                        format!("Failed to set local debug scenarios in {path:?}:\n{message}");
3316                    cx.emit(Event::Toast {
3317                        notification_id: format!("local-debug-scenarios-{path:?}").into(),
3318                        message,
3319                    });
3320                }
3321                Ok(path) => cx.emit(Event::HideToast {
3322                    notification_id: format!("local-debug-scenarios-{path:?}").into(),
3323                }),
3324                Err(_) => {}
3325            },
3326        }
3327    }
3328
3329    fn on_worktree_store_event(
3330        &mut self,
3331        _: Entity<WorktreeStore>,
3332        event: &WorktreeStoreEvent,
3333        cx: &mut Context<Self>,
3334    ) {
3335        match event {
3336            WorktreeStoreEvent::WorktreeAdded(worktree) => {
3337                self.on_worktree_added(worktree, cx);
3338                cx.emit(Event::WorktreeAdded(worktree.read(cx).id()));
3339            }
3340            WorktreeStoreEvent::WorktreeRemoved(_, id) => {
3341                cx.emit(Event::WorktreeRemoved(*id));
3342            }
3343            WorktreeStoreEvent::WorktreeReleased(_, id) => {
3344                self.on_worktree_released(*id, cx);
3345            }
3346            WorktreeStoreEvent::WorktreeOrderChanged => cx.emit(Event::WorktreeOrderChanged),
3347            WorktreeStoreEvent::WorktreeUpdateSent(_) => {}
3348            WorktreeStoreEvent::WorktreeUpdatedEntries(worktree_id, changes) => {
3349                self.client()
3350                    .telemetry()
3351                    .report_discovered_project_type_events(*worktree_id, changes);
3352                cx.emit(Event::WorktreeUpdatedEntries(*worktree_id, changes.clone()))
3353            }
3354            WorktreeStoreEvent::WorktreeDeletedEntry(worktree_id, id) => {
3355                cx.emit(Event::DeletedEntry(*worktree_id, *id))
3356            }
3357            // Listen to the GitStore instead.
3358            WorktreeStoreEvent::WorktreeUpdatedGitRepositories(_, _) => {}
3359        }
3360    }
3361
3362    fn on_worktree_added(&mut self, worktree: &Entity<Worktree>, _: &mut Context<Self>) {
3363        let mut remotely_created_models = self.remotely_created_models.lock();
3364        if remotely_created_models.retain_count > 0 {
3365            remotely_created_models.worktrees.push(worktree.clone())
3366        }
3367    }
3368
3369    fn on_worktree_released(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
3370        if let Some(remote) = &self.remote_client {
3371            remote
3372                .read(cx)
3373                .proto_client()
3374                .send(proto::RemoveWorktree {
3375                    worktree_id: id_to_remove.to_proto(),
3376                })
3377                .log_err();
3378        }
3379    }
3380
3381    fn on_buffer_event(
3382        &mut self,
3383        buffer: Entity<Buffer>,
3384        event: &BufferEvent,
3385        cx: &mut Context<Self>,
3386    ) -> Option<()> {
3387        if matches!(event, BufferEvent::Edited | BufferEvent::Reloaded) {
3388            self.request_buffer_diff_recalculation(&buffer, cx);
3389        }
3390
3391        let buffer_id = buffer.read(cx).remote_id();
3392        match event {
3393            BufferEvent::ReloadNeeded => {
3394                if !self.is_via_collab() {
3395                    self.reload_buffers([buffer.clone()].into_iter().collect(), true, cx)
3396                        .detach_and_log_err(cx);
3397                }
3398            }
3399            BufferEvent::Operation {
3400                operation,
3401                is_local: true,
3402            } => {
3403                let operation = language::proto::serialize_operation(operation);
3404
3405                if let Some(remote) = &self.remote_client {
3406                    remote
3407                        .read(cx)
3408                        .proto_client()
3409                        .send(proto::UpdateBuffer {
3410                            project_id: 0,
3411                            buffer_id: buffer_id.to_proto(),
3412                            operations: vec![operation.clone()],
3413                        })
3414                        .ok();
3415                }
3416
3417                self.enqueue_buffer_ordered_message(BufferOrderedMessage::Operation {
3418                    buffer_id,
3419                    operation,
3420                })
3421                .ok();
3422            }
3423
3424            _ => {}
3425        }
3426
3427        None
3428    }
3429
3430    fn on_image_event(
3431        &mut self,
3432        image: Entity<ImageItem>,
3433        event: &ImageItemEvent,
3434        cx: &mut Context<Self>,
3435    ) -> Option<()> {
3436        // TODO: handle image events from remote
3437        if let ImageItemEvent::ReloadNeeded = event
3438            && !self.is_via_collab()
3439        {
3440            self.reload_images([image].into_iter().collect(), cx)
3441                .detach_and_log_err(cx);
3442        }
3443
3444        None
3445    }
3446
3447    fn request_buffer_diff_recalculation(
3448        &mut self,
3449        buffer: &Entity<Buffer>,
3450        cx: &mut Context<Self>,
3451    ) {
3452        self.buffers_needing_diff.insert(buffer.downgrade());
3453        let first_insertion = self.buffers_needing_diff.len() == 1;
3454        let settings = ProjectSettings::get_global(cx);
3455        let delay = settings.git.gutter_debounce;
3456
3457        if delay == 0 {
3458            if first_insertion {
3459                let this = cx.weak_entity();
3460                cx.defer(move |cx| {
3461                    if let Some(this) = this.upgrade() {
3462                        this.update(cx, |this, cx| {
3463                            this.recalculate_buffer_diffs(cx).detach();
3464                        });
3465                    }
3466                });
3467            }
3468            return;
3469        }
3470
3471        const MIN_DELAY: u64 = 50;
3472        let delay = delay.max(MIN_DELAY);
3473        let duration = Duration::from_millis(delay);
3474
3475        self.git_diff_debouncer
3476            .fire_new(duration, cx, move |this, cx| {
3477                this.recalculate_buffer_diffs(cx)
3478            });
3479    }
3480
3481    fn recalculate_buffer_diffs(&mut self, cx: &mut Context<Self>) -> Task<()> {
3482        cx.spawn(async move |this, cx| {
3483            loop {
3484                let task = this
3485                    .update(cx, |this, cx| {
3486                        let buffers = this
3487                            .buffers_needing_diff
3488                            .drain()
3489                            .filter_map(|buffer| buffer.upgrade())
3490                            .collect::<Vec<_>>();
3491                        if buffers.is_empty() {
3492                            None
3493                        } else {
3494                            Some(this.git_store.update(cx, |git_store, cx| {
3495                                git_store.recalculate_buffer_diffs(buffers, cx)
3496                            }))
3497                        }
3498                    })
3499                    .ok()
3500                    .flatten();
3501
3502                if let Some(task) = task {
3503                    task.await;
3504                } else {
3505                    break;
3506                }
3507            }
3508        })
3509    }
3510
3511    pub fn set_language_for_buffer(
3512        &mut self,
3513        buffer: &Entity<Buffer>,
3514        new_language: Arc<Language>,
3515        cx: &mut Context<Self>,
3516    ) {
3517        self.lsp_store.update(cx, |lsp_store, cx| {
3518            lsp_store.set_language_for_buffer(buffer, new_language, cx)
3519        })
3520    }
3521
3522    pub fn restart_language_servers_for_buffers(
3523        &mut self,
3524        buffers: Vec<Entity<Buffer>>,
3525        only_restart_servers: HashSet<LanguageServerSelector>,
3526        cx: &mut Context<Self>,
3527    ) {
3528        self.lsp_store.update(cx, |lsp_store, cx| {
3529            lsp_store.restart_language_servers_for_buffers(buffers, only_restart_servers, cx)
3530        })
3531    }
3532
3533    pub fn stop_language_servers_for_buffers(
3534        &mut self,
3535        buffers: Vec<Entity<Buffer>>,
3536        also_restart_servers: HashSet<LanguageServerSelector>,
3537        cx: &mut Context<Self>,
3538    ) {
3539        self.lsp_store
3540            .update(cx, |lsp_store, cx| {
3541                lsp_store.stop_language_servers_for_buffers(buffers, also_restart_servers, cx)
3542            })
3543            .detach_and_log_err(cx);
3544    }
3545
3546    pub fn cancel_language_server_work_for_buffers(
3547        &mut self,
3548        buffers: impl IntoIterator<Item = Entity<Buffer>>,
3549        cx: &mut Context<Self>,
3550    ) {
3551        self.lsp_store.update(cx, |lsp_store, cx| {
3552            lsp_store.cancel_language_server_work_for_buffers(buffers, cx)
3553        })
3554    }
3555
3556    pub fn cancel_language_server_work(
3557        &mut self,
3558        server_id: LanguageServerId,
3559        token_to_cancel: Option<ProgressToken>,
3560        cx: &mut Context<Self>,
3561    ) {
3562        self.lsp_store.update(cx, |lsp_store, cx| {
3563            lsp_store.cancel_language_server_work(server_id, token_to_cancel, cx)
3564        })
3565    }
3566
3567    fn enqueue_buffer_ordered_message(&mut self, message: BufferOrderedMessage) -> Result<()> {
3568        self.buffer_ordered_messages_tx
3569            .unbounded_send(message)
3570            .map_err(|e| anyhow!(e))
3571    }
3572
3573    pub fn available_toolchains(
3574        &self,
3575        path: ProjectPath,
3576        language_name: LanguageName,
3577        cx: &App,
3578    ) -> Task<Option<Toolchains>> {
3579        if let Some(toolchain_store) = self.toolchain_store.as_ref().map(Entity::downgrade) {
3580            cx.spawn(async move |cx| {
3581                toolchain_store
3582                    .update(cx, |this, cx| this.list_toolchains(path, language_name, cx))
3583                    .ok()?
3584                    .await
3585            })
3586        } else {
3587            Task::ready(None)
3588        }
3589    }
3590
3591    pub async fn toolchain_metadata(
3592        languages: Arc<LanguageRegistry>,
3593        language_name: LanguageName,
3594    ) -> Option<ToolchainMetadata> {
3595        languages
3596            .language_for_name(language_name.as_ref())
3597            .await
3598            .ok()?
3599            .toolchain_lister()
3600            .map(|lister| lister.meta())
3601    }
3602
3603    pub fn add_toolchain(
3604        &self,
3605        toolchain: Toolchain,
3606        scope: ToolchainScope,
3607        cx: &mut Context<Self>,
3608    ) {
3609        maybe!({
3610            self.toolchain_store.as_ref()?.update(cx, |this, cx| {
3611                this.add_toolchain(toolchain, scope, cx);
3612            });
3613            Some(())
3614        });
3615    }
3616
3617    pub fn remove_toolchain(
3618        &self,
3619        toolchain: Toolchain,
3620        scope: ToolchainScope,
3621        cx: &mut Context<Self>,
3622    ) {
3623        maybe!({
3624            self.toolchain_store.as_ref()?.update(cx, |this, cx| {
3625                this.remove_toolchain(toolchain, scope, cx);
3626            });
3627            Some(())
3628        });
3629    }
3630
3631    pub fn user_toolchains(
3632        &self,
3633        cx: &App,
3634    ) -> Option<BTreeMap<ToolchainScope, IndexSet<Toolchain>>> {
3635        Some(self.toolchain_store.as_ref()?.read(cx).user_toolchains())
3636    }
3637
3638    pub fn resolve_toolchain(
3639        &self,
3640        path: PathBuf,
3641        language_name: LanguageName,
3642        cx: &App,
3643    ) -> Task<Result<Toolchain>> {
3644        if let Some(toolchain_store) = self.toolchain_store.as_ref().map(Entity::downgrade) {
3645            cx.spawn(async move |cx| {
3646                toolchain_store
3647                    .update(cx, |this, cx| {
3648                        this.resolve_toolchain(path, language_name, cx)
3649                    })?
3650                    .await
3651            })
3652        } else {
3653            Task::ready(Err(anyhow!("This project does not support toolchains")))
3654        }
3655    }
3656
3657    pub fn toolchain_store(&self) -> Option<Entity<ToolchainStore>> {
3658        self.toolchain_store.clone()
3659    }
3660    pub fn activate_toolchain(
3661        &self,
3662        path: ProjectPath,
3663        toolchain: Toolchain,
3664        cx: &mut App,
3665    ) -> Task<Option<()>> {
3666        let Some(toolchain_store) = self.toolchain_store.clone() else {
3667            return Task::ready(None);
3668        };
3669        toolchain_store.update(cx, |this, cx| this.activate_toolchain(path, toolchain, cx))
3670    }
3671    pub fn active_toolchain(
3672        &self,
3673        path: ProjectPath,
3674        language_name: LanguageName,
3675        cx: &App,
3676    ) -> Task<Option<Toolchain>> {
3677        let Some(toolchain_store) = self.toolchain_store.clone() else {
3678            return Task::ready(None);
3679        };
3680        toolchain_store
3681            .read(cx)
3682            .active_toolchain(path, language_name, cx)
3683    }
3684    pub fn language_server_statuses<'a>(
3685        &'a self,
3686        cx: &'a App,
3687    ) -> impl DoubleEndedIterator<Item = (LanguageServerId, &'a LanguageServerStatus)> {
3688        self.lsp_store.read(cx).language_server_statuses()
3689    }
3690
3691    pub fn last_formatting_failure<'a>(&self, cx: &'a App) -> Option<&'a str> {
3692        self.lsp_store.read(cx).last_formatting_failure()
3693    }
3694
3695    pub fn reset_last_formatting_failure(&self, cx: &mut App) {
3696        self.lsp_store
3697            .update(cx, |store, _| store.reset_last_formatting_failure());
3698    }
3699
3700    pub fn reload_buffers(
3701        &self,
3702        buffers: HashSet<Entity<Buffer>>,
3703        push_to_history: bool,
3704        cx: &mut Context<Self>,
3705    ) -> Task<Result<ProjectTransaction>> {
3706        self.buffer_store.update(cx, |buffer_store, cx| {
3707            buffer_store.reload_buffers(buffers, push_to_history, cx)
3708        })
3709    }
3710
3711    pub fn reload_images(
3712        &self,
3713        images: HashSet<Entity<ImageItem>>,
3714        cx: &mut Context<Self>,
3715    ) -> Task<Result<()>> {
3716        self.image_store
3717            .update(cx, |image_store, cx| image_store.reload_images(images, cx))
3718    }
3719
3720    pub fn format(
3721        &mut self,
3722        buffers: HashSet<Entity<Buffer>>,
3723        target: LspFormatTarget,
3724        push_to_history: bool,
3725        trigger: lsp_store::FormatTrigger,
3726        cx: &mut Context<Project>,
3727    ) -> Task<anyhow::Result<ProjectTransaction>> {
3728        self.lsp_store.update(cx, |lsp_store, cx| {
3729            lsp_store.format(buffers, target, push_to_history, trigger, cx)
3730        })
3731    }
3732
3733    pub fn definitions<T: ToPointUtf16>(
3734        &mut self,
3735        buffer: &Entity<Buffer>,
3736        position: T,
3737        cx: &mut Context<Self>,
3738    ) -> Task<Result<Option<Vec<LocationLink>>>> {
3739        let position = position.to_point_utf16(buffer.read(cx));
3740        let guard = self.retain_remotely_created_models(cx);
3741        let task = self.lsp_store.update(cx, |lsp_store, cx| {
3742            lsp_store.definitions(buffer, position, cx)
3743        });
3744        cx.background_spawn(async move {
3745            let result = task.await;
3746            drop(guard);
3747            result
3748        })
3749    }
3750
3751    pub fn declarations<T: ToPointUtf16>(
3752        &mut self,
3753        buffer: &Entity<Buffer>,
3754        position: T,
3755        cx: &mut Context<Self>,
3756    ) -> Task<Result<Option<Vec<LocationLink>>>> {
3757        let position = position.to_point_utf16(buffer.read(cx));
3758        let guard = self.retain_remotely_created_models(cx);
3759        let task = self.lsp_store.update(cx, |lsp_store, cx| {
3760            lsp_store.declarations(buffer, position, cx)
3761        });
3762        cx.background_spawn(async move {
3763            let result = task.await;
3764            drop(guard);
3765            result
3766        })
3767    }
3768
3769    pub fn type_definitions<T: ToPointUtf16>(
3770        &mut self,
3771        buffer: &Entity<Buffer>,
3772        position: T,
3773        cx: &mut Context<Self>,
3774    ) -> Task<Result<Option<Vec<LocationLink>>>> {
3775        let position = position.to_point_utf16(buffer.read(cx));
3776        let guard = self.retain_remotely_created_models(cx);
3777        let task = self.lsp_store.update(cx, |lsp_store, cx| {
3778            lsp_store.type_definitions(buffer, position, cx)
3779        });
3780        cx.background_spawn(async move {
3781            let result = task.await;
3782            drop(guard);
3783            result
3784        })
3785    }
3786
3787    pub fn implementations<T: ToPointUtf16>(
3788        &mut self,
3789        buffer: &Entity<Buffer>,
3790        position: T,
3791        cx: &mut Context<Self>,
3792    ) -> Task<Result<Option<Vec<LocationLink>>>> {
3793        let position = position.to_point_utf16(buffer.read(cx));
3794        let guard = self.retain_remotely_created_models(cx);
3795        let task = self.lsp_store.update(cx, |lsp_store, cx| {
3796            lsp_store.implementations(buffer, position, cx)
3797        });
3798        cx.background_spawn(async move {
3799            let result = task.await;
3800            drop(guard);
3801            result
3802        })
3803    }
3804
3805    pub fn references<T: ToPointUtf16>(
3806        &mut self,
3807        buffer: &Entity<Buffer>,
3808        position: T,
3809        cx: &mut Context<Self>,
3810    ) -> Task<Result<Option<Vec<Location>>>> {
3811        let position = position.to_point_utf16(buffer.read(cx));
3812        let guard = self.retain_remotely_created_models(cx);
3813        let task = self.lsp_store.update(cx, |lsp_store, cx| {
3814            lsp_store.references(buffer, position, cx)
3815        });
3816        cx.background_spawn(async move {
3817            let result = task.await;
3818            drop(guard);
3819            result
3820        })
3821    }
3822
3823    pub fn document_highlights<T: ToPointUtf16>(
3824        &mut self,
3825        buffer: &Entity<Buffer>,
3826        position: T,
3827        cx: &mut Context<Self>,
3828    ) -> Task<Result<Vec<DocumentHighlight>>> {
3829        let position = position.to_point_utf16(buffer.read(cx));
3830        self.request_lsp(
3831            buffer.clone(),
3832            LanguageServerToQuery::FirstCapable,
3833            GetDocumentHighlights { position },
3834            cx,
3835        )
3836    }
3837
3838    pub fn document_symbols(
3839        &mut self,
3840        buffer: &Entity<Buffer>,
3841        cx: &mut Context<Self>,
3842    ) -> Task<Result<Vec<DocumentSymbol>>> {
3843        self.request_lsp(
3844            buffer.clone(),
3845            LanguageServerToQuery::FirstCapable,
3846            GetDocumentSymbols,
3847            cx,
3848        )
3849    }
3850
3851    pub fn symbols(&self, query: &str, cx: &mut Context<Self>) -> Task<Result<Vec<Symbol>>> {
3852        self.lsp_store
3853            .update(cx, |lsp_store, cx| lsp_store.symbols(query, cx))
3854    }
3855
3856    pub fn open_buffer_for_symbol(
3857        &mut self,
3858        symbol: &Symbol,
3859        cx: &mut Context<Self>,
3860    ) -> Task<Result<Entity<Buffer>>> {
3861        self.lsp_store.update(cx, |lsp_store, cx| {
3862            lsp_store.open_buffer_for_symbol(symbol, cx)
3863        })
3864    }
3865
3866    pub fn open_server_settings(&mut self, cx: &mut Context<Self>) -> Task<Result<Entity<Buffer>>> {
3867        let guard = self.retain_remotely_created_models(cx);
3868        let Some(remote) = self.remote_client.as_ref() else {
3869            return Task::ready(Err(anyhow!("not an ssh project")));
3870        };
3871
3872        let proto_client = remote.read(cx).proto_client();
3873
3874        cx.spawn(async move |project, cx| {
3875            let buffer = proto_client
3876                .request(proto::OpenServerSettings {
3877                    project_id: REMOTE_SERVER_PROJECT_ID,
3878                })
3879                .await?;
3880
3881            let buffer = project
3882                .update(cx, |project, cx| {
3883                    project.buffer_store.update(cx, |buffer_store, cx| {
3884                        anyhow::Ok(
3885                            buffer_store
3886                                .wait_for_remote_buffer(BufferId::new(buffer.buffer_id)?, cx),
3887                        )
3888                    })
3889                })??
3890                .await;
3891
3892            drop(guard);
3893            buffer
3894        })
3895    }
3896
3897    pub fn open_local_buffer_via_lsp(
3898        &mut self,
3899        abs_path: lsp::Uri,
3900        language_server_id: LanguageServerId,
3901        cx: &mut Context<Self>,
3902    ) -> Task<Result<Entity<Buffer>>> {
3903        self.lsp_store.update(cx, |lsp_store, cx| {
3904            lsp_store.open_local_buffer_via_lsp(abs_path, language_server_id, cx)
3905        })
3906    }
3907
3908    pub fn hover<T: ToPointUtf16>(
3909        &self,
3910        buffer: &Entity<Buffer>,
3911        position: T,
3912        cx: &mut Context<Self>,
3913    ) -> Task<Option<Vec<Hover>>> {
3914        let position = position.to_point_utf16(buffer.read(cx));
3915        self.lsp_store
3916            .update(cx, |lsp_store, cx| lsp_store.hover(buffer, position, cx))
3917    }
3918
3919    pub fn linked_edits(
3920        &self,
3921        buffer: &Entity<Buffer>,
3922        position: Anchor,
3923        cx: &mut Context<Self>,
3924    ) -> Task<Result<Vec<Range<Anchor>>>> {
3925        self.lsp_store.update(cx, |lsp_store, cx| {
3926            lsp_store.linked_edits(buffer, position, cx)
3927        })
3928    }
3929
3930    pub fn completions<T: ToOffset + ToPointUtf16>(
3931        &self,
3932        buffer: &Entity<Buffer>,
3933        position: T,
3934        context: CompletionContext,
3935        cx: &mut Context<Self>,
3936    ) -> Task<Result<Vec<CompletionResponse>>> {
3937        let position = position.to_point_utf16(buffer.read(cx));
3938        self.lsp_store.update(cx, |lsp_store, cx| {
3939            lsp_store.completions(buffer, position, context, cx)
3940        })
3941    }
3942
3943    pub fn code_actions<T: Clone + ToOffset>(
3944        &mut self,
3945        buffer_handle: &Entity<Buffer>,
3946        range: Range<T>,
3947        kinds: Option<Vec<CodeActionKind>>,
3948        cx: &mut Context<Self>,
3949    ) -> Task<Result<Option<Vec<CodeAction>>>> {
3950        let buffer = buffer_handle.read(cx);
3951        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
3952        self.lsp_store.update(cx, |lsp_store, cx| {
3953            lsp_store.code_actions(buffer_handle, range, kinds, cx)
3954        })
3955    }
3956
3957    pub fn code_lens_actions<T: Clone + ToOffset>(
3958        &mut self,
3959        buffer: &Entity<Buffer>,
3960        range: Range<T>,
3961        cx: &mut Context<Self>,
3962    ) -> Task<Result<Option<Vec<CodeAction>>>> {
3963        let snapshot = buffer.read(cx).snapshot();
3964        let range = range.to_point(&snapshot);
3965        let range_start = snapshot.anchor_before(range.start);
3966        let range_end = if range.start == range.end {
3967            range_start
3968        } else {
3969            snapshot.anchor_after(range.end)
3970        };
3971        let range = range_start..range_end;
3972        let code_lens_actions = self
3973            .lsp_store
3974            .update(cx, |lsp_store, cx| lsp_store.code_lens_actions(buffer, cx));
3975
3976        cx.background_spawn(async move {
3977            let mut code_lens_actions = code_lens_actions
3978                .await
3979                .map_err(|e| anyhow!("code lens fetch failed: {e:#}"))?;
3980            if let Some(code_lens_actions) = &mut code_lens_actions {
3981                code_lens_actions.retain(|code_lens_action| {
3982                    range
3983                        .start
3984                        .cmp(&code_lens_action.range.start, &snapshot)
3985                        .is_ge()
3986                        && range
3987                            .end
3988                            .cmp(&code_lens_action.range.end, &snapshot)
3989                            .is_le()
3990                });
3991            }
3992            Ok(code_lens_actions)
3993        })
3994    }
3995
3996    pub fn apply_code_action(
3997        &self,
3998        buffer_handle: Entity<Buffer>,
3999        action: CodeAction,
4000        push_to_history: bool,
4001        cx: &mut Context<Self>,
4002    ) -> Task<Result<ProjectTransaction>> {
4003        self.lsp_store.update(cx, |lsp_store, cx| {
4004            lsp_store.apply_code_action(buffer_handle, action, push_to_history, cx)
4005        })
4006    }
4007
4008    pub fn apply_code_action_kind(
4009        &self,
4010        buffers: HashSet<Entity<Buffer>>,
4011        kind: CodeActionKind,
4012        push_to_history: bool,
4013        cx: &mut Context<Self>,
4014    ) -> Task<Result<ProjectTransaction>> {
4015        self.lsp_store.update(cx, |lsp_store, cx| {
4016            lsp_store.apply_code_action_kind(buffers, kind, push_to_history, cx)
4017        })
4018    }
4019
4020    pub fn prepare_rename<T: ToPointUtf16>(
4021        &mut self,
4022        buffer: Entity<Buffer>,
4023        position: T,
4024        cx: &mut Context<Self>,
4025    ) -> Task<Result<PrepareRenameResponse>> {
4026        let position = position.to_point_utf16(buffer.read(cx));
4027        self.request_lsp(
4028            buffer,
4029            LanguageServerToQuery::FirstCapable,
4030            PrepareRename { position },
4031            cx,
4032        )
4033    }
4034
4035    pub fn perform_rename<T: ToPointUtf16>(
4036        &mut self,
4037        buffer: Entity<Buffer>,
4038        position: T,
4039        new_name: String,
4040        cx: &mut Context<Self>,
4041    ) -> Task<Result<ProjectTransaction>> {
4042        let push_to_history = true;
4043        let position = position.to_point_utf16(buffer.read(cx));
4044        self.request_lsp(
4045            buffer,
4046            LanguageServerToQuery::FirstCapable,
4047            PerformRename {
4048                position,
4049                new_name,
4050                push_to_history,
4051            },
4052            cx,
4053        )
4054    }
4055
4056    pub fn on_type_format<T: ToPointUtf16>(
4057        &mut self,
4058        buffer: Entity<Buffer>,
4059        position: T,
4060        trigger: String,
4061        push_to_history: bool,
4062        cx: &mut Context<Self>,
4063    ) -> Task<Result<Option<Transaction>>> {
4064        self.lsp_store.update(cx, |lsp_store, cx| {
4065            lsp_store.on_type_format(buffer, position, trigger, push_to_history, cx)
4066        })
4067    }
4068
4069    pub fn inline_values(
4070        &mut self,
4071        session: Entity<Session>,
4072        active_stack_frame: ActiveStackFrame,
4073        buffer_handle: Entity<Buffer>,
4074        range: Range<text::Anchor>,
4075        cx: &mut Context<Self>,
4076    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
4077        let snapshot = buffer_handle.read(cx).snapshot();
4078
4079        let captures =
4080            snapshot.debug_variables_query(Anchor::min_for_buffer(snapshot.remote_id())..range.end);
4081
4082        let row = snapshot
4083            .summary_for_anchor::<text::PointUtf16>(&range.end)
4084            .row as usize;
4085
4086        let inline_value_locations = provide_inline_values(captures, &snapshot, row);
4087
4088        let stack_frame_id = active_stack_frame.stack_frame_id;
4089        cx.spawn(async move |this, cx| {
4090            this.update(cx, |project, cx| {
4091                project.dap_store().update(cx, |dap_store, cx| {
4092                    dap_store.resolve_inline_value_locations(
4093                        session,
4094                        stack_frame_id,
4095                        buffer_handle,
4096                        inline_value_locations,
4097                        cx,
4098                    )
4099                })
4100            })?
4101            .await
4102        })
4103    }
4104
4105    fn search_impl(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> SearchResultsHandle {
4106        let client: Option<(AnyProtoClient, _)> = if let Some(ssh_client) = &self.remote_client {
4107            Some((ssh_client.read(cx).proto_client(), 0))
4108        } else if let Some(remote_id) = self.remote_id() {
4109            self.is_local()
4110                .not()
4111                .then(|| (self.collab_client.clone().into(), remote_id))
4112        } else {
4113            None
4114        };
4115        let searcher = if query.is_opened_only() {
4116            project_search::Search::open_buffers_only(
4117                self.buffer_store.clone(),
4118                self.worktree_store.clone(),
4119                project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4120            )
4121        } else {
4122            match client {
4123                Some((client, remote_id)) => project_search::Search::remote(
4124                    self.buffer_store.clone(),
4125                    self.worktree_store.clone(),
4126                    project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4127                    (client, remote_id, self.remotely_created_models.clone()),
4128                ),
4129                None => project_search::Search::local(
4130                    self.fs.clone(),
4131                    self.buffer_store.clone(),
4132                    self.worktree_store.clone(),
4133                    project_search::Search::MAX_SEARCH_RESULT_FILES + 1,
4134                    cx,
4135                ),
4136            }
4137        };
4138        searcher.into_handle(query, cx)
4139    }
4140
4141    pub fn search(&mut self, query: SearchQuery, cx: &mut Context<Self>) -> Receiver<SearchResult> {
4142        self.search_impl(query, cx).results(cx)
4143    }
4144
4145    pub fn request_lsp<R: LspCommand>(
4146        &mut self,
4147        buffer_handle: Entity<Buffer>,
4148        server: LanguageServerToQuery,
4149        request: R,
4150        cx: &mut Context<Self>,
4151    ) -> Task<Result<R::Response>>
4152    where
4153        <R::LspRequest as lsp::request::Request>::Result: Send,
4154        <R::LspRequest as lsp::request::Request>::Params: Send,
4155    {
4156        let guard = self.retain_remotely_created_models(cx);
4157        let task = self.lsp_store.update(cx, |lsp_store, cx| {
4158            lsp_store.request_lsp(buffer_handle, server, request, cx)
4159        });
4160        cx.background_spawn(async move {
4161            let result = task.await;
4162            drop(guard);
4163            result
4164        })
4165    }
4166
4167    /// Move a worktree to a new position in the worktree order.
4168    ///
4169    /// The worktree will moved to the opposite side of the destination worktree.
4170    ///
4171    /// # Example
4172    ///
4173    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `33`,
4174    /// worktree_order will be updated to produce the indexes `[11, 33, 22]`.
4175    ///
4176    /// Given the worktree order `[11, 22, 33]` and a call to move worktree `22` to `11`,
4177    /// worktree_order will be updated to produce the indexes `[22, 11, 33]`.
4178    ///
4179    /// # Errors
4180    ///
4181    /// An error will be returned if the worktree or destination worktree are not found.
4182    pub fn move_worktree(
4183        &mut self,
4184        source: WorktreeId,
4185        destination: WorktreeId,
4186        cx: &mut Context<Self>,
4187    ) -> Result<()> {
4188        self.worktree_store.update(cx, |worktree_store, cx| {
4189            worktree_store.move_worktree(source, destination, cx)
4190        })
4191    }
4192
4193    pub fn find_or_create_worktree(
4194        &mut self,
4195        abs_path: impl AsRef<Path>,
4196        visible: bool,
4197        cx: &mut Context<Self>,
4198    ) -> Task<Result<(Entity<Worktree>, Arc<RelPath>)>> {
4199        self.worktree_store.update(cx, |worktree_store, cx| {
4200            worktree_store.find_or_create_worktree(abs_path, visible, cx)
4201        })
4202    }
4203
4204    pub fn find_worktree(
4205        &self,
4206        abs_path: &Path,
4207        cx: &App,
4208    ) -> Option<(Entity<Worktree>, Arc<RelPath>)> {
4209        self.worktree_store.read(cx).find_worktree(abs_path, cx)
4210    }
4211
4212    pub fn is_shared(&self) -> bool {
4213        match &self.client_state {
4214            ProjectClientState::Shared { .. } => true,
4215            ProjectClientState::Local => false,
4216            ProjectClientState::Remote { .. } => true,
4217        }
4218    }
4219
4220    /// Returns the resolved version of `path`, that was found in `buffer`, if it exists.
4221    pub fn resolve_path_in_buffer(
4222        &self,
4223        path: &str,
4224        buffer: &Entity<Buffer>,
4225        cx: &mut Context<Self>,
4226    ) -> Task<Option<ResolvedPath>> {
4227        if util::paths::is_absolute(path, self.path_style(cx)) || path.starts_with("~") {
4228            self.resolve_abs_path(path, cx)
4229        } else {
4230            self.resolve_path_in_worktrees(path, buffer, cx)
4231        }
4232    }
4233
4234    pub fn resolve_abs_file_path(
4235        &self,
4236        path: &str,
4237        cx: &mut Context<Self>,
4238    ) -> Task<Option<ResolvedPath>> {
4239        let resolve_task = self.resolve_abs_path(path, cx);
4240        cx.background_spawn(async move {
4241            let resolved_path = resolve_task.await;
4242            resolved_path.filter(|path| path.is_file())
4243        })
4244    }
4245
4246    pub fn resolve_abs_path(&self, path: &str, cx: &App) -> Task<Option<ResolvedPath>> {
4247        if self.is_local() {
4248            let expanded = PathBuf::from(shellexpand::tilde(&path).into_owned());
4249            let fs = self.fs.clone();
4250            cx.background_spawn(async move {
4251                let metadata = fs.metadata(&expanded).await.ok().flatten();
4252
4253                metadata.map(|metadata| ResolvedPath::AbsPath {
4254                    path: expanded.to_string_lossy().into_owned(),
4255                    is_dir: metadata.is_dir,
4256                })
4257            })
4258        } else if let Some(ssh_client) = self.remote_client.as_ref() {
4259            let request = ssh_client
4260                .read(cx)
4261                .proto_client()
4262                .request(proto::GetPathMetadata {
4263                    project_id: REMOTE_SERVER_PROJECT_ID,
4264                    path: path.into(),
4265                });
4266            cx.background_spawn(async move {
4267                let response = request.await.log_err()?;
4268                if response.exists {
4269                    Some(ResolvedPath::AbsPath {
4270                        path: response.path,
4271                        is_dir: response.is_dir,
4272                    })
4273                } else {
4274                    None
4275                }
4276            })
4277        } else {
4278            Task::ready(None)
4279        }
4280    }
4281
4282    fn resolve_path_in_worktrees(
4283        &self,
4284        path: &str,
4285        buffer: &Entity<Buffer>,
4286        cx: &mut Context<Self>,
4287    ) -> Task<Option<ResolvedPath>> {
4288        let mut candidates = vec![];
4289        let path_style = self.path_style(cx);
4290        if let Ok(path) = RelPath::new(path.as_ref(), path_style) {
4291            candidates.push(path.into_arc());
4292        }
4293
4294        if let Some(file) = buffer.read(cx).file()
4295            && let Some(dir) = file.path().parent()
4296        {
4297            if let Some(joined) = path_style.join(&*dir.display(path_style), path)
4298                && let Some(joined) = RelPath::new(joined.as_ref(), path_style).ok()
4299            {
4300                candidates.push(joined.into_arc());
4301            }
4302        }
4303
4304        let buffer_worktree_id = buffer.read(cx).file().map(|file| file.worktree_id(cx));
4305        let worktrees_with_ids: Vec<_> = self
4306            .worktrees(cx)
4307            .map(|worktree| {
4308                let id = worktree.read(cx).id();
4309                (worktree, id)
4310            })
4311            .collect();
4312
4313        cx.spawn(async move |_, cx| {
4314            if let Some(buffer_worktree_id) = buffer_worktree_id
4315                && let Some((worktree, _)) = worktrees_with_ids
4316                    .iter()
4317                    .find(|(_, id)| *id == buffer_worktree_id)
4318            {
4319                for candidate in candidates.iter() {
4320                    if let Some(path) = Self::resolve_path_in_worktree(worktree, candidate, cx) {
4321                        return Some(path);
4322                    }
4323                }
4324            }
4325            for (worktree, id) in worktrees_with_ids {
4326                if Some(id) == buffer_worktree_id {
4327                    continue;
4328                }
4329                for candidate in candidates.iter() {
4330                    if let Some(path) = Self::resolve_path_in_worktree(&worktree, candidate, cx) {
4331                        return Some(path);
4332                    }
4333                }
4334            }
4335            None
4336        })
4337    }
4338
4339    fn resolve_path_in_worktree(
4340        worktree: &Entity<Worktree>,
4341        path: &RelPath,
4342        cx: &mut AsyncApp,
4343    ) -> Option<ResolvedPath> {
4344        worktree
4345            .read_with(cx, |worktree, _| {
4346                worktree.entry_for_path(path).map(|entry| {
4347                    let project_path = ProjectPath {
4348                        worktree_id: worktree.id(),
4349                        path: entry.path.clone(),
4350                    };
4351                    ResolvedPath::ProjectPath {
4352                        project_path,
4353                        is_dir: entry.is_dir(),
4354                    }
4355                })
4356            })
4357            .ok()?
4358    }
4359
4360    pub fn list_directory(
4361        &self,
4362        query: String,
4363        cx: &mut Context<Self>,
4364    ) -> Task<Result<Vec<DirectoryItem>>> {
4365        if self.is_local() {
4366            DirectoryLister::Local(cx.entity(), self.fs.clone()).list_directory(query, cx)
4367        } else if let Some(session) = self.remote_client.as_ref() {
4368            let request = proto::ListRemoteDirectory {
4369                dev_server_id: REMOTE_SERVER_PROJECT_ID,
4370                path: query,
4371                config: Some(proto::ListRemoteDirectoryConfig { is_dir: true }),
4372            };
4373
4374            let response = session.read(cx).proto_client().request(request);
4375            cx.background_spawn(async move {
4376                let proto::ListRemoteDirectoryResponse {
4377                    entries,
4378                    entry_info,
4379                } = response.await?;
4380                Ok(entries
4381                    .into_iter()
4382                    .zip(entry_info)
4383                    .map(|(entry, info)| DirectoryItem {
4384                        path: PathBuf::from(entry),
4385                        is_dir: info.is_dir,
4386                    })
4387                    .collect())
4388            })
4389        } else {
4390            Task::ready(Err(anyhow!("cannot list directory in remote project")))
4391        }
4392    }
4393
4394    pub fn create_worktree(
4395        &mut self,
4396        abs_path: impl AsRef<Path>,
4397        visible: bool,
4398        cx: &mut Context<Self>,
4399    ) -> Task<Result<Entity<Worktree>>> {
4400        self.worktree_store.update(cx, |worktree_store, cx| {
4401            worktree_store.create_worktree(abs_path, visible, cx)
4402        })
4403    }
4404
4405    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut Context<Self>) {
4406        self.worktree_store.update(cx, |worktree_store, cx| {
4407            worktree_store.remove_worktree(id_to_remove, cx);
4408        });
4409    }
4410
4411    fn add_worktree(&mut self, worktree: &Entity<Worktree>, cx: &mut Context<Self>) {
4412        self.worktree_store.update(cx, |worktree_store, cx| {
4413            worktree_store.add(worktree, cx);
4414        });
4415    }
4416
4417    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut Context<Self>) {
4418        let new_active_entry = entry.and_then(|project_path| {
4419            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
4420            let entry = worktree.read(cx).entry_for_path(&project_path.path)?;
4421            Some(entry.id)
4422        });
4423        if new_active_entry != self.active_entry {
4424            self.active_entry = new_active_entry;
4425            self.lsp_store.update(cx, |lsp_store, _| {
4426                lsp_store.set_active_entry(new_active_entry);
4427            });
4428            cx.emit(Event::ActiveEntryChanged(new_active_entry));
4429        }
4430    }
4431
4432    pub fn language_servers_running_disk_based_diagnostics<'a>(
4433        &'a self,
4434        cx: &'a App,
4435    ) -> impl Iterator<Item = LanguageServerId> + 'a {
4436        self.lsp_store
4437            .read(cx)
4438            .language_servers_running_disk_based_diagnostics()
4439    }
4440
4441    pub fn diagnostic_summary(&self, include_ignored: bool, cx: &App) -> DiagnosticSummary {
4442        self.lsp_store
4443            .read(cx)
4444            .diagnostic_summary(include_ignored, cx)
4445    }
4446
4447    /// Returns a summary of the diagnostics for the provided project path only.
4448    pub fn diagnostic_summary_for_path(&self, path: &ProjectPath, cx: &App) -> DiagnosticSummary {
4449        self.lsp_store
4450            .read(cx)
4451            .diagnostic_summary_for_path(path, cx)
4452    }
4453
4454    pub fn diagnostic_summaries<'a>(
4455        &'a self,
4456        include_ignored: bool,
4457        cx: &'a App,
4458    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
4459        self.lsp_store
4460            .read(cx)
4461            .diagnostic_summaries(include_ignored, cx)
4462    }
4463
4464    pub fn active_entry(&self) -> Option<ProjectEntryId> {
4465        self.active_entry
4466    }
4467
4468    pub fn entry_for_path<'a>(&'a self, path: &ProjectPath, cx: &'a App) -> Option<&'a Entry> {
4469        self.worktree_store.read(cx).entry_for_path(path, cx)
4470    }
4471
4472    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &App) -> Option<ProjectPath> {
4473        let worktree = self.worktree_for_entry(entry_id, cx)?;
4474        let worktree = worktree.read(cx);
4475        let worktree_id = worktree.id();
4476        let path = worktree.entry_for_id(entry_id)?.path.clone();
4477        Some(ProjectPath { worktree_id, path })
4478    }
4479
4480    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4481        Some(
4482            self.worktree_for_id(project_path.worktree_id, cx)?
4483                .read(cx)
4484                .absolutize(&project_path.path),
4485        )
4486    }
4487
4488    /// Attempts to find a `ProjectPath` corresponding to the given path. If the path
4489    /// is a *full path*, meaning it starts with the root name of a worktree, we'll locate
4490    /// it in that worktree. Otherwise, we'll attempt to find it as a relative path in
4491    /// the first visible worktree that has an entry for that relative path.
4492    ///
4493    /// We use this to resolve edit steps, when there's a chance an LLM may omit the workree
4494    /// root name from paths.
4495    ///
4496    /// # Arguments
4497    ///
4498    /// * `path` - An absolute path, or a full path that starts with a worktree root name, or a
4499    ///   relative path within a visible worktree.
4500    /// * `cx` - A reference to the `AppContext`.
4501    ///
4502    /// # Returns
4503    ///
4504    /// Returns `Some(ProjectPath)` if a matching worktree is found, otherwise `None`.
4505    pub fn find_project_path(&self, path: impl AsRef<Path>, cx: &App) -> Option<ProjectPath> {
4506        let path_style = self.path_style(cx);
4507        let path = path.as_ref();
4508        let worktree_store = self.worktree_store.read(cx);
4509
4510        if is_absolute(&path.to_string_lossy(), path_style) {
4511            for worktree in worktree_store.visible_worktrees(cx) {
4512                let worktree_abs_path = worktree.read(cx).abs_path();
4513
4514                if let Ok(relative_path) = path.strip_prefix(worktree_abs_path)
4515                    && let Ok(path) = RelPath::new(relative_path, path_style)
4516                {
4517                    return Some(ProjectPath {
4518                        worktree_id: worktree.read(cx).id(),
4519                        path: path.into_arc(),
4520                    });
4521                }
4522            }
4523        } else {
4524            for worktree in worktree_store.visible_worktrees(cx) {
4525                let worktree_root_name = worktree.read(cx).root_name();
4526                if let Ok(relative_path) = path.strip_prefix(worktree_root_name.as_std_path())
4527                    && let Ok(path) = RelPath::new(relative_path, path_style)
4528                {
4529                    return Some(ProjectPath {
4530                        worktree_id: worktree.read(cx).id(),
4531                        path: path.into_arc(),
4532                    });
4533                }
4534            }
4535
4536            for worktree in worktree_store.visible_worktrees(cx) {
4537                let worktree = worktree.read(cx);
4538                if let Ok(path) = RelPath::new(path, path_style)
4539                    && let Some(entry) = worktree.entry_for_path(&path)
4540                {
4541                    return Some(ProjectPath {
4542                        worktree_id: worktree.id(),
4543                        path: entry.path.clone(),
4544                    });
4545                }
4546            }
4547        }
4548
4549        None
4550    }
4551
4552    /// If there's only one visible worktree, returns the given worktree-relative path with no prefix.
4553    ///
4554    /// Otherwise, returns the full path for the project path (obtained by prefixing the worktree-relative path with the name of the worktree).
4555    pub fn short_full_path_for_project_path(
4556        &self,
4557        project_path: &ProjectPath,
4558        cx: &App,
4559    ) -> Option<String> {
4560        let path_style = self.path_style(cx);
4561        if self.visible_worktrees(cx).take(2).count() < 2 {
4562            return Some(project_path.path.display(path_style).to_string());
4563        }
4564        self.worktree_for_id(project_path.worktree_id, cx)
4565            .map(|worktree| {
4566                let worktree_name = worktree.read(cx).root_name();
4567                worktree_name
4568                    .join(&project_path.path)
4569                    .display(path_style)
4570                    .to_string()
4571            })
4572    }
4573
4574    pub fn project_path_for_absolute_path(&self, abs_path: &Path, cx: &App) -> Option<ProjectPath> {
4575        self.find_worktree(abs_path, cx)
4576            .map(|(worktree, relative_path)| ProjectPath {
4577                worktree_id: worktree.read(cx).id(),
4578                path: relative_path,
4579            })
4580    }
4581
4582    pub fn get_workspace_root(&self, project_path: &ProjectPath, cx: &App) -> Option<PathBuf> {
4583        Some(
4584            self.worktree_for_id(project_path.worktree_id, cx)?
4585                .read(cx)
4586                .abs_path()
4587                .to_path_buf(),
4588        )
4589    }
4590
4591    pub fn blame_buffer(
4592        &self,
4593        buffer: &Entity<Buffer>,
4594        version: Option<clock::Global>,
4595        cx: &mut App,
4596    ) -> Task<Result<Option<Blame>>> {
4597        self.git_store.update(cx, |git_store, cx| {
4598            git_store.blame_buffer(buffer, version, cx)
4599        })
4600    }
4601
4602    pub fn get_permalink_to_line(
4603        &self,
4604        buffer: &Entity<Buffer>,
4605        selection: Range<u32>,
4606        cx: &mut App,
4607    ) -> Task<Result<url::Url>> {
4608        self.git_store.update(cx, |git_store, cx| {
4609            git_store.get_permalink_to_line(buffer, selection, cx)
4610        })
4611    }
4612
4613    // RPC message handlers
4614
4615    async fn handle_unshare_project(
4616        this: Entity<Self>,
4617        _: TypedEnvelope<proto::UnshareProject>,
4618        mut cx: AsyncApp,
4619    ) -> Result<()> {
4620        this.update(&mut cx, |this, cx| {
4621            if this.is_local() || this.is_via_remote_server() {
4622                this.unshare(cx)?;
4623            } else {
4624                this.disconnected_from_host(cx);
4625            }
4626            Ok(())
4627        })?
4628    }
4629
4630    async fn handle_add_collaborator(
4631        this: Entity<Self>,
4632        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
4633        mut cx: AsyncApp,
4634    ) -> Result<()> {
4635        let collaborator = envelope
4636            .payload
4637            .collaborator
4638            .take()
4639            .context("empty collaborator")?;
4640
4641        let collaborator = Collaborator::from_proto(collaborator)?;
4642        this.update(&mut cx, |this, cx| {
4643            this.buffer_store.update(cx, |buffer_store, _| {
4644                buffer_store.forget_shared_buffers_for(&collaborator.peer_id);
4645            });
4646            this.breakpoint_store.read(cx).broadcast();
4647            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
4648            this.collaborators
4649                .insert(collaborator.peer_id, collaborator);
4650        })?;
4651
4652        Ok(())
4653    }
4654
4655    async fn handle_update_project_collaborator(
4656        this: Entity<Self>,
4657        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
4658        mut cx: AsyncApp,
4659    ) -> Result<()> {
4660        let old_peer_id = envelope
4661            .payload
4662            .old_peer_id
4663            .context("missing old peer id")?;
4664        let new_peer_id = envelope
4665            .payload
4666            .new_peer_id
4667            .context("missing new peer id")?;
4668        this.update(&mut cx, |this, cx| {
4669            let collaborator = this
4670                .collaborators
4671                .remove(&old_peer_id)
4672                .context("received UpdateProjectCollaborator for unknown peer")?;
4673            let is_host = collaborator.is_host;
4674            this.collaborators.insert(new_peer_id, collaborator);
4675
4676            log::info!("peer {} became {}", old_peer_id, new_peer_id,);
4677            this.buffer_store.update(cx, |buffer_store, _| {
4678                buffer_store.update_peer_id(&old_peer_id, new_peer_id)
4679            });
4680
4681            if is_host {
4682                this.buffer_store
4683                    .update(cx, |buffer_store, _| buffer_store.discard_incomplete());
4684                this.enqueue_buffer_ordered_message(BufferOrderedMessage::Resync)
4685                    .unwrap();
4686                cx.emit(Event::HostReshared);
4687            }
4688
4689            cx.emit(Event::CollaboratorUpdated {
4690                old_peer_id,
4691                new_peer_id,
4692            });
4693            Ok(())
4694        })?
4695    }
4696
4697    async fn handle_remove_collaborator(
4698        this: Entity<Self>,
4699        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
4700        mut cx: AsyncApp,
4701    ) -> Result<()> {
4702        this.update(&mut cx, |this, cx| {
4703            let peer_id = envelope.payload.peer_id.context("invalid peer id")?;
4704            let replica_id = this
4705                .collaborators
4706                .remove(&peer_id)
4707                .with_context(|| format!("unknown peer {peer_id:?}"))?
4708                .replica_id;
4709            this.buffer_store.update(cx, |buffer_store, cx| {
4710                buffer_store.forget_shared_buffers_for(&peer_id);
4711                for buffer in buffer_store.buffers() {
4712                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
4713                }
4714            });
4715            this.git_store.update(cx, |git_store, _| {
4716                git_store.forget_shared_diffs_for(&peer_id);
4717            });
4718
4719            cx.emit(Event::CollaboratorLeft(peer_id));
4720            Ok(())
4721        })?
4722    }
4723
4724    async fn handle_update_project(
4725        this: Entity<Self>,
4726        envelope: TypedEnvelope<proto::UpdateProject>,
4727        mut cx: AsyncApp,
4728    ) -> Result<()> {
4729        this.update(&mut cx, |this, cx| {
4730            // Don't handle messages that were sent before the response to us joining the project
4731            if envelope.message_id > this.join_project_response_message_id {
4732                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
4733            }
4734            Ok(())
4735        })?
4736    }
4737
4738    async fn handle_toast(
4739        this: Entity<Self>,
4740        envelope: TypedEnvelope<proto::Toast>,
4741        mut cx: AsyncApp,
4742    ) -> Result<()> {
4743        this.update(&mut cx, |_, cx| {
4744            cx.emit(Event::Toast {
4745                notification_id: envelope.payload.notification_id.into(),
4746                message: envelope.payload.message,
4747            });
4748            Ok(())
4749        })?
4750    }
4751
4752    async fn handle_language_server_prompt_request(
4753        this: Entity<Self>,
4754        envelope: TypedEnvelope<proto::LanguageServerPromptRequest>,
4755        mut cx: AsyncApp,
4756    ) -> Result<proto::LanguageServerPromptResponse> {
4757        let (tx, rx) = smol::channel::bounded(1);
4758        let actions: Vec<_> = envelope
4759            .payload
4760            .actions
4761            .into_iter()
4762            .map(|action| MessageActionItem {
4763                title: action,
4764                properties: Default::default(),
4765            })
4766            .collect();
4767        this.update(&mut cx, |_, cx| {
4768            cx.emit(Event::LanguageServerPrompt(LanguageServerPromptRequest {
4769                level: proto_to_prompt(envelope.payload.level.context("Invalid prompt level")?),
4770                message: envelope.payload.message,
4771                actions: actions.clone(),
4772                lsp_name: envelope.payload.lsp_name,
4773                response_channel: tx,
4774            }));
4775
4776            anyhow::Ok(())
4777        })??;
4778
4779        // We drop `this` to avoid holding a reference in this future for too
4780        // long.
4781        // If we keep the reference, we might not drop the `Project` early
4782        // enough when closing a window and it will only get releases on the
4783        // next `flush_effects()` call.
4784        drop(this);
4785
4786        let mut rx = pin!(rx);
4787        let answer = rx.next().await;
4788
4789        Ok(LanguageServerPromptResponse {
4790            action_response: answer.and_then(|answer| {
4791                actions
4792                    .iter()
4793                    .position(|action| *action == answer)
4794                    .map(|index| index as u64)
4795            }),
4796        })
4797    }
4798
4799    async fn handle_hide_toast(
4800        this: Entity<Self>,
4801        envelope: TypedEnvelope<proto::HideToast>,
4802        mut cx: AsyncApp,
4803    ) -> Result<()> {
4804        this.update(&mut cx, |_, cx| {
4805            cx.emit(Event::HideToast {
4806                notification_id: envelope.payload.notification_id.into(),
4807            });
4808            Ok(())
4809        })?
4810    }
4811
4812    // Collab sends UpdateWorktree protos as messages
4813    async fn handle_update_worktree(
4814        this: Entity<Self>,
4815        envelope: TypedEnvelope<proto::UpdateWorktree>,
4816        mut cx: AsyncApp,
4817    ) -> Result<()> {
4818        this.update(&mut cx, |project, cx| {
4819            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
4820            if let Some(trusted_worktrees) = TrustedWorktrees::try_get_global(cx) {
4821                trusted_worktrees.update(cx, |trusted_worktrees, cx| {
4822                    trusted_worktrees.can_trust(worktree_id, cx)
4823                });
4824            }
4825            if let Some(worktree) = project.worktree_for_id(worktree_id, cx) {
4826                worktree.update(cx, |worktree, _| {
4827                    let worktree = worktree.as_remote_mut().unwrap();
4828                    worktree.update_from_remote(envelope.payload);
4829                });
4830            }
4831            Ok(())
4832        })?
4833    }
4834
4835    async fn handle_update_buffer_from_remote_server(
4836        this: Entity<Self>,
4837        envelope: TypedEnvelope<proto::UpdateBuffer>,
4838        cx: AsyncApp,
4839    ) -> Result<proto::Ack> {
4840        let buffer_store = this.read_with(&cx, |this, cx| {
4841            if let Some(remote_id) = this.remote_id() {
4842                let mut payload = envelope.payload.clone();
4843                payload.project_id = remote_id;
4844                cx.background_spawn(this.collab_client.request(payload))
4845                    .detach_and_log_err(cx);
4846            }
4847            this.buffer_store.clone()
4848        })?;
4849        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4850    }
4851
4852    async fn handle_trust_worktrees(
4853        this: Entity<Self>,
4854        envelope: TypedEnvelope<proto::TrustWorktrees>,
4855        mut cx: AsyncApp,
4856    ) -> Result<proto::Ack> {
4857        let trusted_worktrees = cx
4858            .update(|cx| TrustedWorktrees::try_get_global(cx))?
4859            .context("missing trusted worktrees")?;
4860        trusted_worktrees.update(&mut cx, |trusted_worktrees, cx| {
4861            let remote_host = this
4862                .read(cx)
4863                .remote_connection_options(cx)
4864                .map(RemoteHostLocation::from);
4865            trusted_worktrees.trust(
4866                envelope
4867                    .payload
4868                    .trusted_paths
4869                    .into_iter()
4870                    .filter_map(|proto_path| PathTrust::from_proto(proto_path))
4871                    .collect(),
4872                remote_host,
4873                cx,
4874            );
4875        })?;
4876        Ok(proto::Ack {})
4877    }
4878
4879    async fn handle_restrict_worktrees(
4880        this: Entity<Self>,
4881        envelope: TypedEnvelope<proto::RestrictWorktrees>,
4882        mut cx: AsyncApp,
4883    ) -> Result<proto::Ack> {
4884        let trusted_worktrees = cx
4885            .update(|cx| TrustedWorktrees::try_get_global(cx))?
4886            .context("missing trusted worktrees")?;
4887        trusted_worktrees.update(&mut cx, |trusted_worktrees, cx| {
4888            let mut restricted_paths = envelope
4889                .payload
4890                .worktree_ids
4891                .into_iter()
4892                .map(WorktreeId::from_proto)
4893                .map(PathTrust::Worktree)
4894                .collect::<HashSet<_>>();
4895            if envelope.payload.restrict_workspace {
4896                restricted_paths.insert(PathTrust::Workspace);
4897            }
4898            let remote_host = this
4899                .read(cx)
4900                .remote_connection_options(cx)
4901                .map(RemoteHostLocation::from);
4902            trusted_worktrees.restrict(restricted_paths, remote_host, cx);
4903        })?;
4904        Ok(proto::Ack {})
4905    }
4906
4907    async fn handle_update_buffer(
4908        this: Entity<Self>,
4909        envelope: TypedEnvelope<proto::UpdateBuffer>,
4910        cx: AsyncApp,
4911    ) -> Result<proto::Ack> {
4912        let buffer_store = this.read_with(&cx, |this, cx| {
4913            if let Some(ssh) = &this.remote_client {
4914                let mut payload = envelope.payload.clone();
4915                payload.project_id = REMOTE_SERVER_PROJECT_ID;
4916                cx.background_spawn(ssh.read(cx).proto_client().request(payload))
4917                    .detach_and_log_err(cx);
4918            }
4919            this.buffer_store.clone()
4920        })?;
4921        BufferStore::handle_update_buffer(buffer_store, envelope, cx).await
4922    }
4923
4924    fn retain_remotely_created_models(
4925        &mut self,
4926        cx: &mut Context<Self>,
4927    ) -> RemotelyCreatedModelGuard {
4928        Self::retain_remotely_created_models_impl(
4929            &self.remotely_created_models,
4930            &self.buffer_store,
4931            &self.worktree_store,
4932            cx,
4933        )
4934    }
4935
4936    fn retain_remotely_created_models_impl(
4937        models: &Arc<Mutex<RemotelyCreatedModels>>,
4938        buffer_store: &Entity<BufferStore>,
4939        worktree_store: &Entity<WorktreeStore>,
4940        cx: &mut App,
4941    ) -> RemotelyCreatedModelGuard {
4942        {
4943            let mut remotely_create_models = models.lock();
4944            if remotely_create_models.retain_count == 0 {
4945                remotely_create_models.buffers = buffer_store.read(cx).buffers().collect();
4946                remotely_create_models.worktrees = worktree_store.read(cx).worktrees().collect();
4947            }
4948            remotely_create_models.retain_count += 1;
4949        }
4950        RemotelyCreatedModelGuard {
4951            remote_models: Arc::downgrade(&models),
4952        }
4953    }
4954
4955    async fn handle_create_buffer_for_peer(
4956        this: Entity<Self>,
4957        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
4958        mut cx: AsyncApp,
4959    ) -> Result<()> {
4960        this.update(&mut cx, |this, cx| {
4961            this.buffer_store.update(cx, |buffer_store, cx| {
4962                buffer_store.handle_create_buffer_for_peer(
4963                    envelope,
4964                    this.replica_id(),
4965                    this.capability(),
4966                    cx,
4967                )
4968            })
4969        })?
4970    }
4971
4972    async fn handle_toggle_lsp_logs(
4973        project: Entity<Self>,
4974        envelope: TypedEnvelope<proto::ToggleLspLogs>,
4975        mut cx: AsyncApp,
4976    ) -> Result<()> {
4977        let toggled_log_kind =
4978            match proto::toggle_lsp_logs::LogType::from_i32(envelope.payload.log_type)
4979                .context("invalid log type")?
4980            {
4981                proto::toggle_lsp_logs::LogType::Log => LogKind::Logs,
4982                proto::toggle_lsp_logs::LogType::Trace => LogKind::Trace,
4983                proto::toggle_lsp_logs::LogType::Rpc => LogKind::Rpc,
4984            };
4985        project.update(&mut cx, |_, cx| {
4986            cx.emit(Event::ToggleLspLogs {
4987                server_id: LanguageServerId::from_proto(envelope.payload.server_id),
4988                enabled: envelope.payload.enabled,
4989                toggled_log_kind,
4990            })
4991        })?;
4992        Ok(())
4993    }
4994
4995    async fn handle_synchronize_buffers(
4996        this: Entity<Self>,
4997        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
4998        mut cx: AsyncApp,
4999    ) -> Result<proto::SynchronizeBuffersResponse> {
5000        let response = this.update(&mut cx, |this, cx| {
5001            let client = this.collab_client.clone();
5002            this.buffer_store.update(cx, |this, cx| {
5003                this.handle_synchronize_buffers(envelope, cx, client)
5004            })
5005        })??;
5006
5007        Ok(response)
5008    }
5009
5010    async fn handle_search_candidate_buffers(
5011        this: Entity<Self>,
5012        envelope: TypedEnvelope<proto::FindSearchCandidates>,
5013        mut cx: AsyncApp,
5014    ) -> Result<proto::FindSearchCandidatesResponse> {
5015        let peer_id = envelope.original_sender_id()?;
5016        let message = envelope.payload;
5017        let path_style = this.read_with(&cx, |this, cx| this.path_style(cx))?;
5018        let query =
5019            SearchQuery::from_proto(message.query.context("missing query field")?, path_style)?;
5020        let results = this.update(&mut cx, |this, cx| {
5021            this.search_impl(query, cx).matching_buffers(cx)
5022        })?;
5023
5024        let mut response = proto::FindSearchCandidatesResponse {
5025            buffer_ids: Vec::new(),
5026        };
5027
5028        while let Ok(buffer) = results.recv().await {
5029            this.update(&mut cx, |this, cx| {
5030                let buffer_id = this.create_buffer_for_peer(&buffer, peer_id, cx);
5031                response.buffer_ids.push(buffer_id.to_proto());
5032            })?;
5033        }
5034
5035        Ok(response)
5036    }
5037
5038    async fn handle_open_buffer_by_id(
5039        this: Entity<Self>,
5040        envelope: TypedEnvelope<proto::OpenBufferById>,
5041        mut cx: AsyncApp,
5042    ) -> Result<proto::OpenBufferResponse> {
5043        let peer_id = envelope.original_sender_id()?;
5044        let buffer_id = BufferId::new(envelope.payload.id)?;
5045        let buffer = this
5046            .update(&mut cx, |this, cx| this.open_buffer_by_id(buffer_id, cx))?
5047            .await?;
5048        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
5049    }
5050
5051    async fn handle_open_buffer_by_path(
5052        this: Entity<Self>,
5053        envelope: TypedEnvelope<proto::OpenBufferByPath>,
5054        mut cx: AsyncApp,
5055    ) -> Result<proto::OpenBufferResponse> {
5056        let peer_id = envelope.original_sender_id()?;
5057        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
5058        let path = RelPath::from_proto(&envelope.payload.path)?;
5059        let open_buffer = this
5060            .update(&mut cx, |this, cx| {
5061                this.open_buffer(ProjectPath { worktree_id, path }, cx)
5062            })?
5063            .await?;
5064        Project::respond_to_open_buffer_request(this, open_buffer, peer_id, &mut cx)
5065    }
5066
5067    async fn handle_open_new_buffer(
5068        this: Entity<Self>,
5069        envelope: TypedEnvelope<proto::OpenNewBuffer>,
5070        mut cx: AsyncApp,
5071    ) -> Result<proto::OpenBufferResponse> {
5072        let buffer = this
5073            .update(&mut cx, |this, cx| this.create_buffer(true, cx))?
5074            .await?;
5075        let peer_id = envelope.original_sender_id()?;
5076
5077        Project::respond_to_open_buffer_request(this, buffer, peer_id, &mut cx)
5078    }
5079
5080    fn respond_to_open_buffer_request(
5081        this: Entity<Self>,
5082        buffer: Entity<Buffer>,
5083        peer_id: proto::PeerId,
5084        cx: &mut AsyncApp,
5085    ) -> Result<proto::OpenBufferResponse> {
5086        this.update(cx, |this, cx| {
5087            let is_private = buffer
5088                .read(cx)
5089                .file()
5090                .map(|f| f.is_private())
5091                .unwrap_or_default();
5092            anyhow::ensure!(!is_private, ErrorCode::UnsharedItem);
5093            Ok(proto::OpenBufferResponse {
5094                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx).into(),
5095            })
5096        })?
5097    }
5098
5099    fn create_buffer_for_peer(
5100        &mut self,
5101        buffer: &Entity<Buffer>,
5102        peer_id: proto::PeerId,
5103        cx: &mut App,
5104    ) -> BufferId {
5105        self.buffer_store
5106            .update(cx, |buffer_store, cx| {
5107                buffer_store.create_buffer_for_peer(buffer, peer_id, cx)
5108            })
5109            .detach_and_log_err(cx);
5110        buffer.read(cx).remote_id()
5111    }
5112
5113    async fn handle_create_image_for_peer(
5114        this: Entity<Self>,
5115        envelope: TypedEnvelope<proto::CreateImageForPeer>,
5116        mut cx: AsyncApp,
5117    ) -> Result<()> {
5118        this.update(&mut cx, |this, cx| {
5119            this.image_store.update(cx, |image_store, cx| {
5120                image_store.handle_create_image_for_peer(envelope, cx)
5121            })
5122        })?
5123        .log_err();
5124        Ok(())
5125    }
5126
5127    fn synchronize_remote_buffers(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
5128        let project_id = match self.client_state {
5129            ProjectClientState::Remote {
5130                sharing_has_stopped,
5131                remote_id,
5132                ..
5133            } => {
5134                if sharing_has_stopped {
5135                    return Task::ready(Err(anyhow!(
5136                        "can't synchronize remote buffers on a readonly project"
5137                    )));
5138                } else {
5139                    remote_id
5140                }
5141            }
5142            ProjectClientState::Shared { .. } | ProjectClientState::Local => {
5143                return Task::ready(Err(anyhow!(
5144                    "can't synchronize remote buffers on a local project"
5145                )));
5146            }
5147        };
5148
5149        let client = self.collab_client.clone();
5150        cx.spawn(async move |this, cx| {
5151            let (buffers, incomplete_buffer_ids) = this.update(cx, |this, cx| {
5152                this.buffer_store.read(cx).buffer_version_info(cx)
5153            })?;
5154            let response = client
5155                .request(proto::SynchronizeBuffers {
5156                    project_id,
5157                    buffers,
5158                })
5159                .await?;
5160
5161            let send_updates_for_buffers = this.update(cx, |this, cx| {
5162                response
5163                    .buffers
5164                    .into_iter()
5165                    .map(|buffer| {
5166                        let client = client.clone();
5167                        let buffer_id = match BufferId::new(buffer.id) {
5168                            Ok(id) => id,
5169                            Err(e) => {
5170                                return Task::ready(Err(e));
5171                            }
5172                        };
5173                        let remote_version = language::proto::deserialize_version(&buffer.version);
5174                        if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
5175                            let operations =
5176                                buffer.read(cx).serialize_ops(Some(remote_version), cx);
5177                            cx.background_spawn(async move {
5178                                let operations = operations.await;
5179                                for chunk in split_operations(operations) {
5180                                    client
5181                                        .request(proto::UpdateBuffer {
5182                                            project_id,
5183                                            buffer_id: buffer_id.into(),
5184                                            operations: chunk,
5185                                        })
5186                                        .await?;
5187                                }
5188                                anyhow::Ok(())
5189                            })
5190                        } else {
5191                            Task::ready(Ok(()))
5192                        }
5193                    })
5194                    .collect::<Vec<_>>()
5195            })?;
5196
5197            // Any incomplete buffers have open requests waiting. Request that the host sends
5198            // creates these buffers for us again to unblock any waiting futures.
5199            for id in incomplete_buffer_ids {
5200                cx.background_spawn(client.request(proto::OpenBufferById {
5201                    project_id,
5202                    id: id.into(),
5203                }))
5204                .detach();
5205            }
5206
5207            futures::future::join_all(send_updates_for_buffers)
5208                .await
5209                .into_iter()
5210                .collect()
5211        })
5212    }
5213
5214    pub fn worktree_metadata_protos(&self, cx: &App) -> Vec<proto::WorktreeMetadata> {
5215        self.worktree_store.read(cx).worktree_metadata_protos(cx)
5216    }
5217
5218    /// Iterator of all open buffers that have unsaved changes
5219    pub fn dirty_buffers<'a>(&'a self, cx: &'a App) -> impl Iterator<Item = ProjectPath> + 'a {
5220        self.buffer_store.read(cx).buffers().filter_map(|buf| {
5221            let buf = buf.read(cx);
5222            if buf.is_dirty() {
5223                buf.project_path(cx)
5224            } else {
5225                None
5226            }
5227        })
5228    }
5229
5230    fn set_worktrees_from_proto(
5231        &mut self,
5232        worktrees: Vec<proto::WorktreeMetadata>,
5233        cx: &mut Context<Project>,
5234    ) -> Result<()> {
5235        self.worktree_store.update(cx, |worktree_store, cx| {
5236            worktree_store.set_worktrees_from_proto(worktrees, self.replica_id(), cx)
5237        })
5238    }
5239
5240    fn set_collaborators_from_proto(
5241        &mut self,
5242        messages: Vec<proto::Collaborator>,
5243        cx: &mut Context<Self>,
5244    ) -> Result<()> {
5245        let mut collaborators = HashMap::default();
5246        for message in messages {
5247            let collaborator = Collaborator::from_proto(message)?;
5248            collaborators.insert(collaborator.peer_id, collaborator);
5249        }
5250        for old_peer_id in self.collaborators.keys() {
5251            if !collaborators.contains_key(old_peer_id) {
5252                cx.emit(Event::CollaboratorLeft(*old_peer_id));
5253            }
5254        }
5255        self.collaborators = collaborators;
5256        Ok(())
5257    }
5258
5259    pub fn supplementary_language_servers<'a>(
5260        &'a self,
5261        cx: &'a App,
5262    ) -> impl 'a + Iterator<Item = (LanguageServerId, LanguageServerName)> {
5263        self.lsp_store.read(cx).supplementary_language_servers()
5264    }
5265
5266    pub fn any_language_server_supports_inlay_hints(&self, buffer: &Buffer, cx: &mut App) -> bool {
5267        let Some(language) = buffer.language().cloned() else {
5268            return false;
5269        };
5270        self.lsp_store.update(cx, |lsp_store, _| {
5271            let relevant_language_servers = lsp_store
5272                .languages
5273                .lsp_adapters(&language.name())
5274                .into_iter()
5275                .map(|lsp_adapter| lsp_adapter.name())
5276                .collect::<HashSet<_>>();
5277            lsp_store
5278                .language_server_statuses()
5279                .filter_map(|(server_id, server_status)| {
5280                    relevant_language_servers
5281                        .contains(&server_status.name)
5282                        .then_some(server_id)
5283                })
5284                .filter_map(|server_id| lsp_store.lsp_server_capabilities.get(&server_id))
5285                .any(InlayHints::check_capabilities)
5286        })
5287    }
5288
5289    pub fn language_server_id_for_name(
5290        &self,
5291        buffer: &Buffer,
5292        name: &LanguageServerName,
5293        cx: &App,
5294    ) -> Option<LanguageServerId> {
5295        let language = buffer.language()?;
5296        let relevant_language_servers = self
5297            .languages
5298            .lsp_adapters(&language.name())
5299            .into_iter()
5300            .map(|lsp_adapter| lsp_adapter.name())
5301            .collect::<HashSet<_>>();
5302        if !relevant_language_servers.contains(name) {
5303            return None;
5304        }
5305        self.language_server_statuses(cx)
5306            .filter(|(_, server_status)| relevant_language_servers.contains(&server_status.name))
5307            .find_map(|(server_id, server_status)| {
5308                if &server_status.name == name {
5309                    Some(server_id)
5310                } else {
5311                    None
5312                }
5313            })
5314    }
5315
5316    #[cfg(any(test, feature = "test-support"))]
5317    pub fn has_language_servers_for(&self, buffer: &Buffer, cx: &mut App) -> bool {
5318        self.lsp_store.update(cx, |this, cx| {
5319            this.running_language_servers_for_local_buffer(buffer, cx)
5320                .next()
5321                .is_some()
5322        })
5323    }
5324
5325    pub fn git_init(
5326        &self,
5327        path: Arc<Path>,
5328        fallback_branch_name: String,
5329        cx: &App,
5330    ) -> Task<Result<()>> {
5331        self.git_store
5332            .read(cx)
5333            .git_init(path, fallback_branch_name, cx)
5334    }
5335
5336    pub fn buffer_store(&self) -> &Entity<BufferStore> {
5337        &self.buffer_store
5338    }
5339
5340    pub fn git_store(&self) -> &Entity<GitStore> {
5341        &self.git_store
5342    }
5343
5344    pub fn agent_server_store(&self) -> &Entity<AgentServerStore> {
5345        &self.agent_server_store
5346    }
5347
5348    #[cfg(test)]
5349    fn git_scans_complete(&self, cx: &Context<Self>) -> Task<()> {
5350        cx.spawn(async move |this, cx| {
5351            let scans_complete = this
5352                .read_with(cx, |this, cx| {
5353                    this.worktrees(cx)
5354                        .filter_map(|worktree| Some(worktree.read(cx).as_local()?.scan_complete()))
5355                        .collect::<Vec<_>>()
5356                })
5357                .unwrap();
5358            join_all(scans_complete).await;
5359            let barriers = this
5360                .update(cx, |this, cx| {
5361                    let repos = this.repositories(cx).values().cloned().collect::<Vec<_>>();
5362                    repos
5363                        .into_iter()
5364                        .map(|repo| repo.update(cx, |repo, _| repo.barrier()))
5365                        .collect::<Vec<_>>()
5366                })
5367                .unwrap();
5368            join_all(barriers).await;
5369        })
5370    }
5371
5372    pub fn active_repository(&self, cx: &App) -> Option<Entity<Repository>> {
5373        self.git_store.read(cx).active_repository()
5374    }
5375
5376    pub fn repositories<'a>(&self, cx: &'a App) -> &'a HashMap<RepositoryId, Entity<Repository>> {
5377        self.git_store.read(cx).repositories()
5378    }
5379
5380    pub fn status_for_buffer_id(&self, buffer_id: BufferId, cx: &App) -> Option<FileStatus> {
5381        self.git_store.read(cx).status_for_buffer_id(buffer_id, cx)
5382    }
5383
5384    pub fn set_agent_location(
5385        &mut self,
5386        new_location: Option<AgentLocation>,
5387        cx: &mut Context<Self>,
5388    ) {
5389        if let Some(old_location) = self.agent_location.as_ref() {
5390            old_location
5391                .buffer
5392                .update(cx, |buffer, cx| buffer.remove_agent_selections(cx))
5393                .ok();
5394        }
5395
5396        if let Some(location) = new_location.as_ref() {
5397            location
5398                .buffer
5399                .update(cx, |buffer, cx| {
5400                    buffer.set_agent_selections(
5401                        Arc::from([language::Selection {
5402                            id: 0,
5403                            start: location.position,
5404                            end: location.position,
5405                            reversed: false,
5406                            goal: language::SelectionGoal::None,
5407                        }]),
5408                        false,
5409                        CursorShape::Hollow,
5410                        cx,
5411                    )
5412                })
5413                .ok();
5414        }
5415
5416        self.agent_location = new_location;
5417        cx.emit(Event::AgentLocationChanged);
5418    }
5419
5420    pub fn agent_location(&self) -> Option<AgentLocation> {
5421        self.agent_location.clone()
5422    }
5423
5424    pub fn path_style(&self, cx: &App) -> PathStyle {
5425        self.worktree_store.read(cx).path_style()
5426    }
5427
5428    pub fn contains_local_settings_file(
5429        &self,
5430        worktree_id: WorktreeId,
5431        rel_path: &RelPath,
5432        cx: &App,
5433    ) -> bool {
5434        self.worktree_for_id(worktree_id, cx)
5435            .map_or(false, |worktree| {
5436                worktree.read(cx).entry_for_path(rel_path).is_some()
5437            })
5438    }
5439
5440    pub fn update_local_settings_file(
5441        &self,
5442        worktree_id: WorktreeId,
5443        rel_path: Arc<RelPath>,
5444        cx: &mut App,
5445        update: impl 'static + Send + FnOnce(&mut settings::SettingsContent, &App),
5446    ) {
5447        let Some(worktree) = self.worktree_for_id(worktree_id, cx) else {
5448            // todo(settings_ui) error?
5449            return;
5450        };
5451        cx.spawn(async move |cx| {
5452            let file = worktree
5453                .update(cx, |worktree, cx| worktree.load_file(&rel_path, cx))?
5454                .await
5455                .context("Failed to load settings file")?;
5456
5457            let new_text = cx.read_global::<SettingsStore, _>(|store, cx| {
5458                store.new_text_for_update(file.text, move |settings| update(settings, cx))
5459            })?;
5460            worktree
5461                .update(cx, |worktree, cx| {
5462                    let line_ending = text::LineEnding::detect(&new_text);
5463                    worktree.write_file(rel_path.clone(), new_text.into(), line_ending, cx)
5464                })?
5465                .await
5466                .context("Failed to write settings file")?;
5467
5468            anyhow::Ok(())
5469        })
5470        .detach_and_log_err(cx);
5471    }
5472}
5473
5474pub struct PathMatchCandidateSet {
5475    pub snapshot: Snapshot,
5476    pub include_ignored: bool,
5477    pub include_root_name: bool,
5478    pub candidates: Candidates,
5479}
5480
5481pub enum Candidates {
5482    /// Only consider directories.
5483    Directories,
5484    /// Only consider files.
5485    Files,
5486    /// Consider directories and files.
5487    Entries,
5488}
5489
5490impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
5491    type Candidates = PathMatchCandidateSetIter<'a>;
5492
5493    fn id(&self) -> usize {
5494        self.snapshot.id().to_usize()
5495    }
5496
5497    fn len(&self) -> usize {
5498        match self.candidates {
5499            Candidates::Files => {
5500                if self.include_ignored {
5501                    self.snapshot.file_count()
5502                } else {
5503                    self.snapshot.visible_file_count()
5504                }
5505            }
5506
5507            Candidates::Directories => {
5508                if self.include_ignored {
5509                    self.snapshot.dir_count()
5510                } else {
5511                    self.snapshot.visible_dir_count()
5512                }
5513            }
5514
5515            Candidates::Entries => {
5516                if self.include_ignored {
5517                    self.snapshot.entry_count()
5518                } else {
5519                    self.snapshot.visible_entry_count()
5520                }
5521            }
5522        }
5523    }
5524
5525    fn prefix(&self) -> Arc<RelPath> {
5526        if self.snapshot.root_entry().is_some_and(|e| e.is_file()) || self.include_root_name {
5527            self.snapshot.root_name().into()
5528        } else {
5529            RelPath::empty().into()
5530        }
5531    }
5532
5533    fn root_is_file(&self) -> bool {
5534        self.snapshot.root_entry().is_some_and(|f| f.is_file())
5535    }
5536
5537    fn path_style(&self) -> PathStyle {
5538        self.snapshot.path_style()
5539    }
5540
5541    fn candidates(&'a self, start: usize) -> Self::Candidates {
5542        PathMatchCandidateSetIter {
5543            traversal: match self.candidates {
5544                Candidates::Directories => self.snapshot.directories(self.include_ignored, start),
5545                Candidates::Files => self.snapshot.files(self.include_ignored, start),
5546                Candidates::Entries => self.snapshot.entries(self.include_ignored, start),
5547            },
5548        }
5549    }
5550}
5551
5552pub struct PathMatchCandidateSetIter<'a> {
5553    traversal: Traversal<'a>,
5554}
5555
5556impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
5557    type Item = fuzzy::PathMatchCandidate<'a>;
5558
5559    fn next(&mut self) -> Option<Self::Item> {
5560        self.traversal
5561            .next()
5562            .map(|entry| fuzzy::PathMatchCandidate {
5563                is_dir: entry.kind.is_dir(),
5564                path: &entry.path,
5565                char_bag: entry.char_bag,
5566            })
5567    }
5568}
5569
5570impl EventEmitter<Event> for Project {}
5571
5572impl<'a> From<&'a ProjectPath> for SettingsLocation<'a> {
5573    fn from(val: &'a ProjectPath) -> Self {
5574        SettingsLocation {
5575            worktree_id: val.worktree_id,
5576            path: val.path.as_ref(),
5577        }
5578    }
5579}
5580
5581impl<P: Into<Arc<RelPath>>> From<(WorktreeId, P)> for ProjectPath {
5582    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
5583        Self {
5584            worktree_id,
5585            path: path.into(),
5586        }
5587    }
5588}
5589
5590/// ResolvedPath is a path that has been resolved to either a ProjectPath
5591/// or an AbsPath and that *exists*.
5592#[derive(Debug, Clone)]
5593pub enum ResolvedPath {
5594    ProjectPath {
5595        project_path: ProjectPath,
5596        is_dir: bool,
5597    },
5598    AbsPath {
5599        path: String,
5600        is_dir: bool,
5601    },
5602}
5603
5604impl ResolvedPath {
5605    pub fn abs_path(&self) -> Option<&str> {
5606        match self {
5607            Self::AbsPath { path, .. } => Some(path),
5608            _ => None,
5609        }
5610    }
5611
5612    pub fn into_abs_path(self) -> Option<String> {
5613        match self {
5614            Self::AbsPath { path, .. } => Some(path),
5615            _ => None,
5616        }
5617    }
5618
5619    pub fn project_path(&self) -> Option<&ProjectPath> {
5620        match self {
5621            Self::ProjectPath { project_path, .. } => Some(project_path),
5622            _ => None,
5623        }
5624    }
5625
5626    pub fn is_file(&self) -> bool {
5627        !self.is_dir()
5628    }
5629
5630    pub fn is_dir(&self) -> bool {
5631        match self {
5632            Self::ProjectPath { is_dir, .. } => *is_dir,
5633            Self::AbsPath { is_dir, .. } => *is_dir,
5634        }
5635    }
5636}
5637
5638impl ProjectItem for Buffer {
5639    fn try_open(
5640        project: &Entity<Project>,
5641        path: &ProjectPath,
5642        cx: &mut App,
5643    ) -> Option<Task<Result<Entity<Self>>>> {
5644        Some(project.update(cx, |project, cx| project.open_buffer(path.clone(), cx)))
5645    }
5646
5647    fn entry_id(&self, _cx: &App) -> Option<ProjectEntryId> {
5648        File::from_dyn(self.file()).and_then(|file| file.project_entry_id())
5649    }
5650
5651    fn project_path(&self, cx: &App) -> Option<ProjectPath> {
5652        self.file().map(|file| ProjectPath {
5653            worktree_id: file.worktree_id(cx),
5654            path: file.path().clone(),
5655        })
5656    }
5657
5658    fn is_dirty(&self) -> bool {
5659        self.is_dirty()
5660    }
5661}
5662
5663impl Completion {
5664    pub fn kind(&self) -> Option<CompletionItemKind> {
5665        self.source
5666            // `lsp::CompletionListItemDefaults` has no `kind` field
5667            .lsp_completion(false)
5668            .and_then(|lsp_completion| lsp_completion.kind)
5669    }
5670
5671    pub fn label(&self) -> Option<String> {
5672        self.source
5673            .lsp_completion(false)
5674            .map(|lsp_completion| lsp_completion.label.clone())
5675    }
5676
5677    /// A key that can be used to sort completions when displaying
5678    /// them to the user.
5679    pub fn sort_key(&self) -> (usize, &str) {
5680        const DEFAULT_KIND_KEY: usize = 4;
5681        let kind_key = self
5682            .kind()
5683            .and_then(|lsp_completion_kind| match lsp_completion_kind {
5684                lsp::CompletionItemKind::KEYWORD => Some(0),
5685                lsp::CompletionItemKind::VARIABLE => Some(1),
5686                lsp::CompletionItemKind::CONSTANT => Some(2),
5687                lsp::CompletionItemKind::PROPERTY => Some(3),
5688                _ => None,
5689            })
5690            .unwrap_or(DEFAULT_KIND_KEY);
5691        (kind_key, self.label.filter_text())
5692    }
5693
5694    /// Whether this completion is a snippet.
5695    pub fn is_snippet_kind(&self) -> bool {
5696        matches!(
5697            &self.source,
5698            CompletionSource::Lsp { lsp_completion, .. }
5699            if lsp_completion.kind == Some(CompletionItemKind::SNIPPET)
5700        )
5701    }
5702
5703    /// Whether this completion is a snippet or snippet-style LSP completion.
5704    pub fn is_snippet(&self) -> bool {
5705        self.source
5706            // `lsp::CompletionListItemDefaults` has `insert_text_format` field
5707            .lsp_completion(true)
5708            .is_some_and(|lsp_completion| {
5709                lsp_completion.insert_text_format == Some(lsp::InsertTextFormat::SNIPPET)
5710            })
5711    }
5712
5713    /// Returns the corresponding color for this completion.
5714    ///
5715    /// Will return `None` if this completion's kind is not [`CompletionItemKind::COLOR`].
5716    pub fn color(&self) -> Option<Hsla> {
5717        // `lsp::CompletionListItemDefaults` has no `kind` field
5718        let lsp_completion = self.source.lsp_completion(false)?;
5719        if lsp_completion.kind? == CompletionItemKind::COLOR {
5720            return color_extractor::extract_color(&lsp_completion);
5721        }
5722        None
5723    }
5724}
5725
5726fn proto_to_prompt(level: proto::language_server_prompt_request::Level) -> gpui::PromptLevel {
5727    match level {
5728        proto::language_server_prompt_request::Level::Info(_) => gpui::PromptLevel::Info,
5729        proto::language_server_prompt_request::Level::Warning(_) => gpui::PromptLevel::Warning,
5730        proto::language_server_prompt_request::Level::Critical(_) => gpui::PromptLevel::Critical,
5731    }
5732}
5733
5734fn provide_inline_values(
5735    captures: impl Iterator<Item = (Range<usize>, language::DebuggerTextObject)>,
5736    snapshot: &language::BufferSnapshot,
5737    max_row: usize,
5738) -> Vec<InlineValueLocation> {
5739    let mut variables = Vec::new();
5740    let mut variable_position = HashSet::default();
5741    let mut scopes = Vec::new();
5742
5743    let active_debug_line_offset = snapshot.point_to_offset(Point::new(max_row as u32, 0));
5744
5745    for (capture_range, capture_kind) in captures {
5746        match capture_kind {
5747            language::DebuggerTextObject::Variable => {
5748                let variable_name = snapshot
5749                    .text_for_range(capture_range.clone())
5750                    .collect::<String>();
5751                let point = snapshot.offset_to_point(capture_range.end);
5752
5753                while scopes
5754                    .last()
5755                    .is_some_and(|scope: &Range<_>| !scope.contains(&capture_range.start))
5756                {
5757                    scopes.pop();
5758                }
5759
5760                if point.row as usize > max_row {
5761                    break;
5762                }
5763
5764                let scope = if scopes
5765                    .last()
5766                    .is_none_or(|scope| !scope.contains(&active_debug_line_offset))
5767                {
5768                    VariableScope::Global
5769                } else {
5770                    VariableScope::Local
5771                };
5772
5773                if variable_position.insert(capture_range.end) {
5774                    variables.push(InlineValueLocation {
5775                        variable_name,
5776                        scope,
5777                        lookup: VariableLookupKind::Variable,
5778                        row: point.row as usize,
5779                        column: point.column as usize,
5780                    });
5781                }
5782            }
5783            language::DebuggerTextObject::Scope => {
5784                while scopes.last().map_or_else(
5785                    || false,
5786                    |scope: &Range<usize>| {
5787                        !(scope.contains(&capture_range.start)
5788                            && scope.contains(&capture_range.end))
5789                    },
5790                ) {
5791                    scopes.pop();
5792                }
5793                scopes.push(capture_range);
5794            }
5795        }
5796    }
5797
5798    variables
5799}
5800
5801#[cfg(test)]
5802mod disable_ai_settings_tests {
5803    use super::*;
5804    use gpui::TestAppContext;
5805    use settings::Settings;
5806
5807    #[gpui::test]
5808    async fn test_disable_ai_settings_security(cx: &mut TestAppContext) {
5809        cx.update(|cx| {
5810            settings::init(cx);
5811
5812            // Test 1: Default is false (AI enabled)
5813            assert!(
5814                !DisableAiSettings::get_global(cx).disable_ai,
5815                "Default should allow AI"
5816            );
5817        });
5818
5819        let disable_true = serde_json::json!({
5820            "disable_ai": true
5821        })
5822        .to_string();
5823        let disable_false = serde_json::json!({
5824            "disable_ai": false
5825        })
5826        .to_string();
5827
5828        cx.update_global::<SettingsStore, _>(|store, cx| {
5829            store.set_user_settings(&disable_false, cx).unwrap();
5830            store.set_global_settings(&disable_true, cx).unwrap();
5831        });
5832        cx.update(|cx| {
5833            assert!(
5834                DisableAiSettings::get_global(cx).disable_ai,
5835                "Local false cannot override global true"
5836            );
5837        });
5838
5839        cx.update_global::<SettingsStore, _>(|store, cx| {
5840            store.set_global_settings(&disable_false, cx).unwrap();
5841            store.set_user_settings(&disable_true, cx).unwrap();
5842        });
5843
5844        cx.update(|cx| {
5845            assert!(
5846                DisableAiSettings::get_global(cx).disable_ai,
5847                "Local false cannot override global true"
5848            );
5849        });
5850    }
5851}