project.rs

   1mod ignore;
   2mod lsp_command;
   3pub mod project_settings;
   4pub mod search;
   5pub mod terminals;
   6pub mod worktree;
   7
   8#[cfg(test)]
   9mod project_tests;
  10#[cfg(test)]
  11mod worktree_tests;
  12
  13use anyhow::{anyhow, Context, Result};
  14use client::{proto, Client, Collaborator, TypedEnvelope, UserStore};
  15use clock::ReplicaId;
  16use collections::{hash_map, BTreeMap, HashMap, HashSet};
  17use copilot::Copilot;
  18use futures::{
  19    channel::{
  20        mpsc::{self, UnboundedReceiver},
  21        oneshot,
  22    },
  23    future::{self, try_join_all, Shared},
  24    stream::FuturesUnordered,
  25    AsyncWriteExt, Future, FutureExt, StreamExt, TryFutureExt,
  26};
  27use globset::{Glob, GlobSet, GlobSetBuilder};
  28use gpui::{
  29    executor::Background, AnyModelHandle, AppContext, AsyncAppContext, BorrowAppContext, Entity,
  30    ModelContext, ModelHandle, Task, WeakModelHandle,
  31};
  32use itertools::Itertools;
  33use language::{
  34    language_settings::{
  35        language_settings, FormatOnSave, Formatter, InlayHintKind, LanguageSettings,
  36    },
  37    point_to_lsp,
  38    proto::{
  39        deserialize_anchor, deserialize_fingerprint, deserialize_line_ending, deserialize_version,
  40        serialize_anchor, serialize_version, split_operations,
  41    },
  42    range_from_lsp, range_to_lsp, Bias, Buffer, BufferSnapshot, CachedLspAdapter, CodeAction,
  43    CodeLabel, Completion, Diagnostic, DiagnosticEntry, DiagnosticSet, Diff, Event as BufferEvent,
  44    File as _, Language, LanguageRegistry, LanguageServerName, LocalFile, LspAdapterDelegate,
  45    OffsetRangeExt, Operation, Patch, PendingLanguageServer, PointUtf16, TextBufferSnapshot,
  46    ToOffset, ToPointUtf16, Transaction, Unclipped,
  47};
  48use log::error;
  49use lsp::{
  50    DiagnosticSeverity, DiagnosticTag, DidChangeWatchedFilesRegistrationOptions,
  51    DocumentHighlightKind, LanguageServer, LanguageServerBinary, LanguageServerId, OneOf,
  52};
  53use lsp_command::*;
  54use node_runtime::NodeRuntime;
  55use parking_lot::Mutex;
  56use postage::watch;
  57use prettier::Prettier;
  58use project_settings::{LspSettings, ProjectSettings};
  59use rand::prelude::*;
  60use search::SearchQuery;
  61use serde::Serialize;
  62use settings::SettingsStore;
  63use sha2::{Digest, Sha256};
  64use similar::{ChangeTag, TextDiff};
  65use smol::channel::{Receiver, Sender};
  66use std::{
  67    cmp::{self, Ordering},
  68    convert::TryInto,
  69    hash::Hash,
  70    mem,
  71    num::NonZeroU32,
  72    ops::Range,
  73    path::{self, Component, Path, PathBuf},
  74    process::Stdio,
  75    str,
  76    sync::{
  77        atomic::{AtomicUsize, Ordering::SeqCst},
  78        Arc,
  79    },
  80    time::{Duration, Instant},
  81};
  82use terminals::Terminals;
  83use text::Anchor;
  84use util::{
  85    debug_panic, defer,
  86    http::HttpClient,
  87    merge_json_value_into,
  88    paths::{DEFAULT_PRETTIER_DIR, LOCAL_SETTINGS_RELATIVE_PATH},
  89    post_inc, ResultExt, TryFutureExt as _,
  90};
  91
  92pub use fs::*;
  93#[cfg(any(test, feature = "test-support"))]
  94pub use prettier::FORMAT_SUFFIX as TEST_PRETTIER_FORMAT_SUFFIX;
  95pub use worktree::*;
  96
  97const MAX_SERVER_REINSTALL_ATTEMPT_COUNT: u64 = 4;
  98
  99pub trait Item {
 100    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId>;
 101    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath>;
 102}
 103
 104// Language server state is stored across 3 collections:
 105//     language_servers =>
 106//         a mapping from unique server id to LanguageServerState which can either be a task for a
 107//         server in the process of starting, or a running server with adapter and language server arcs
 108//     language_server_ids => a mapping from worktreeId and server name to the unique server id
 109//     language_server_statuses => a mapping from unique server id to the current server status
 110//
 111// Multiple worktrees can map to the same language server for example when you jump to the definition
 112// of a file in the standard library. So language_server_ids is used to look up which server is active
 113// for a given worktree and language server name
 114//
 115// When starting a language server, first the id map is checked to make sure a server isn't already available
 116// for that worktree. If there is one, it finishes early. Otherwise, a new id is allocated and and
 117// the Starting variant of LanguageServerState is stored in the language_servers map.
 118pub struct Project {
 119    worktrees: Vec<WorktreeHandle>,
 120    active_entry: Option<ProjectEntryId>,
 121    buffer_ordered_messages_tx: mpsc::UnboundedSender<BufferOrderedMessage>,
 122    languages: Arc<LanguageRegistry>,
 123    supplementary_language_servers:
 124        HashMap<LanguageServerId, (LanguageServerName, Arc<LanguageServer>)>,
 125    language_servers: HashMap<LanguageServerId, LanguageServerState>,
 126    language_server_ids: HashMap<(WorktreeId, LanguageServerName), LanguageServerId>,
 127    language_server_statuses: BTreeMap<LanguageServerId, LanguageServerStatus>,
 128    last_workspace_edits_by_language_server: HashMap<LanguageServerId, ProjectTransaction>,
 129    client: Arc<client::Client>,
 130    next_entry_id: Arc<AtomicUsize>,
 131    join_project_response_message_id: u32,
 132    next_diagnostic_group_id: usize,
 133    user_store: ModelHandle<UserStore>,
 134    fs: Arc<dyn Fs>,
 135    client_state: Option<ProjectClientState>,
 136    collaborators: HashMap<proto::PeerId, Collaborator>,
 137    client_subscriptions: Vec<client::Subscription>,
 138    _subscriptions: Vec<gpui::Subscription>,
 139    next_buffer_id: u64,
 140    opened_buffer: (watch::Sender<()>, watch::Receiver<()>),
 141    shared_buffers: HashMap<proto::PeerId, HashSet<u64>>,
 142    #[allow(clippy::type_complexity)]
 143    loading_buffers_by_path: HashMap<
 144        ProjectPath,
 145        postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
 146    >,
 147    #[allow(clippy::type_complexity)]
 148    loading_local_worktrees:
 149        HashMap<Arc<Path>, Shared<Task<Result<ModelHandle<Worktree>, Arc<anyhow::Error>>>>>,
 150    opened_buffers: HashMap<u64, OpenBuffer>,
 151    local_buffer_ids_by_path: HashMap<ProjectPath, u64>,
 152    local_buffer_ids_by_entry_id: HashMap<ProjectEntryId, u64>,
 153    /// A mapping from a buffer ID to None means that we've started waiting for an ID but haven't finished loading it.
 154    /// Used for re-issuing buffer requests when peers temporarily disconnect
 155    incomplete_remote_buffers: HashMap<u64, Option<ModelHandle<Buffer>>>,
 156    buffer_snapshots: HashMap<u64, HashMap<LanguageServerId, Vec<LspBufferSnapshot>>>, // buffer_id -> server_id -> vec of snapshots
 157    buffers_being_formatted: HashSet<u64>,
 158    buffers_needing_diff: HashSet<WeakModelHandle<Buffer>>,
 159    git_diff_debouncer: DelayedDebounced,
 160    nonce: u128,
 161    _maintain_buffer_languages: Task<()>,
 162    _maintain_workspace_config: Task<()>,
 163    terminals: Terminals,
 164    copilot_lsp_subscription: Option<gpui::Subscription>,
 165    copilot_log_subscription: Option<lsp::Subscription>,
 166    current_lsp_settings: HashMap<Arc<str>, LspSettings>,
 167    node: Option<Arc<dyn NodeRuntime>>,
 168    default_prettier: Option<DefaultPrettier>,
 169    prettiers_per_worktree: HashMap<WorktreeId, HashSet<Option<PathBuf>>>,
 170    prettier_instances: HashMap<PathBuf, Shared<Task<Result<Arc<Prettier>, Arc<anyhow::Error>>>>>,
 171}
 172
 173struct DefaultPrettier {
 174    instance: Option<Shared<Task<Result<Arc<Prettier>, Arc<anyhow::Error>>>>>,
 175    #[cfg(not(any(test, feature = "test-support")))]
 176    installed_plugins: HashSet<&'static str>,
 177}
 178
 179struct DelayedDebounced {
 180    task: Option<Task<()>>,
 181    cancel_channel: Option<oneshot::Sender<()>>,
 182}
 183
 184enum LanguageServerToQuery {
 185    Primary,
 186    Other(LanguageServerId),
 187}
 188
 189impl DelayedDebounced {
 190    fn new() -> DelayedDebounced {
 191        DelayedDebounced {
 192            task: None,
 193            cancel_channel: None,
 194        }
 195    }
 196
 197    fn fire_new<F>(&mut self, delay: Duration, cx: &mut ModelContext<Project>, func: F)
 198    where
 199        F: 'static + FnOnce(&mut Project, &mut ModelContext<Project>) -> Task<()>,
 200    {
 201        if let Some(channel) = self.cancel_channel.take() {
 202            _ = channel.send(());
 203        }
 204
 205        let (sender, mut receiver) = oneshot::channel::<()>();
 206        self.cancel_channel = Some(sender);
 207
 208        let previous_task = self.task.take();
 209        self.task = Some(cx.spawn(|workspace, mut cx| async move {
 210            let mut timer = cx.background().timer(delay).fuse();
 211            if let Some(previous_task) = previous_task {
 212                previous_task.await;
 213            }
 214
 215            futures::select_biased! {
 216                _ = receiver => return,
 217                    _ = timer => {}
 218            }
 219
 220            workspace
 221                .update(&mut cx, |workspace, cx| (func)(workspace, cx))
 222                .await;
 223        }));
 224    }
 225}
 226
 227struct LspBufferSnapshot {
 228    version: i32,
 229    snapshot: TextBufferSnapshot,
 230}
 231
 232/// Message ordered with respect to buffer operations
 233enum BufferOrderedMessage {
 234    Operation {
 235        buffer_id: u64,
 236        operation: proto::Operation,
 237    },
 238    LanguageServerUpdate {
 239        language_server_id: LanguageServerId,
 240        message: proto::update_language_server::Variant,
 241    },
 242    Resync,
 243}
 244
 245enum LocalProjectUpdate {
 246    WorktreesChanged,
 247    CreateBufferForPeer {
 248        peer_id: proto::PeerId,
 249        buffer_id: u64,
 250    },
 251}
 252
 253enum OpenBuffer {
 254    Strong(ModelHandle<Buffer>),
 255    Weak(WeakModelHandle<Buffer>),
 256    Operations(Vec<Operation>),
 257}
 258
 259#[derive(Clone)]
 260enum WorktreeHandle {
 261    Strong(ModelHandle<Worktree>),
 262    Weak(WeakModelHandle<Worktree>),
 263}
 264
 265enum ProjectClientState {
 266    Local {
 267        remote_id: u64,
 268        updates_tx: mpsc::UnboundedSender<LocalProjectUpdate>,
 269        _send_updates: Task<()>,
 270    },
 271    Remote {
 272        sharing_has_stopped: bool,
 273        remote_id: u64,
 274        replica_id: ReplicaId,
 275    },
 276}
 277
 278#[derive(Clone, Debug, PartialEq)]
 279pub enum Event {
 280    LanguageServerAdded(LanguageServerId),
 281    LanguageServerRemoved(LanguageServerId),
 282    LanguageServerLog(LanguageServerId, String),
 283    Notification(String),
 284    ActiveEntryChanged(Option<ProjectEntryId>),
 285    ActivateProjectPanel,
 286    WorktreeAdded,
 287    WorktreeRemoved(WorktreeId),
 288    WorktreeUpdatedEntries(WorktreeId, UpdatedEntriesSet),
 289    DiskBasedDiagnosticsStarted {
 290        language_server_id: LanguageServerId,
 291    },
 292    DiskBasedDiagnosticsFinished {
 293        language_server_id: LanguageServerId,
 294    },
 295    DiagnosticsUpdated {
 296        path: ProjectPath,
 297        language_server_id: LanguageServerId,
 298    },
 299    RemoteIdChanged(Option<u64>),
 300    DisconnectedFromHost,
 301    Closed,
 302    DeletedEntry(ProjectEntryId),
 303    CollaboratorUpdated {
 304        old_peer_id: proto::PeerId,
 305        new_peer_id: proto::PeerId,
 306    },
 307    CollaboratorJoined(proto::PeerId),
 308    CollaboratorLeft(proto::PeerId),
 309    RefreshInlayHints,
 310}
 311
 312pub enum LanguageServerState {
 313    Starting(Task<Option<Arc<LanguageServer>>>),
 314
 315    Running {
 316        language: Arc<Language>,
 317        adapter: Arc<CachedLspAdapter>,
 318        server: Arc<LanguageServer>,
 319        watched_paths: HashMap<WorktreeId, GlobSet>,
 320        simulate_disk_based_diagnostics_completion: Option<Task<()>>,
 321    },
 322}
 323
 324#[derive(Serialize)]
 325pub struct LanguageServerStatus {
 326    pub name: String,
 327    pub pending_work: BTreeMap<String, LanguageServerProgress>,
 328    pub has_pending_diagnostic_updates: bool,
 329    progress_tokens: HashSet<String>,
 330}
 331
 332#[derive(Clone, Debug, Serialize)]
 333pub struct LanguageServerProgress {
 334    pub message: Option<String>,
 335    pub percentage: Option<usize>,
 336    #[serde(skip_serializing)]
 337    pub last_update_at: Instant,
 338}
 339
 340#[derive(Clone, Debug, Eq, PartialEq, Hash, PartialOrd, Ord)]
 341pub struct ProjectPath {
 342    pub worktree_id: WorktreeId,
 343    pub path: Arc<Path>,
 344}
 345
 346#[derive(Copy, Clone, Debug, Default, PartialEq, Serialize)]
 347pub struct DiagnosticSummary {
 348    pub error_count: usize,
 349    pub warning_count: usize,
 350}
 351
 352#[derive(Debug, Clone, PartialEq, Eq, Hash)]
 353pub struct Location {
 354    pub buffer: ModelHandle<Buffer>,
 355    pub range: Range<language::Anchor>,
 356}
 357
 358#[derive(Debug, Clone, PartialEq, Eq)]
 359pub struct InlayHint {
 360    pub position: language::Anchor,
 361    pub label: InlayHintLabel,
 362    pub kind: Option<InlayHintKind>,
 363    pub padding_left: bool,
 364    pub padding_right: bool,
 365    pub tooltip: Option<InlayHintTooltip>,
 366    pub resolve_state: ResolveState,
 367}
 368
 369#[derive(Debug, Clone, PartialEq, Eq)]
 370pub enum ResolveState {
 371    Resolved,
 372    CanResolve(LanguageServerId, Option<lsp::LSPAny>),
 373    Resolving,
 374}
 375
 376impl InlayHint {
 377    pub fn text(&self) -> String {
 378        match &self.label {
 379            InlayHintLabel::String(s) => s.to_owned(),
 380            InlayHintLabel::LabelParts(parts) => parts.iter().map(|part| &part.value).join(""),
 381        }
 382    }
 383}
 384
 385#[derive(Debug, Clone, PartialEq, Eq)]
 386pub enum InlayHintLabel {
 387    String(String),
 388    LabelParts(Vec<InlayHintLabelPart>),
 389}
 390
 391#[derive(Debug, Clone, PartialEq, Eq)]
 392pub struct InlayHintLabelPart {
 393    pub value: String,
 394    pub tooltip: Option<InlayHintLabelPartTooltip>,
 395    pub location: Option<(LanguageServerId, lsp::Location)>,
 396}
 397
 398#[derive(Debug, Clone, PartialEq, Eq)]
 399pub enum InlayHintTooltip {
 400    String(String),
 401    MarkupContent(MarkupContent),
 402}
 403
 404#[derive(Debug, Clone, PartialEq, Eq)]
 405pub enum InlayHintLabelPartTooltip {
 406    String(String),
 407    MarkupContent(MarkupContent),
 408}
 409
 410#[derive(Debug, Clone, PartialEq, Eq)]
 411pub struct MarkupContent {
 412    pub kind: HoverBlockKind,
 413    pub value: String,
 414}
 415
 416#[derive(Debug, Clone)]
 417pub struct LocationLink {
 418    pub origin: Option<Location>,
 419    pub target: Location,
 420}
 421
 422#[derive(Debug)]
 423pub struct DocumentHighlight {
 424    pub range: Range<language::Anchor>,
 425    pub kind: DocumentHighlightKind,
 426}
 427
 428#[derive(Clone, Debug)]
 429pub struct Symbol {
 430    pub language_server_name: LanguageServerName,
 431    pub source_worktree_id: WorktreeId,
 432    pub path: ProjectPath,
 433    pub label: CodeLabel,
 434    pub name: String,
 435    pub kind: lsp::SymbolKind,
 436    pub range: Range<Unclipped<PointUtf16>>,
 437    pub signature: [u8; 32],
 438}
 439
 440#[derive(Clone, Debug, PartialEq)]
 441pub struct HoverBlock {
 442    pub text: String,
 443    pub kind: HoverBlockKind,
 444}
 445
 446#[derive(Clone, Debug, PartialEq, Eq)]
 447pub enum HoverBlockKind {
 448    PlainText,
 449    Markdown,
 450    Code { language: String },
 451}
 452
 453#[derive(Debug)]
 454pub struct Hover {
 455    pub contents: Vec<HoverBlock>,
 456    pub range: Option<Range<language::Anchor>>,
 457    pub language: Option<Arc<Language>>,
 458}
 459
 460impl Hover {
 461    pub fn is_empty(&self) -> bool {
 462        self.contents.iter().all(|block| block.text.is_empty())
 463    }
 464}
 465
 466#[derive(Default)]
 467pub struct ProjectTransaction(pub HashMap<ModelHandle<Buffer>, language::Transaction>);
 468
 469impl DiagnosticSummary {
 470    fn new<'a, T: 'a>(diagnostics: impl IntoIterator<Item = &'a DiagnosticEntry<T>>) -> Self {
 471        let mut this = Self {
 472            error_count: 0,
 473            warning_count: 0,
 474        };
 475
 476        for entry in diagnostics {
 477            if entry.diagnostic.is_primary {
 478                match entry.diagnostic.severity {
 479                    DiagnosticSeverity::ERROR => this.error_count += 1,
 480                    DiagnosticSeverity::WARNING => this.warning_count += 1,
 481                    _ => {}
 482                }
 483            }
 484        }
 485
 486        this
 487    }
 488
 489    pub fn is_empty(&self) -> bool {
 490        self.error_count == 0 && self.warning_count == 0
 491    }
 492
 493    pub fn to_proto(
 494        &self,
 495        language_server_id: LanguageServerId,
 496        path: &Path,
 497    ) -> proto::DiagnosticSummary {
 498        proto::DiagnosticSummary {
 499            path: path.to_string_lossy().to_string(),
 500            language_server_id: language_server_id.0 as u64,
 501            error_count: self.error_count as u32,
 502            warning_count: self.warning_count as u32,
 503        }
 504    }
 505}
 506
 507#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq, PartialOrd, Ord)]
 508pub struct ProjectEntryId(usize);
 509
 510impl ProjectEntryId {
 511    pub const MAX: Self = Self(usize::MAX);
 512
 513    pub fn new(counter: &AtomicUsize) -> Self {
 514        Self(counter.fetch_add(1, SeqCst))
 515    }
 516
 517    pub fn from_proto(id: u64) -> Self {
 518        Self(id as usize)
 519    }
 520
 521    pub fn to_proto(&self) -> u64 {
 522        self.0 as u64
 523    }
 524
 525    pub fn to_usize(&self) -> usize {
 526        self.0
 527    }
 528}
 529
 530#[derive(Debug, Clone, Copy, PartialEq, Eq)]
 531pub enum FormatTrigger {
 532    Save,
 533    Manual,
 534}
 535
 536struct ProjectLspAdapterDelegate {
 537    project: ModelHandle<Project>,
 538    http_client: Arc<dyn HttpClient>,
 539}
 540
 541impl FormatTrigger {
 542    fn from_proto(value: i32) -> FormatTrigger {
 543        match value {
 544            0 => FormatTrigger::Save,
 545            1 => FormatTrigger::Manual,
 546            _ => FormatTrigger::Save,
 547        }
 548    }
 549}
 550#[derive(Clone, Debug, PartialEq)]
 551enum SearchMatchCandidate {
 552    OpenBuffer {
 553        buffer: ModelHandle<Buffer>,
 554        // This might be an unnamed file without representation on filesystem
 555        path: Option<Arc<Path>>,
 556    },
 557    Path {
 558        worktree_id: WorktreeId,
 559        path: Arc<Path>,
 560    },
 561}
 562
 563type SearchMatchCandidateIndex = usize;
 564impl SearchMatchCandidate {
 565    fn path(&self) -> Option<Arc<Path>> {
 566        match self {
 567            SearchMatchCandidate::OpenBuffer { path, .. } => path.clone(),
 568            SearchMatchCandidate::Path { path, .. } => Some(path.clone()),
 569        }
 570    }
 571}
 572
 573impl Project {
 574    pub fn init_settings(cx: &mut AppContext) {
 575        settings::register::<ProjectSettings>(cx);
 576    }
 577
 578    pub fn init(client: &Arc<Client>, cx: &mut AppContext) {
 579        Self::init_settings(cx);
 580
 581        client.add_model_message_handler(Self::handle_add_collaborator);
 582        client.add_model_message_handler(Self::handle_update_project_collaborator);
 583        client.add_model_message_handler(Self::handle_remove_collaborator);
 584        client.add_model_message_handler(Self::handle_buffer_reloaded);
 585        client.add_model_message_handler(Self::handle_buffer_saved);
 586        client.add_model_message_handler(Self::handle_start_language_server);
 587        client.add_model_message_handler(Self::handle_update_language_server);
 588        client.add_model_message_handler(Self::handle_update_project);
 589        client.add_model_message_handler(Self::handle_unshare_project);
 590        client.add_model_message_handler(Self::handle_create_buffer_for_peer);
 591        client.add_model_message_handler(Self::handle_update_buffer_file);
 592        client.add_model_request_handler(Self::handle_update_buffer);
 593        client.add_model_message_handler(Self::handle_update_diagnostic_summary);
 594        client.add_model_message_handler(Self::handle_update_worktree);
 595        client.add_model_message_handler(Self::handle_update_worktree_settings);
 596        client.add_model_request_handler(Self::handle_create_project_entry);
 597        client.add_model_request_handler(Self::handle_rename_project_entry);
 598        client.add_model_request_handler(Self::handle_copy_project_entry);
 599        client.add_model_request_handler(Self::handle_delete_project_entry);
 600        client.add_model_request_handler(Self::handle_expand_project_entry);
 601        client.add_model_request_handler(Self::handle_apply_additional_edits_for_completion);
 602        client.add_model_request_handler(Self::handle_apply_code_action);
 603        client.add_model_request_handler(Self::handle_on_type_formatting);
 604        client.add_model_request_handler(Self::handle_inlay_hints);
 605        client.add_model_request_handler(Self::handle_resolve_completion_documentation);
 606        client.add_model_request_handler(Self::handle_resolve_inlay_hint);
 607        client.add_model_request_handler(Self::handle_refresh_inlay_hints);
 608        client.add_model_request_handler(Self::handle_reload_buffers);
 609        client.add_model_request_handler(Self::handle_synchronize_buffers);
 610        client.add_model_request_handler(Self::handle_format_buffers);
 611        client.add_model_request_handler(Self::handle_lsp_command::<GetCodeActions>);
 612        client.add_model_request_handler(Self::handle_lsp_command::<GetCompletions>);
 613        client.add_model_request_handler(Self::handle_lsp_command::<GetHover>);
 614        client.add_model_request_handler(Self::handle_lsp_command::<GetDefinition>);
 615        client.add_model_request_handler(Self::handle_lsp_command::<GetTypeDefinition>);
 616        client.add_model_request_handler(Self::handle_lsp_command::<GetDocumentHighlights>);
 617        client.add_model_request_handler(Self::handle_lsp_command::<GetReferences>);
 618        client.add_model_request_handler(Self::handle_lsp_command::<PrepareRename>);
 619        client.add_model_request_handler(Self::handle_lsp_command::<PerformRename>);
 620        client.add_model_request_handler(Self::handle_search_project);
 621        client.add_model_request_handler(Self::handle_get_project_symbols);
 622        client.add_model_request_handler(Self::handle_open_buffer_for_symbol);
 623        client.add_model_request_handler(Self::handle_open_buffer_by_id);
 624        client.add_model_request_handler(Self::handle_open_buffer_by_path);
 625        client.add_model_request_handler(Self::handle_save_buffer);
 626        client.add_model_message_handler(Self::handle_update_diff_base);
 627    }
 628
 629    pub fn local(
 630        client: Arc<Client>,
 631        node: Arc<dyn NodeRuntime>,
 632        user_store: ModelHandle<UserStore>,
 633        languages: Arc<LanguageRegistry>,
 634        fs: Arc<dyn Fs>,
 635        cx: &mut AppContext,
 636    ) -> ModelHandle<Self> {
 637        cx.add_model(|cx: &mut ModelContext<Self>| {
 638            let (tx, rx) = mpsc::unbounded();
 639            cx.spawn_weak(|this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
 640                .detach();
 641            let copilot_lsp_subscription =
 642                Copilot::global(cx).map(|copilot| subscribe_for_copilot_events(&copilot, cx));
 643            Self {
 644                worktrees: Default::default(),
 645                buffer_ordered_messages_tx: tx,
 646                collaborators: Default::default(),
 647                next_buffer_id: 0,
 648                opened_buffers: Default::default(),
 649                shared_buffers: Default::default(),
 650                incomplete_remote_buffers: Default::default(),
 651                loading_buffers_by_path: Default::default(),
 652                loading_local_worktrees: Default::default(),
 653                local_buffer_ids_by_path: Default::default(),
 654                local_buffer_ids_by_entry_id: Default::default(),
 655                buffer_snapshots: Default::default(),
 656                join_project_response_message_id: 0,
 657                client_state: None,
 658                opened_buffer: watch::channel(),
 659                client_subscriptions: Vec::new(),
 660                _subscriptions: vec![
 661                    cx.observe_global::<SettingsStore, _>(Self::on_settings_changed)
 662                ],
 663                _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
 664                _maintain_workspace_config: Self::maintain_workspace_config(cx),
 665                active_entry: None,
 666                languages,
 667                client,
 668                user_store,
 669                fs,
 670                next_entry_id: Default::default(),
 671                next_diagnostic_group_id: Default::default(),
 672                supplementary_language_servers: HashMap::default(),
 673                language_servers: Default::default(),
 674                language_server_ids: Default::default(),
 675                language_server_statuses: Default::default(),
 676                last_workspace_edits_by_language_server: Default::default(),
 677                buffers_being_formatted: Default::default(),
 678                buffers_needing_diff: Default::default(),
 679                git_diff_debouncer: DelayedDebounced::new(),
 680                nonce: StdRng::from_entropy().gen(),
 681                terminals: Terminals {
 682                    local_handles: Vec::new(),
 683                },
 684                copilot_lsp_subscription,
 685                copilot_log_subscription: None,
 686                current_lsp_settings: settings::get::<ProjectSettings>(cx).lsp.clone(),
 687                node: Some(node),
 688                default_prettier: None,
 689                prettiers_per_worktree: HashMap::default(),
 690                prettier_instances: HashMap::default(),
 691            }
 692        })
 693    }
 694
 695    pub async fn remote(
 696        remote_id: u64,
 697        client: Arc<Client>,
 698        user_store: ModelHandle<UserStore>,
 699        languages: Arc<LanguageRegistry>,
 700        fs: Arc<dyn Fs>,
 701        mut cx: AsyncAppContext,
 702    ) -> Result<ModelHandle<Self>> {
 703        client.authenticate_and_connect(true, &cx).await?;
 704
 705        let subscription = client.subscribe_to_entity(remote_id)?;
 706        let response = client
 707            .request_envelope(proto::JoinProject {
 708                project_id: remote_id,
 709            })
 710            .await?;
 711        let this = cx.add_model(|cx| {
 712            let replica_id = response.payload.replica_id as ReplicaId;
 713
 714            let mut worktrees = Vec::new();
 715            for worktree in response.payload.worktrees {
 716                let worktree = cx.update(|cx| {
 717                    Worktree::remote(remote_id, replica_id, worktree, client.clone(), cx)
 718                });
 719                worktrees.push(worktree);
 720            }
 721
 722            let (tx, rx) = mpsc::unbounded();
 723            cx.spawn_weak(|this, cx| Self::send_buffer_ordered_messages(this, rx, cx))
 724                .detach();
 725            let copilot_lsp_subscription =
 726                Copilot::global(cx).map(|copilot| subscribe_for_copilot_events(&copilot, cx));
 727            let mut this = Self {
 728                worktrees: Vec::new(),
 729                buffer_ordered_messages_tx: tx,
 730                loading_buffers_by_path: Default::default(),
 731                next_buffer_id: 0,
 732                opened_buffer: watch::channel(),
 733                shared_buffers: Default::default(),
 734                incomplete_remote_buffers: Default::default(),
 735                loading_local_worktrees: Default::default(),
 736                local_buffer_ids_by_path: Default::default(),
 737                local_buffer_ids_by_entry_id: Default::default(),
 738                active_entry: None,
 739                collaborators: Default::default(),
 740                join_project_response_message_id: response.message_id,
 741                _maintain_buffer_languages: Self::maintain_buffer_languages(languages.clone(), cx),
 742                _maintain_workspace_config: Self::maintain_workspace_config(cx),
 743                languages,
 744                user_store: user_store.clone(),
 745                fs,
 746                next_entry_id: Default::default(),
 747                next_diagnostic_group_id: Default::default(),
 748                client_subscriptions: Default::default(),
 749                _subscriptions: Default::default(),
 750                client: client.clone(),
 751                client_state: Some(ProjectClientState::Remote {
 752                    sharing_has_stopped: false,
 753                    remote_id,
 754                    replica_id,
 755                }),
 756                supplementary_language_servers: HashMap::default(),
 757                language_servers: Default::default(),
 758                language_server_ids: Default::default(),
 759                language_server_statuses: response
 760                    .payload
 761                    .language_servers
 762                    .into_iter()
 763                    .map(|server| {
 764                        (
 765                            LanguageServerId(server.id as usize),
 766                            LanguageServerStatus {
 767                                name: server.name,
 768                                pending_work: Default::default(),
 769                                has_pending_diagnostic_updates: false,
 770                                progress_tokens: Default::default(),
 771                            },
 772                        )
 773                    })
 774                    .collect(),
 775                last_workspace_edits_by_language_server: Default::default(),
 776                opened_buffers: Default::default(),
 777                buffers_being_formatted: Default::default(),
 778                buffers_needing_diff: Default::default(),
 779                git_diff_debouncer: DelayedDebounced::new(),
 780                buffer_snapshots: Default::default(),
 781                nonce: StdRng::from_entropy().gen(),
 782                terminals: Terminals {
 783                    local_handles: Vec::new(),
 784                },
 785                copilot_lsp_subscription,
 786                copilot_log_subscription: None,
 787                current_lsp_settings: settings::get::<ProjectSettings>(cx).lsp.clone(),
 788                node: None,
 789                default_prettier: None,
 790                prettiers_per_worktree: HashMap::default(),
 791                prettier_instances: HashMap::default(),
 792            };
 793            for worktree in worktrees {
 794                let _ = this.add_worktree(&worktree, cx);
 795            }
 796            this
 797        });
 798        let subscription = subscription.set_model(&this, &mut cx);
 799
 800        let user_ids = response
 801            .payload
 802            .collaborators
 803            .iter()
 804            .map(|peer| peer.user_id)
 805            .collect();
 806        user_store
 807            .update(&mut cx, |user_store, cx| user_store.get_users(user_ids, cx))
 808            .await?;
 809
 810        this.update(&mut cx, |this, cx| {
 811            this.set_collaborators_from_proto(response.payload.collaborators, cx)?;
 812            this.client_subscriptions.push(subscription);
 813            anyhow::Ok(())
 814        })?;
 815
 816        Ok(this)
 817    }
 818
 819    #[cfg(any(test, feature = "test-support"))]
 820    pub async fn test(
 821        fs: Arc<dyn Fs>,
 822        root_paths: impl IntoIterator<Item = &Path>,
 823        cx: &mut gpui::TestAppContext,
 824    ) -> ModelHandle<Project> {
 825        let mut languages = LanguageRegistry::test();
 826        languages.set_executor(cx.background());
 827        let http_client = util::http::FakeHttpClient::with_404_response();
 828        let client = cx.update(|cx| client::Client::new(http_client.clone(), cx));
 829        let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http_client, cx));
 830        let project = cx.update(|cx| {
 831            Project::local(
 832                client,
 833                node_runtime::FakeNodeRuntime::new(),
 834                user_store,
 835                Arc::new(languages),
 836                fs,
 837                cx,
 838            )
 839        });
 840        for path in root_paths {
 841            let (tree, _) = project
 842                .update(cx, |project, cx| {
 843                    project.find_or_create_local_worktree(path, true, cx)
 844                })
 845                .await
 846                .unwrap();
 847            tree.read_with(cx, |tree, _| tree.as_local().unwrap().scan_complete())
 848                .await;
 849        }
 850        project
 851    }
 852
 853    fn on_settings_changed(&mut self, cx: &mut ModelContext<Self>) {
 854        let mut language_servers_to_start = Vec::new();
 855        let mut language_formatters_to_check = Vec::new();
 856        for buffer in self.opened_buffers.values() {
 857            if let Some(buffer) = buffer.upgrade(cx) {
 858                let buffer = buffer.read(cx);
 859                let buffer_file = File::from_dyn(buffer.file());
 860                let buffer_language = buffer.language();
 861                let settings = language_settings(buffer_language, buffer.file(), cx);
 862                if let Some(language) = buffer_language {
 863                    if settings.enable_language_server {
 864                        if let Some(file) = buffer_file {
 865                            language_servers_to_start
 866                                .push((file.worktree.clone(), Arc::clone(language)));
 867                        }
 868                    }
 869                    language_formatters_to_check.push((
 870                        buffer_file.map(|f| f.worktree_id(cx)),
 871                        Arc::clone(language),
 872                        settings.clone(),
 873                    ));
 874                }
 875            }
 876        }
 877
 878        let mut language_servers_to_stop = Vec::new();
 879        let mut language_servers_to_restart = Vec::new();
 880        let languages = self.languages.to_vec();
 881
 882        let new_lsp_settings = settings::get::<ProjectSettings>(cx).lsp.clone();
 883        let current_lsp_settings = &self.current_lsp_settings;
 884        for (worktree_id, started_lsp_name) in self.language_server_ids.keys() {
 885            let language = languages.iter().find_map(|l| {
 886                let adapter = l
 887                    .lsp_adapters()
 888                    .iter()
 889                    .find(|adapter| &adapter.name == started_lsp_name)?;
 890                Some((l, adapter))
 891            });
 892            if let Some((language, adapter)) = language {
 893                let worktree = self.worktree_for_id(*worktree_id, cx);
 894                let file = worktree.as_ref().and_then(|tree| {
 895                    tree.update(cx, |tree, cx| tree.root_file(cx).map(|f| f as _))
 896                });
 897                if !language_settings(Some(language), file.as_ref(), cx).enable_language_server {
 898                    language_servers_to_stop.push((*worktree_id, started_lsp_name.clone()));
 899                } else if let Some(worktree) = worktree {
 900                    let server_name = &adapter.name.0;
 901                    match (
 902                        current_lsp_settings.get(server_name),
 903                        new_lsp_settings.get(server_name),
 904                    ) {
 905                        (None, None) => {}
 906                        (Some(_), None) | (None, Some(_)) => {
 907                            language_servers_to_restart.push((worktree, Arc::clone(language)));
 908                        }
 909                        (Some(current_lsp_settings), Some(new_lsp_settings)) => {
 910                            if current_lsp_settings != new_lsp_settings {
 911                                language_servers_to_restart.push((worktree, Arc::clone(language)));
 912                            }
 913                        }
 914                    }
 915                }
 916            }
 917        }
 918        self.current_lsp_settings = new_lsp_settings;
 919
 920        // Stop all newly-disabled language servers.
 921        for (worktree_id, adapter_name) in language_servers_to_stop {
 922            self.stop_language_server(worktree_id, adapter_name, cx)
 923                .detach();
 924        }
 925
 926        for (worktree, language, settings) in language_formatters_to_check {
 927            self.install_default_formatters(worktree, &language, &settings, cx)
 928                .detach_and_log_err(cx);
 929        }
 930
 931        // Start all the newly-enabled language servers.
 932        for (worktree, language) in language_servers_to_start {
 933            let worktree_path = worktree.read(cx).abs_path();
 934            self.start_language_servers(&worktree, worktree_path, language, cx);
 935        }
 936
 937        // Restart all language servers with changed initialization options.
 938        for (worktree, language) in language_servers_to_restart {
 939            self.restart_language_servers(worktree, language, cx);
 940        }
 941
 942        if self.copilot_lsp_subscription.is_none() {
 943            if let Some(copilot) = Copilot::global(cx) {
 944                for buffer in self.opened_buffers.values() {
 945                    if let Some(buffer) = buffer.upgrade(cx) {
 946                        self.register_buffer_with_copilot(&buffer, cx);
 947                    }
 948                }
 949                self.copilot_lsp_subscription = Some(subscribe_for_copilot_events(&copilot, cx));
 950            }
 951        }
 952
 953        cx.notify();
 954    }
 955
 956    pub fn buffer_for_id(&self, remote_id: u64, cx: &AppContext) -> Option<ModelHandle<Buffer>> {
 957        self.opened_buffers
 958            .get(&remote_id)
 959            .and_then(|buffer| buffer.upgrade(cx))
 960    }
 961
 962    pub fn languages(&self) -> &Arc<LanguageRegistry> {
 963        &self.languages
 964    }
 965
 966    pub fn client(&self) -> Arc<Client> {
 967        self.client.clone()
 968    }
 969
 970    pub fn user_store(&self) -> ModelHandle<UserStore> {
 971        self.user_store.clone()
 972    }
 973
 974    pub fn opened_buffers(&self, cx: &AppContext) -> Vec<ModelHandle<Buffer>> {
 975        self.opened_buffers
 976            .values()
 977            .filter_map(|b| b.upgrade(cx))
 978            .collect()
 979    }
 980
 981    #[cfg(any(test, feature = "test-support"))]
 982    pub fn has_open_buffer(&self, path: impl Into<ProjectPath>, cx: &AppContext) -> bool {
 983        let path = path.into();
 984        if let Some(worktree) = self.worktree_for_id(path.worktree_id, cx) {
 985            self.opened_buffers.iter().any(|(_, buffer)| {
 986                if let Some(buffer) = buffer.upgrade(cx) {
 987                    if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
 988                        if file.worktree == worktree && file.path() == &path.path {
 989                            return true;
 990                        }
 991                    }
 992                }
 993                false
 994            })
 995        } else {
 996            false
 997        }
 998    }
 999
1000    pub fn fs(&self) -> &Arc<dyn Fs> {
1001        &self.fs
1002    }
1003
1004    pub fn remote_id(&self) -> Option<u64> {
1005        match self.client_state.as_ref()? {
1006            ProjectClientState::Local { remote_id, .. }
1007            | ProjectClientState::Remote { remote_id, .. } => Some(*remote_id),
1008        }
1009    }
1010
1011    pub fn replica_id(&self) -> ReplicaId {
1012        match &self.client_state {
1013            Some(ProjectClientState::Remote { replica_id, .. }) => *replica_id,
1014            _ => 0,
1015        }
1016    }
1017
1018    fn metadata_changed(&mut self, cx: &mut ModelContext<Self>) {
1019        if let Some(ProjectClientState::Local { updates_tx, .. }) = &mut self.client_state {
1020            updates_tx
1021                .unbounded_send(LocalProjectUpdate::WorktreesChanged)
1022                .ok();
1023        }
1024        cx.notify();
1025    }
1026
1027    pub fn collaborators(&self) -> &HashMap<proto::PeerId, Collaborator> {
1028        &self.collaborators
1029    }
1030
1031    pub fn host(&self) -> Option<&Collaborator> {
1032        self.collaborators.values().find(|c| c.replica_id == 0)
1033    }
1034
1035    /// Collect all worktrees, including ones that don't appear in the project panel
1036    pub fn worktrees<'a>(
1037        &'a self,
1038        cx: &'a AppContext,
1039    ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
1040        self.worktrees
1041            .iter()
1042            .filter_map(move |worktree| worktree.upgrade(cx))
1043    }
1044
1045    /// Collect all user-visible worktrees, the ones that appear in the project panel
1046    pub fn visible_worktrees<'a>(
1047        &'a self,
1048        cx: &'a AppContext,
1049    ) -> impl 'a + DoubleEndedIterator<Item = ModelHandle<Worktree>> {
1050        self.worktrees.iter().filter_map(|worktree| {
1051            worktree.upgrade(cx).and_then(|worktree| {
1052                if worktree.read(cx).is_visible() {
1053                    Some(worktree)
1054                } else {
1055                    None
1056                }
1057            })
1058        })
1059    }
1060
1061    pub fn worktree_root_names<'a>(&'a self, cx: &'a AppContext) -> impl Iterator<Item = &'a str> {
1062        self.visible_worktrees(cx)
1063            .map(|tree| tree.read(cx).root_name())
1064    }
1065
1066    pub fn worktree_for_id(
1067        &self,
1068        id: WorktreeId,
1069        cx: &AppContext,
1070    ) -> Option<ModelHandle<Worktree>> {
1071        self.worktrees(cx)
1072            .find(|worktree| worktree.read(cx).id() == id)
1073    }
1074
1075    pub fn worktree_for_entry(
1076        &self,
1077        entry_id: ProjectEntryId,
1078        cx: &AppContext,
1079    ) -> Option<ModelHandle<Worktree>> {
1080        self.worktrees(cx)
1081            .find(|worktree| worktree.read(cx).contains_entry(entry_id))
1082    }
1083
1084    pub fn worktree_id_for_entry(
1085        &self,
1086        entry_id: ProjectEntryId,
1087        cx: &AppContext,
1088    ) -> Option<WorktreeId> {
1089        self.worktree_for_entry(entry_id, cx)
1090            .map(|worktree| worktree.read(cx).id())
1091    }
1092
1093    pub fn contains_paths(&self, paths: &[PathBuf], cx: &AppContext) -> bool {
1094        paths.iter().all(|path| self.contains_path(path, cx))
1095    }
1096
1097    pub fn contains_path(&self, path: &Path, cx: &AppContext) -> bool {
1098        for worktree in self.worktrees(cx) {
1099            let worktree = worktree.read(cx).as_local();
1100            if worktree.map_or(false, |w| w.contains_abs_path(path)) {
1101                return true;
1102            }
1103        }
1104        false
1105    }
1106
1107    pub fn create_entry(
1108        &mut self,
1109        project_path: impl Into<ProjectPath>,
1110        is_directory: bool,
1111        cx: &mut ModelContext<Self>,
1112    ) -> Option<Task<Result<Entry>>> {
1113        let project_path = project_path.into();
1114        let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
1115        if self.is_local() {
1116            Some(worktree.update(cx, |worktree, cx| {
1117                worktree
1118                    .as_local_mut()
1119                    .unwrap()
1120                    .create_entry(project_path.path, is_directory, cx)
1121            }))
1122        } else {
1123            let client = self.client.clone();
1124            let project_id = self.remote_id().unwrap();
1125            Some(cx.spawn_weak(|_, mut cx| async move {
1126                let response = client
1127                    .request(proto::CreateProjectEntry {
1128                        worktree_id: project_path.worktree_id.to_proto(),
1129                        project_id,
1130                        path: project_path.path.to_string_lossy().into(),
1131                        is_directory,
1132                    })
1133                    .await?;
1134                let entry = response
1135                    .entry
1136                    .ok_or_else(|| anyhow!("missing entry in response"))?;
1137                worktree
1138                    .update(&mut cx, |worktree, cx| {
1139                        worktree.as_remote_mut().unwrap().insert_entry(
1140                            entry,
1141                            response.worktree_scan_id as usize,
1142                            cx,
1143                        )
1144                    })
1145                    .await
1146            }))
1147        }
1148    }
1149
1150    pub fn copy_entry(
1151        &mut self,
1152        entry_id: ProjectEntryId,
1153        new_path: impl Into<Arc<Path>>,
1154        cx: &mut ModelContext<Self>,
1155    ) -> Option<Task<Result<Entry>>> {
1156        let worktree = self.worktree_for_entry(entry_id, cx)?;
1157        let new_path = new_path.into();
1158        if self.is_local() {
1159            worktree.update(cx, |worktree, cx| {
1160                worktree
1161                    .as_local_mut()
1162                    .unwrap()
1163                    .copy_entry(entry_id, new_path, cx)
1164            })
1165        } else {
1166            let client = self.client.clone();
1167            let project_id = self.remote_id().unwrap();
1168
1169            Some(cx.spawn_weak(|_, mut cx| async move {
1170                let response = client
1171                    .request(proto::CopyProjectEntry {
1172                        project_id,
1173                        entry_id: entry_id.to_proto(),
1174                        new_path: new_path.to_string_lossy().into(),
1175                    })
1176                    .await?;
1177                let entry = response
1178                    .entry
1179                    .ok_or_else(|| anyhow!("missing entry in response"))?;
1180                worktree
1181                    .update(&mut cx, |worktree, cx| {
1182                        worktree.as_remote_mut().unwrap().insert_entry(
1183                            entry,
1184                            response.worktree_scan_id as usize,
1185                            cx,
1186                        )
1187                    })
1188                    .await
1189            }))
1190        }
1191    }
1192
1193    pub fn rename_entry(
1194        &mut self,
1195        entry_id: ProjectEntryId,
1196        new_path: impl Into<Arc<Path>>,
1197        cx: &mut ModelContext<Self>,
1198    ) -> Option<Task<Result<Entry>>> {
1199        let worktree = self.worktree_for_entry(entry_id, cx)?;
1200        let new_path = new_path.into();
1201        if self.is_local() {
1202            worktree.update(cx, |worktree, cx| {
1203                worktree
1204                    .as_local_mut()
1205                    .unwrap()
1206                    .rename_entry(entry_id, new_path, cx)
1207            })
1208        } else {
1209            let client = self.client.clone();
1210            let project_id = self.remote_id().unwrap();
1211
1212            Some(cx.spawn_weak(|_, mut cx| async move {
1213                let response = client
1214                    .request(proto::RenameProjectEntry {
1215                        project_id,
1216                        entry_id: entry_id.to_proto(),
1217                        new_path: new_path.to_string_lossy().into(),
1218                    })
1219                    .await?;
1220                let entry = response
1221                    .entry
1222                    .ok_or_else(|| anyhow!("missing entry in response"))?;
1223                worktree
1224                    .update(&mut cx, |worktree, cx| {
1225                        worktree.as_remote_mut().unwrap().insert_entry(
1226                            entry,
1227                            response.worktree_scan_id as usize,
1228                            cx,
1229                        )
1230                    })
1231                    .await
1232            }))
1233        }
1234    }
1235
1236    pub fn delete_entry(
1237        &mut self,
1238        entry_id: ProjectEntryId,
1239        cx: &mut ModelContext<Self>,
1240    ) -> Option<Task<Result<()>>> {
1241        let worktree = self.worktree_for_entry(entry_id, cx)?;
1242
1243        cx.emit(Event::DeletedEntry(entry_id));
1244
1245        if self.is_local() {
1246            worktree.update(cx, |worktree, cx| {
1247                worktree.as_local_mut().unwrap().delete_entry(entry_id, cx)
1248            })
1249        } else {
1250            let client = self.client.clone();
1251            let project_id = self.remote_id().unwrap();
1252            Some(cx.spawn_weak(|_, mut cx| async move {
1253                let response = client
1254                    .request(proto::DeleteProjectEntry {
1255                        project_id,
1256                        entry_id: entry_id.to_proto(),
1257                    })
1258                    .await?;
1259                worktree
1260                    .update(&mut cx, move |worktree, cx| {
1261                        worktree.as_remote_mut().unwrap().delete_entry(
1262                            entry_id,
1263                            response.worktree_scan_id as usize,
1264                            cx,
1265                        )
1266                    })
1267                    .await
1268            }))
1269        }
1270    }
1271
1272    pub fn expand_entry(
1273        &mut self,
1274        worktree_id: WorktreeId,
1275        entry_id: ProjectEntryId,
1276        cx: &mut ModelContext<Self>,
1277    ) -> Option<Task<Result<()>>> {
1278        let worktree = self.worktree_for_id(worktree_id, cx)?;
1279        if self.is_local() {
1280            worktree.update(cx, |worktree, cx| {
1281                worktree.as_local_mut().unwrap().expand_entry(entry_id, cx)
1282            })
1283        } else {
1284            let worktree = worktree.downgrade();
1285            let request = self.client.request(proto::ExpandProjectEntry {
1286                project_id: self.remote_id().unwrap(),
1287                entry_id: entry_id.to_proto(),
1288            });
1289            Some(cx.spawn_weak(|_, mut cx| async move {
1290                let response = request.await?;
1291                if let Some(worktree) = worktree.upgrade(&cx) {
1292                    worktree
1293                        .update(&mut cx, |worktree, _| {
1294                            worktree
1295                                .as_remote_mut()
1296                                .unwrap()
1297                                .wait_for_snapshot(response.worktree_scan_id as usize)
1298                        })
1299                        .await?;
1300                }
1301                Ok(())
1302            }))
1303        }
1304    }
1305
1306    pub fn shared(&mut self, project_id: u64, cx: &mut ModelContext<Self>) -> Result<()> {
1307        if self.client_state.is_some() {
1308            return Err(anyhow!("project was already shared"));
1309        }
1310        self.client_subscriptions.push(
1311            self.client
1312                .subscribe_to_entity(project_id)?
1313                .set_model(&cx.handle(), &mut cx.to_async()),
1314        );
1315
1316        for open_buffer in self.opened_buffers.values_mut() {
1317            match open_buffer {
1318                OpenBuffer::Strong(_) => {}
1319                OpenBuffer::Weak(buffer) => {
1320                    if let Some(buffer) = buffer.upgrade(cx) {
1321                        *open_buffer = OpenBuffer::Strong(buffer);
1322                    }
1323                }
1324                OpenBuffer::Operations(_) => unreachable!(),
1325            }
1326        }
1327
1328        for worktree_handle in self.worktrees.iter_mut() {
1329            match worktree_handle {
1330                WorktreeHandle::Strong(_) => {}
1331                WorktreeHandle::Weak(worktree) => {
1332                    if let Some(worktree) = worktree.upgrade(cx) {
1333                        *worktree_handle = WorktreeHandle::Strong(worktree);
1334                    }
1335                }
1336            }
1337        }
1338
1339        for (server_id, status) in &self.language_server_statuses {
1340            self.client
1341                .send(proto::StartLanguageServer {
1342                    project_id,
1343                    server: Some(proto::LanguageServer {
1344                        id: server_id.0 as u64,
1345                        name: status.name.clone(),
1346                    }),
1347                })
1348                .log_err();
1349        }
1350
1351        let store = cx.global::<SettingsStore>();
1352        for worktree in self.worktrees(cx) {
1353            let worktree_id = worktree.read(cx).id().to_proto();
1354            for (path, content) in store.local_settings(worktree.id()) {
1355                self.client
1356                    .send(proto::UpdateWorktreeSettings {
1357                        project_id,
1358                        worktree_id,
1359                        path: path.to_string_lossy().into(),
1360                        content: Some(content),
1361                    })
1362                    .log_err();
1363            }
1364        }
1365
1366        let (updates_tx, mut updates_rx) = mpsc::unbounded();
1367        let client = self.client.clone();
1368        self.client_state = Some(ProjectClientState::Local {
1369            remote_id: project_id,
1370            updates_tx,
1371            _send_updates: cx.spawn_weak(move |this, mut cx| async move {
1372                while let Some(update) = updates_rx.next().await {
1373                    let Some(this) = this.upgrade(&cx) else { break };
1374
1375                    match update {
1376                        LocalProjectUpdate::WorktreesChanged => {
1377                            let worktrees = this
1378                                .read_with(&cx, |this, cx| this.worktrees(cx).collect::<Vec<_>>());
1379                            let update_project = this
1380                                .read_with(&cx, |this, cx| {
1381                                    this.client.request(proto::UpdateProject {
1382                                        project_id,
1383                                        worktrees: this.worktree_metadata_protos(cx),
1384                                    })
1385                                })
1386                                .await;
1387                            if update_project.is_ok() {
1388                                for worktree in worktrees {
1389                                    worktree.update(&mut cx, |worktree, cx| {
1390                                        let worktree = worktree.as_local_mut().unwrap();
1391                                        worktree.share(project_id, cx).detach_and_log_err(cx)
1392                                    });
1393                                }
1394                            }
1395                        }
1396                        LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id } => {
1397                            let buffer = this.update(&mut cx, |this, _| {
1398                                let buffer = this.opened_buffers.get(&buffer_id).unwrap();
1399                                let shared_buffers =
1400                                    this.shared_buffers.entry(peer_id).or_default();
1401                                if shared_buffers.insert(buffer_id) {
1402                                    if let OpenBuffer::Strong(buffer) = buffer {
1403                                        Some(buffer.clone())
1404                                    } else {
1405                                        None
1406                                    }
1407                                } else {
1408                                    None
1409                                }
1410                            });
1411
1412                            let Some(buffer) = buffer else { continue };
1413                            let operations =
1414                                buffer.read_with(&cx, |b, cx| b.serialize_ops(None, cx));
1415                            let operations = operations.await;
1416                            let state = buffer.read_with(&cx, |buffer, _| buffer.to_proto());
1417
1418                            let initial_state = proto::CreateBufferForPeer {
1419                                project_id,
1420                                peer_id: Some(peer_id),
1421                                variant: Some(proto::create_buffer_for_peer::Variant::State(state)),
1422                            };
1423                            if client.send(initial_state).log_err().is_some() {
1424                                let client = client.clone();
1425                                cx.background()
1426                                    .spawn(async move {
1427                                        let mut chunks = split_operations(operations).peekable();
1428                                        while let Some(chunk) = chunks.next() {
1429                                            let is_last = chunks.peek().is_none();
1430                                            client.send(proto::CreateBufferForPeer {
1431                                                project_id,
1432                                                peer_id: Some(peer_id),
1433                                                variant: Some(
1434                                                    proto::create_buffer_for_peer::Variant::Chunk(
1435                                                        proto::BufferChunk {
1436                                                            buffer_id,
1437                                                            operations: chunk,
1438                                                            is_last,
1439                                                        },
1440                                                    ),
1441                                                ),
1442                                            })?;
1443                                        }
1444                                        anyhow::Ok(())
1445                                    })
1446                                    .await
1447                                    .log_err();
1448                            }
1449                        }
1450                    }
1451                }
1452            }),
1453        });
1454
1455        self.metadata_changed(cx);
1456        cx.emit(Event::RemoteIdChanged(Some(project_id)));
1457        cx.notify();
1458        Ok(())
1459    }
1460
1461    pub fn reshared(
1462        &mut self,
1463        message: proto::ResharedProject,
1464        cx: &mut ModelContext<Self>,
1465    ) -> Result<()> {
1466        self.shared_buffers.clear();
1467        self.set_collaborators_from_proto(message.collaborators, cx)?;
1468        self.metadata_changed(cx);
1469        Ok(())
1470    }
1471
1472    pub fn rejoined(
1473        &mut self,
1474        message: proto::RejoinedProject,
1475        message_id: u32,
1476        cx: &mut ModelContext<Self>,
1477    ) -> Result<()> {
1478        cx.update_global::<SettingsStore, _, _>(|store, cx| {
1479            for worktree in &self.worktrees {
1480                store
1481                    .clear_local_settings(worktree.handle_id(), cx)
1482                    .log_err();
1483            }
1484        });
1485
1486        self.join_project_response_message_id = message_id;
1487        self.set_worktrees_from_proto(message.worktrees, cx)?;
1488        self.set_collaborators_from_proto(message.collaborators, cx)?;
1489        self.language_server_statuses = message
1490            .language_servers
1491            .into_iter()
1492            .map(|server| {
1493                (
1494                    LanguageServerId(server.id as usize),
1495                    LanguageServerStatus {
1496                        name: server.name,
1497                        pending_work: Default::default(),
1498                        has_pending_diagnostic_updates: false,
1499                        progress_tokens: Default::default(),
1500                    },
1501                )
1502            })
1503            .collect();
1504        self.buffer_ordered_messages_tx
1505            .unbounded_send(BufferOrderedMessage::Resync)
1506            .unwrap();
1507        cx.notify();
1508        Ok(())
1509    }
1510
1511    pub fn unshare(&mut self, cx: &mut ModelContext<Self>) -> Result<()> {
1512        self.unshare_internal(cx)?;
1513        self.metadata_changed(cx);
1514        cx.notify();
1515        Ok(())
1516    }
1517
1518    fn unshare_internal(&mut self, cx: &mut AppContext) -> Result<()> {
1519        if self.is_remote() {
1520            return Err(anyhow!("attempted to unshare a remote project"));
1521        }
1522
1523        if let Some(ProjectClientState::Local { remote_id, .. }) = self.client_state.take() {
1524            self.collaborators.clear();
1525            self.shared_buffers.clear();
1526            self.client_subscriptions.clear();
1527
1528            for worktree_handle in self.worktrees.iter_mut() {
1529                if let WorktreeHandle::Strong(worktree) = worktree_handle {
1530                    let is_visible = worktree.update(cx, |worktree, _| {
1531                        worktree.as_local_mut().unwrap().unshare();
1532                        worktree.is_visible()
1533                    });
1534                    if !is_visible {
1535                        *worktree_handle = WorktreeHandle::Weak(worktree.downgrade());
1536                    }
1537                }
1538            }
1539
1540            for open_buffer in self.opened_buffers.values_mut() {
1541                // Wake up any tasks waiting for peers' edits to this buffer.
1542                if let Some(buffer) = open_buffer.upgrade(cx) {
1543                    buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1544                }
1545
1546                if let OpenBuffer::Strong(buffer) = open_buffer {
1547                    *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1548                }
1549            }
1550
1551            self.client.send(proto::UnshareProject {
1552                project_id: remote_id,
1553            })?;
1554
1555            Ok(())
1556        } else {
1557            Err(anyhow!("attempted to unshare an unshared project"))
1558        }
1559    }
1560
1561    pub fn disconnected_from_host(&mut self, cx: &mut ModelContext<Self>) {
1562        self.disconnected_from_host_internal(cx);
1563        cx.emit(Event::DisconnectedFromHost);
1564        cx.notify();
1565    }
1566
1567    fn disconnected_from_host_internal(&mut self, cx: &mut AppContext) {
1568        if let Some(ProjectClientState::Remote {
1569            sharing_has_stopped,
1570            ..
1571        }) = &mut self.client_state
1572        {
1573            *sharing_has_stopped = true;
1574
1575            self.collaborators.clear();
1576
1577            for worktree in &self.worktrees {
1578                if let Some(worktree) = worktree.upgrade(cx) {
1579                    worktree.update(cx, |worktree, _| {
1580                        if let Some(worktree) = worktree.as_remote_mut() {
1581                            worktree.disconnected_from_host();
1582                        }
1583                    });
1584                }
1585            }
1586
1587            for open_buffer in self.opened_buffers.values_mut() {
1588                // Wake up any tasks waiting for peers' edits to this buffer.
1589                if let Some(buffer) = open_buffer.upgrade(cx) {
1590                    buffer.update(cx, |buffer, _| buffer.give_up_waiting());
1591                }
1592
1593                if let OpenBuffer::Strong(buffer) = open_buffer {
1594                    *open_buffer = OpenBuffer::Weak(buffer.downgrade());
1595                }
1596            }
1597
1598            // Wake up all futures currently waiting on a buffer to get opened,
1599            // to give them a chance to fail now that we've disconnected.
1600            *self.opened_buffer.0.borrow_mut() = ();
1601        }
1602    }
1603
1604    pub fn close(&mut self, cx: &mut ModelContext<Self>) {
1605        cx.emit(Event::Closed);
1606    }
1607
1608    pub fn is_read_only(&self) -> bool {
1609        match &self.client_state {
1610            Some(ProjectClientState::Remote {
1611                sharing_has_stopped,
1612                ..
1613            }) => *sharing_has_stopped,
1614            _ => false,
1615        }
1616    }
1617
1618    pub fn is_local(&self) -> bool {
1619        match &self.client_state {
1620            Some(ProjectClientState::Remote { .. }) => false,
1621            _ => true,
1622        }
1623    }
1624
1625    pub fn is_remote(&self) -> bool {
1626        !self.is_local()
1627    }
1628
1629    pub fn create_buffer(
1630        &mut self,
1631        text: &str,
1632        language: Option<Arc<Language>>,
1633        cx: &mut ModelContext<Self>,
1634    ) -> Result<ModelHandle<Buffer>> {
1635        if self.is_remote() {
1636            return Err(anyhow!("creating buffers as a guest is not supported yet"));
1637        }
1638        let id = post_inc(&mut self.next_buffer_id);
1639        let buffer = cx.add_model(|cx| {
1640            Buffer::new(self.replica_id(), id, text)
1641                .with_language(language.unwrap_or_else(|| language::PLAIN_TEXT.clone()), cx)
1642        });
1643        self.register_buffer(&buffer, cx)?;
1644        Ok(buffer)
1645    }
1646
1647    pub fn open_path(
1648        &mut self,
1649        path: impl Into<ProjectPath>,
1650        cx: &mut ModelContext<Self>,
1651    ) -> Task<Result<(ProjectEntryId, AnyModelHandle)>> {
1652        let task = self.open_buffer(path, cx);
1653        cx.spawn_weak(|_, cx| async move {
1654            let buffer = task.await?;
1655            let project_entry_id = buffer
1656                .read_with(&cx, |buffer, cx| {
1657                    File::from_dyn(buffer.file()).and_then(|file| file.project_entry_id(cx))
1658                })
1659                .ok_or_else(|| anyhow!("no project entry"))?;
1660
1661            let buffer: &AnyModelHandle = &buffer;
1662            Ok((project_entry_id, buffer.clone()))
1663        })
1664    }
1665
1666    pub fn open_local_buffer(
1667        &mut self,
1668        abs_path: impl AsRef<Path>,
1669        cx: &mut ModelContext<Self>,
1670    ) -> Task<Result<ModelHandle<Buffer>>> {
1671        if let Some((worktree, relative_path)) = self.find_local_worktree(abs_path.as_ref(), cx) {
1672            self.open_buffer((worktree.read(cx).id(), relative_path), cx)
1673        } else {
1674            Task::ready(Err(anyhow!("no such path")))
1675        }
1676    }
1677
1678    pub fn open_buffer(
1679        &mut self,
1680        path: impl Into<ProjectPath>,
1681        cx: &mut ModelContext<Self>,
1682    ) -> Task<Result<ModelHandle<Buffer>>> {
1683        let project_path = path.into();
1684        let worktree = if let Some(worktree) = self.worktree_for_id(project_path.worktree_id, cx) {
1685            worktree
1686        } else {
1687            return Task::ready(Err(anyhow!("no such worktree")));
1688        };
1689
1690        // If there is already a buffer for the given path, then return it.
1691        let existing_buffer = self.get_open_buffer(&project_path, cx);
1692        if let Some(existing_buffer) = existing_buffer {
1693            return Task::ready(Ok(existing_buffer));
1694        }
1695
1696        let loading_watch = match self.loading_buffers_by_path.entry(project_path.clone()) {
1697            // If the given path is already being loaded, then wait for that existing
1698            // task to complete and return the same buffer.
1699            hash_map::Entry::Occupied(e) => e.get().clone(),
1700
1701            // Otherwise, record the fact that this path is now being loaded.
1702            hash_map::Entry::Vacant(entry) => {
1703                let (mut tx, rx) = postage::watch::channel();
1704                entry.insert(rx.clone());
1705
1706                let load_buffer = if worktree.read(cx).is_local() {
1707                    self.open_local_buffer_internal(&project_path.path, &worktree, cx)
1708                } else {
1709                    self.open_remote_buffer_internal(&project_path.path, &worktree, cx)
1710                };
1711
1712                cx.spawn(move |this, mut cx| async move {
1713                    let load_result = load_buffer.await;
1714                    *tx.borrow_mut() = Some(this.update(&mut cx, |this, _| {
1715                        // Record the fact that the buffer is no longer loading.
1716                        this.loading_buffers_by_path.remove(&project_path);
1717                        let buffer = load_result.map_err(Arc::new)?;
1718                        Ok(buffer)
1719                    }));
1720                })
1721                .detach();
1722                rx
1723            }
1724        };
1725
1726        cx.foreground().spawn(async move {
1727            wait_for_loading_buffer(loading_watch)
1728                .await
1729                .map_err(|error| anyhow!("{}", error))
1730        })
1731    }
1732
1733    fn open_local_buffer_internal(
1734        &mut self,
1735        path: &Arc<Path>,
1736        worktree: &ModelHandle<Worktree>,
1737        cx: &mut ModelContext<Self>,
1738    ) -> Task<Result<ModelHandle<Buffer>>> {
1739        let buffer_id = post_inc(&mut self.next_buffer_id);
1740        let load_buffer = worktree.update(cx, |worktree, cx| {
1741            let worktree = worktree.as_local_mut().unwrap();
1742            worktree.load_buffer(buffer_id, path, cx)
1743        });
1744        cx.spawn(|this, mut cx| async move {
1745            let buffer = load_buffer.await?;
1746            this.update(&mut cx, |this, cx| this.register_buffer(&buffer, cx))?;
1747            Ok(buffer)
1748        })
1749    }
1750
1751    fn open_remote_buffer_internal(
1752        &mut self,
1753        path: &Arc<Path>,
1754        worktree: &ModelHandle<Worktree>,
1755        cx: &mut ModelContext<Self>,
1756    ) -> Task<Result<ModelHandle<Buffer>>> {
1757        let rpc = self.client.clone();
1758        let project_id = self.remote_id().unwrap();
1759        let remote_worktree_id = worktree.read(cx).id();
1760        let path = path.clone();
1761        let path_string = path.to_string_lossy().to_string();
1762        cx.spawn(|this, mut cx| async move {
1763            let response = rpc
1764                .request(proto::OpenBufferByPath {
1765                    project_id,
1766                    worktree_id: remote_worktree_id.to_proto(),
1767                    path: path_string,
1768                })
1769                .await?;
1770            this.update(&mut cx, |this, cx| {
1771                this.wait_for_remote_buffer(response.buffer_id, cx)
1772            })
1773            .await
1774        })
1775    }
1776
1777    /// LanguageServerName is owned, because it is inserted into a map
1778    pub fn open_local_buffer_via_lsp(
1779        &mut self,
1780        abs_path: lsp::Url,
1781        language_server_id: LanguageServerId,
1782        language_server_name: LanguageServerName,
1783        cx: &mut ModelContext<Self>,
1784    ) -> Task<Result<ModelHandle<Buffer>>> {
1785        cx.spawn(|this, mut cx| async move {
1786            let abs_path = abs_path
1787                .to_file_path()
1788                .map_err(|_| anyhow!("can't convert URI to path"))?;
1789            let (worktree, relative_path) = if let Some(result) =
1790                this.read_with(&cx, |this, cx| this.find_local_worktree(&abs_path, cx))
1791            {
1792                result
1793            } else {
1794                let worktree = this
1795                    .update(&mut cx, |this, cx| {
1796                        this.create_local_worktree(&abs_path, false, cx)
1797                    })
1798                    .await?;
1799                this.update(&mut cx, |this, cx| {
1800                    this.language_server_ids.insert(
1801                        (worktree.read(cx).id(), language_server_name),
1802                        language_server_id,
1803                    );
1804                });
1805                (worktree, PathBuf::new())
1806            };
1807
1808            let project_path = ProjectPath {
1809                worktree_id: worktree.read_with(&cx, |worktree, _| worktree.id()),
1810                path: relative_path.into(),
1811            };
1812            this.update(&mut cx, |this, cx| this.open_buffer(project_path, cx))
1813                .await
1814        })
1815    }
1816
1817    pub fn open_buffer_by_id(
1818        &mut self,
1819        id: u64,
1820        cx: &mut ModelContext<Self>,
1821    ) -> Task<Result<ModelHandle<Buffer>>> {
1822        if let Some(buffer) = self.buffer_for_id(id, cx) {
1823            Task::ready(Ok(buffer))
1824        } else if self.is_local() {
1825            Task::ready(Err(anyhow!("buffer {} does not exist", id)))
1826        } else if let Some(project_id) = self.remote_id() {
1827            let request = self
1828                .client
1829                .request(proto::OpenBufferById { project_id, id });
1830            cx.spawn(|this, mut cx| async move {
1831                let buffer_id = request.await?.buffer_id;
1832                this.update(&mut cx, |this, cx| {
1833                    this.wait_for_remote_buffer(buffer_id, cx)
1834                })
1835                .await
1836            })
1837        } else {
1838            Task::ready(Err(anyhow!("cannot open buffer while disconnected")))
1839        }
1840    }
1841
1842    pub fn save_buffers(
1843        &self,
1844        buffers: HashSet<ModelHandle<Buffer>>,
1845        cx: &mut ModelContext<Self>,
1846    ) -> Task<Result<()>> {
1847        cx.spawn(|this, mut cx| async move {
1848            let save_tasks = buffers
1849                .into_iter()
1850                .map(|buffer| this.update(&mut cx, |this, cx| this.save_buffer(buffer, cx)));
1851            try_join_all(save_tasks).await?;
1852            Ok(())
1853        })
1854    }
1855
1856    pub fn save_buffer(
1857        &self,
1858        buffer: ModelHandle<Buffer>,
1859        cx: &mut ModelContext<Self>,
1860    ) -> Task<Result<()>> {
1861        let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
1862            return Task::ready(Err(anyhow!("buffer doesn't have a file")));
1863        };
1864        let worktree = file.worktree.clone();
1865        let path = file.path.clone();
1866        worktree.update(cx, |worktree, cx| match worktree {
1867            Worktree::Local(worktree) => worktree.save_buffer(buffer, path, false, cx),
1868            Worktree::Remote(worktree) => worktree.save_buffer(buffer, cx),
1869        })
1870    }
1871
1872    pub fn save_buffer_as(
1873        &mut self,
1874        buffer: ModelHandle<Buffer>,
1875        abs_path: PathBuf,
1876        cx: &mut ModelContext<Self>,
1877    ) -> Task<Result<()>> {
1878        let worktree_task = self.find_or_create_local_worktree(&abs_path, true, cx);
1879        let old_file = File::from_dyn(buffer.read(cx).file())
1880            .filter(|f| f.is_local())
1881            .cloned();
1882        cx.spawn(|this, mut cx| async move {
1883            if let Some(old_file) = &old_file {
1884                this.update(&mut cx, |this, cx| {
1885                    this.unregister_buffer_from_language_servers(&buffer, old_file, cx);
1886                });
1887            }
1888            let (worktree, path) = worktree_task.await?;
1889            worktree
1890                .update(&mut cx, |worktree, cx| match worktree {
1891                    Worktree::Local(worktree) => {
1892                        worktree.save_buffer(buffer.clone(), path.into(), true, cx)
1893                    }
1894                    Worktree::Remote(_) => panic!("cannot remote buffers as new files"),
1895                })
1896                .await?;
1897
1898            this.update(&mut cx, |this, cx| {
1899                this.detect_language_for_buffer(&buffer, cx);
1900                this.register_buffer_with_language_servers(&buffer, cx);
1901            });
1902            Ok(())
1903        })
1904    }
1905
1906    pub fn get_open_buffer(
1907        &mut self,
1908        path: &ProjectPath,
1909        cx: &mut ModelContext<Self>,
1910    ) -> Option<ModelHandle<Buffer>> {
1911        let worktree = self.worktree_for_id(path.worktree_id, cx)?;
1912        self.opened_buffers.values().find_map(|buffer| {
1913            let buffer = buffer.upgrade(cx)?;
1914            let file = File::from_dyn(buffer.read(cx).file())?;
1915            if file.worktree == worktree && file.path() == &path.path {
1916                Some(buffer)
1917            } else {
1918                None
1919            }
1920        })
1921    }
1922
1923    fn register_buffer(
1924        &mut self,
1925        buffer: &ModelHandle<Buffer>,
1926        cx: &mut ModelContext<Self>,
1927    ) -> Result<()> {
1928        self.request_buffer_diff_recalculation(buffer, cx);
1929        buffer.update(cx, |buffer, _| {
1930            buffer.set_language_registry(self.languages.clone())
1931        });
1932
1933        let remote_id = buffer.read(cx).remote_id();
1934        let is_remote = self.is_remote();
1935        let open_buffer = if is_remote || self.is_shared() {
1936            OpenBuffer::Strong(buffer.clone())
1937        } else {
1938            OpenBuffer::Weak(buffer.downgrade())
1939        };
1940
1941        match self.opened_buffers.entry(remote_id) {
1942            hash_map::Entry::Vacant(entry) => {
1943                entry.insert(open_buffer);
1944            }
1945            hash_map::Entry::Occupied(mut entry) => {
1946                if let OpenBuffer::Operations(operations) = entry.get_mut() {
1947                    buffer.update(cx, |b, cx| b.apply_ops(operations.drain(..), cx))?;
1948                } else if entry.get().upgrade(cx).is_some() {
1949                    if is_remote {
1950                        return Ok(());
1951                    } else {
1952                        debug_panic!("buffer {} was already registered", remote_id);
1953                        Err(anyhow!("buffer {} was already registered", remote_id))?;
1954                    }
1955                }
1956                entry.insert(open_buffer);
1957            }
1958        }
1959        cx.subscribe(buffer, |this, buffer, event, cx| {
1960            this.on_buffer_event(buffer, event, cx);
1961        })
1962        .detach();
1963
1964        if let Some(file) = File::from_dyn(buffer.read(cx).file()) {
1965            if file.is_local {
1966                self.local_buffer_ids_by_path.insert(
1967                    ProjectPath {
1968                        worktree_id: file.worktree_id(cx),
1969                        path: file.path.clone(),
1970                    },
1971                    remote_id,
1972                );
1973
1974                self.local_buffer_ids_by_entry_id
1975                    .insert(file.entry_id, remote_id);
1976            }
1977        }
1978
1979        self.detect_language_for_buffer(buffer, cx);
1980        self.register_buffer_with_language_servers(buffer, cx);
1981        self.register_buffer_with_copilot(buffer, cx);
1982        cx.observe_release(buffer, |this, buffer, cx| {
1983            if let Some(file) = File::from_dyn(buffer.file()) {
1984                if file.is_local() {
1985                    let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
1986                    for server in this.language_servers_for_buffer(buffer, cx) {
1987                        server
1988                            .1
1989                            .notify::<lsp::notification::DidCloseTextDocument>(
1990                                lsp::DidCloseTextDocumentParams {
1991                                    text_document: lsp::TextDocumentIdentifier::new(uri.clone()),
1992                                },
1993                            )
1994                            .log_err();
1995                    }
1996                }
1997            }
1998        })
1999        .detach();
2000
2001        *self.opened_buffer.0.borrow_mut() = ();
2002        Ok(())
2003    }
2004
2005    fn register_buffer_with_language_servers(
2006        &mut self,
2007        buffer_handle: &ModelHandle<Buffer>,
2008        cx: &mut ModelContext<Self>,
2009    ) {
2010        let buffer = buffer_handle.read(cx);
2011        let buffer_id = buffer.remote_id();
2012
2013        if let Some(file) = File::from_dyn(buffer.file()) {
2014            if !file.is_local() {
2015                return;
2016            }
2017
2018            let abs_path = file.abs_path(cx);
2019            let uri = lsp::Url::from_file_path(&abs_path)
2020                .unwrap_or_else(|()| panic!("Failed to register file {abs_path:?}"));
2021            let initial_snapshot = buffer.text_snapshot();
2022            let language = buffer.language().cloned();
2023            let worktree_id = file.worktree_id(cx);
2024
2025            if let Some(local_worktree) = file.worktree.read(cx).as_local() {
2026                for (server_id, diagnostics) in local_worktree.diagnostics_for_path(file.path()) {
2027                    self.update_buffer_diagnostics(buffer_handle, server_id, None, diagnostics, cx)
2028                        .log_err();
2029                }
2030            }
2031
2032            if let Some(language) = language {
2033                for adapter in language.lsp_adapters() {
2034                    let language_id = adapter.language_ids.get(language.name().as_ref()).cloned();
2035                    let server = self
2036                        .language_server_ids
2037                        .get(&(worktree_id, adapter.name.clone()))
2038                        .and_then(|id| self.language_servers.get(id))
2039                        .and_then(|server_state| {
2040                            if let LanguageServerState::Running { server, .. } = server_state {
2041                                Some(server.clone())
2042                            } else {
2043                                None
2044                            }
2045                        });
2046                    let server = match server {
2047                        Some(server) => server,
2048                        None => continue,
2049                    };
2050
2051                    server
2052                        .notify::<lsp::notification::DidOpenTextDocument>(
2053                            lsp::DidOpenTextDocumentParams {
2054                                text_document: lsp::TextDocumentItem::new(
2055                                    uri.clone(),
2056                                    language_id.unwrap_or_default(),
2057                                    0,
2058                                    initial_snapshot.text(),
2059                                ),
2060                            },
2061                        )
2062                        .log_err();
2063
2064                    buffer_handle.update(cx, |buffer, cx| {
2065                        buffer.set_completion_triggers(
2066                            server
2067                                .capabilities()
2068                                .completion_provider
2069                                .as_ref()
2070                                .and_then(|provider| provider.trigger_characters.clone())
2071                                .unwrap_or_default(),
2072                            cx,
2073                        );
2074                    });
2075
2076                    let snapshot = LspBufferSnapshot {
2077                        version: 0,
2078                        snapshot: initial_snapshot.clone(),
2079                    };
2080                    self.buffer_snapshots
2081                        .entry(buffer_id)
2082                        .or_default()
2083                        .insert(server.server_id(), vec![snapshot]);
2084                }
2085            }
2086        }
2087    }
2088
2089    fn unregister_buffer_from_language_servers(
2090        &mut self,
2091        buffer: &ModelHandle<Buffer>,
2092        old_file: &File,
2093        cx: &mut ModelContext<Self>,
2094    ) {
2095        let old_path = match old_file.as_local() {
2096            Some(local) => local.abs_path(cx),
2097            None => return,
2098        };
2099
2100        buffer.update(cx, |buffer, cx| {
2101            let worktree_id = old_file.worktree_id(cx);
2102            let ids = &self.language_server_ids;
2103
2104            let language = buffer.language().cloned();
2105            let adapters = language.iter().flat_map(|language| language.lsp_adapters());
2106            for &server_id in adapters.flat_map(|a| ids.get(&(worktree_id, a.name.clone()))) {
2107                buffer.update_diagnostics(server_id, Default::default(), cx);
2108            }
2109
2110            self.buffer_snapshots.remove(&buffer.remote_id());
2111            let file_url = lsp::Url::from_file_path(old_path).unwrap();
2112            for (_, language_server) in self.language_servers_for_buffer(buffer, cx) {
2113                language_server
2114                    .notify::<lsp::notification::DidCloseTextDocument>(
2115                        lsp::DidCloseTextDocumentParams {
2116                            text_document: lsp::TextDocumentIdentifier::new(file_url.clone()),
2117                        },
2118                    )
2119                    .log_err();
2120            }
2121        });
2122    }
2123
2124    fn register_buffer_with_copilot(
2125        &self,
2126        buffer_handle: &ModelHandle<Buffer>,
2127        cx: &mut ModelContext<Self>,
2128    ) {
2129        if let Some(copilot) = Copilot::global(cx) {
2130            copilot.update(cx, |copilot, cx| copilot.register_buffer(buffer_handle, cx));
2131        }
2132    }
2133
2134    async fn send_buffer_ordered_messages(
2135        this: WeakModelHandle<Self>,
2136        rx: UnboundedReceiver<BufferOrderedMessage>,
2137        mut cx: AsyncAppContext,
2138    ) -> Option<()> {
2139        const MAX_BATCH_SIZE: usize = 128;
2140
2141        let mut operations_by_buffer_id = HashMap::default();
2142        async fn flush_operations(
2143            this: &ModelHandle<Project>,
2144            operations_by_buffer_id: &mut HashMap<u64, Vec<proto::Operation>>,
2145            needs_resync_with_host: &mut bool,
2146            is_local: bool,
2147            cx: &AsyncAppContext,
2148        ) {
2149            for (buffer_id, operations) in operations_by_buffer_id.drain() {
2150                let request = this.read_with(cx, |this, _| {
2151                    let project_id = this.remote_id()?;
2152                    Some(this.client.request(proto::UpdateBuffer {
2153                        buffer_id,
2154                        project_id,
2155                        operations,
2156                    }))
2157                });
2158                if let Some(request) = request {
2159                    if request.await.is_err() && !is_local {
2160                        *needs_resync_with_host = true;
2161                        break;
2162                    }
2163                }
2164            }
2165        }
2166
2167        let mut needs_resync_with_host = false;
2168        let mut changes = rx.ready_chunks(MAX_BATCH_SIZE);
2169
2170        while let Some(changes) = changes.next().await {
2171            let this = this.upgrade(&mut cx)?;
2172            let is_local = this.read_with(&cx, |this, _| this.is_local());
2173
2174            for change in changes {
2175                match change {
2176                    BufferOrderedMessage::Operation {
2177                        buffer_id,
2178                        operation,
2179                    } => {
2180                        if needs_resync_with_host {
2181                            continue;
2182                        }
2183
2184                        operations_by_buffer_id
2185                            .entry(buffer_id)
2186                            .or_insert(Vec::new())
2187                            .push(operation);
2188                    }
2189
2190                    BufferOrderedMessage::Resync => {
2191                        operations_by_buffer_id.clear();
2192                        if this
2193                            .update(&mut cx, |this, cx| this.synchronize_remote_buffers(cx))
2194                            .await
2195                            .is_ok()
2196                        {
2197                            needs_resync_with_host = false;
2198                        }
2199                    }
2200
2201                    BufferOrderedMessage::LanguageServerUpdate {
2202                        language_server_id,
2203                        message,
2204                    } => {
2205                        flush_operations(
2206                            &this,
2207                            &mut operations_by_buffer_id,
2208                            &mut needs_resync_with_host,
2209                            is_local,
2210                            &cx,
2211                        )
2212                        .await;
2213
2214                        this.read_with(&cx, |this, _| {
2215                            if let Some(project_id) = this.remote_id() {
2216                                this.client
2217                                    .send(proto::UpdateLanguageServer {
2218                                        project_id,
2219                                        language_server_id: language_server_id.0 as u64,
2220                                        variant: Some(message),
2221                                    })
2222                                    .log_err();
2223                            }
2224                        });
2225                    }
2226                }
2227            }
2228
2229            flush_operations(
2230                &this,
2231                &mut operations_by_buffer_id,
2232                &mut needs_resync_with_host,
2233                is_local,
2234                &cx,
2235            )
2236            .await;
2237        }
2238
2239        None
2240    }
2241
2242    fn on_buffer_event(
2243        &mut self,
2244        buffer: ModelHandle<Buffer>,
2245        event: &BufferEvent,
2246        cx: &mut ModelContext<Self>,
2247    ) -> Option<()> {
2248        if matches!(
2249            event,
2250            BufferEvent::Edited { .. } | BufferEvent::Reloaded | BufferEvent::DiffBaseChanged
2251        ) {
2252            self.request_buffer_diff_recalculation(&buffer, cx);
2253        }
2254
2255        match event {
2256            BufferEvent::Operation(operation) => {
2257                self.buffer_ordered_messages_tx
2258                    .unbounded_send(BufferOrderedMessage::Operation {
2259                        buffer_id: buffer.read(cx).remote_id(),
2260                        operation: language::proto::serialize_operation(operation),
2261                    })
2262                    .ok();
2263            }
2264
2265            BufferEvent::Edited { .. } => {
2266                let buffer = buffer.read(cx);
2267                let file = File::from_dyn(buffer.file())?;
2268                let abs_path = file.as_local()?.abs_path(cx);
2269                let uri = lsp::Url::from_file_path(abs_path).unwrap();
2270                let next_snapshot = buffer.text_snapshot();
2271
2272                let language_servers: Vec<_> = self
2273                    .language_servers_for_buffer(buffer, cx)
2274                    .map(|i| i.1.clone())
2275                    .collect();
2276
2277                for language_server in language_servers {
2278                    let language_server = language_server.clone();
2279
2280                    let buffer_snapshots = self
2281                        .buffer_snapshots
2282                        .get_mut(&buffer.remote_id())
2283                        .and_then(|m| m.get_mut(&language_server.server_id()))?;
2284                    let previous_snapshot = buffer_snapshots.last()?;
2285
2286                    let build_incremental_change = || {
2287                        buffer
2288                            .edits_since::<(PointUtf16, usize)>(
2289                                previous_snapshot.snapshot.version(),
2290                            )
2291                            .map(|edit| {
2292                                let edit_start = edit.new.start.0;
2293                                let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
2294                                let new_text = next_snapshot
2295                                    .text_for_range(edit.new.start.1..edit.new.end.1)
2296                                    .collect();
2297                                lsp::TextDocumentContentChangeEvent {
2298                                    range: Some(lsp::Range::new(
2299                                        point_to_lsp(edit_start),
2300                                        point_to_lsp(edit_end),
2301                                    )),
2302                                    range_length: None,
2303                                    text: new_text,
2304                                }
2305                            })
2306                            .collect()
2307                    };
2308
2309                    let document_sync_kind = language_server
2310                        .capabilities()
2311                        .text_document_sync
2312                        .as_ref()
2313                        .and_then(|sync| match sync {
2314                            lsp::TextDocumentSyncCapability::Kind(kind) => Some(*kind),
2315                            lsp::TextDocumentSyncCapability::Options(options) => options.change,
2316                        });
2317
2318                    let content_changes: Vec<_> = match document_sync_kind {
2319                        Some(lsp::TextDocumentSyncKind::FULL) => {
2320                            vec![lsp::TextDocumentContentChangeEvent {
2321                                range: None,
2322                                range_length: None,
2323                                text: next_snapshot.text(),
2324                            }]
2325                        }
2326                        Some(lsp::TextDocumentSyncKind::INCREMENTAL) => build_incremental_change(),
2327                        _ => {
2328                            #[cfg(any(test, feature = "test-support"))]
2329                            {
2330                                build_incremental_change()
2331                            }
2332
2333                            #[cfg(not(any(test, feature = "test-support")))]
2334                            {
2335                                continue;
2336                            }
2337                        }
2338                    };
2339
2340                    let next_version = previous_snapshot.version + 1;
2341
2342                    buffer_snapshots.push(LspBufferSnapshot {
2343                        version: next_version,
2344                        snapshot: next_snapshot.clone(),
2345                    });
2346
2347                    language_server
2348                        .notify::<lsp::notification::DidChangeTextDocument>(
2349                            lsp::DidChangeTextDocumentParams {
2350                                text_document: lsp::VersionedTextDocumentIdentifier::new(
2351                                    uri.clone(),
2352                                    next_version,
2353                                ),
2354                                content_changes,
2355                            },
2356                        )
2357                        .log_err();
2358                }
2359            }
2360
2361            BufferEvent::Saved => {
2362                let file = File::from_dyn(buffer.read(cx).file())?;
2363                let worktree_id = file.worktree_id(cx);
2364                let abs_path = file.as_local()?.abs_path(cx);
2365                let text_document = lsp::TextDocumentIdentifier {
2366                    uri: lsp::Url::from_file_path(abs_path).unwrap(),
2367                };
2368
2369                for (_, _, server) in self.language_servers_for_worktree(worktree_id) {
2370                    let text = include_text(server.as_ref()).then(|| buffer.read(cx).text());
2371
2372                    server
2373                        .notify::<lsp::notification::DidSaveTextDocument>(
2374                            lsp::DidSaveTextDocumentParams {
2375                                text_document: text_document.clone(),
2376                                text,
2377                            },
2378                        )
2379                        .log_err();
2380                }
2381
2382                let language_server_ids = self.language_server_ids_for_buffer(buffer.read(cx), cx);
2383                for language_server_id in language_server_ids {
2384                    if let Some(LanguageServerState::Running {
2385                        adapter,
2386                        simulate_disk_based_diagnostics_completion,
2387                        ..
2388                    }) = self.language_servers.get_mut(&language_server_id)
2389                    {
2390                        // After saving a buffer using a language server that doesn't provide
2391                        // a disk-based progress token, kick off a timer that will reset every
2392                        // time the buffer is saved. If the timer eventually fires, simulate
2393                        // disk-based diagnostics being finished so that other pieces of UI
2394                        // (e.g., project diagnostics view, diagnostic status bar) can update.
2395                        // We don't emit an event right away because the language server might take
2396                        // some time to publish diagnostics.
2397                        if adapter.disk_based_diagnostics_progress_token.is_none() {
2398                            const DISK_BASED_DIAGNOSTICS_DEBOUNCE: Duration =
2399                                Duration::from_secs(1);
2400
2401                            let task = cx.spawn_weak(|this, mut cx| async move {
2402                                cx.background().timer(DISK_BASED_DIAGNOSTICS_DEBOUNCE).await;
2403                                if let Some(this) = this.upgrade(&cx) {
2404                                    this.update(&mut cx, |this, cx| {
2405                                        this.disk_based_diagnostics_finished(
2406                                            language_server_id,
2407                                            cx,
2408                                        );
2409                                        this.buffer_ordered_messages_tx
2410                                            .unbounded_send(
2411                                                BufferOrderedMessage::LanguageServerUpdate {
2412                                                    language_server_id,
2413                                                    message:proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(Default::default())
2414                                                },
2415                                            )
2416                                            .ok();
2417                                    });
2418                                }
2419                            });
2420                            *simulate_disk_based_diagnostics_completion = Some(task);
2421                        }
2422                    }
2423                }
2424            }
2425            BufferEvent::FileHandleChanged => {
2426                let Some(file) = File::from_dyn(buffer.read(cx).file()) else {
2427                    return None;
2428                };
2429
2430                match self.local_buffer_ids_by_entry_id.get(&file.entry_id) {
2431                    Some(_) => {
2432                        return None;
2433                    }
2434                    None => {
2435                        let remote_id = buffer.read(cx).remote_id();
2436                        self.local_buffer_ids_by_entry_id
2437                            .insert(file.entry_id, remote_id);
2438
2439                        self.local_buffer_ids_by_path.insert(
2440                            ProjectPath {
2441                                worktree_id: file.worktree_id(cx),
2442                                path: file.path.clone(),
2443                            },
2444                            remote_id,
2445                        );
2446                    }
2447                }
2448            }
2449            _ => {}
2450        }
2451
2452        None
2453    }
2454
2455    fn request_buffer_diff_recalculation(
2456        &mut self,
2457        buffer: &ModelHandle<Buffer>,
2458        cx: &mut ModelContext<Self>,
2459    ) {
2460        self.buffers_needing_diff.insert(buffer.downgrade());
2461        let first_insertion = self.buffers_needing_diff.len() == 1;
2462
2463        let settings = settings::get::<ProjectSettings>(cx);
2464        let delay = if let Some(delay) = settings.git.gutter_debounce {
2465            delay
2466        } else {
2467            if first_insertion {
2468                let this = cx.weak_handle();
2469                cx.defer(move |cx| {
2470                    if let Some(this) = this.upgrade(cx) {
2471                        this.update(cx, |this, cx| {
2472                            this.recalculate_buffer_diffs(cx).detach();
2473                        });
2474                    }
2475                });
2476            }
2477            return;
2478        };
2479
2480        const MIN_DELAY: u64 = 50;
2481        let delay = delay.max(MIN_DELAY);
2482        let duration = Duration::from_millis(delay);
2483
2484        self.git_diff_debouncer
2485            .fire_new(duration, cx, move |this, cx| {
2486                this.recalculate_buffer_diffs(cx)
2487            });
2488    }
2489
2490    fn recalculate_buffer_diffs(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
2491        cx.spawn(|this, mut cx| async move {
2492            let buffers: Vec<_> = this.update(&mut cx, |this, _| {
2493                this.buffers_needing_diff.drain().collect()
2494            });
2495
2496            let tasks: Vec<_> = this.update(&mut cx, |_, cx| {
2497                buffers
2498                    .iter()
2499                    .filter_map(|buffer| {
2500                        let buffer = buffer.upgrade(cx)?;
2501                        buffer.update(cx, |buffer, cx| buffer.git_diff_recalc(cx))
2502                    })
2503                    .collect()
2504            });
2505
2506            futures::future::join_all(tasks).await;
2507
2508            this.update(&mut cx, |this, cx| {
2509                if !this.buffers_needing_diff.is_empty() {
2510                    this.recalculate_buffer_diffs(cx).detach();
2511                } else {
2512                    // TODO: Would a `ModelContext<Project>.notify()` suffice here?
2513                    for buffer in buffers {
2514                        if let Some(buffer) = buffer.upgrade(cx) {
2515                            buffer.update(cx, |_, cx| cx.notify());
2516                        }
2517                    }
2518                }
2519            });
2520        })
2521    }
2522
2523    fn language_servers_for_worktree(
2524        &self,
2525        worktree_id: WorktreeId,
2526    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<Language>, &Arc<LanguageServer>)> {
2527        self.language_server_ids
2528            .iter()
2529            .filter_map(move |((language_server_worktree_id, _), id)| {
2530                if *language_server_worktree_id == worktree_id {
2531                    if let Some(LanguageServerState::Running {
2532                        adapter,
2533                        language,
2534                        server,
2535                        ..
2536                    }) = self.language_servers.get(id)
2537                    {
2538                        return Some((adapter, language, server));
2539                    }
2540                }
2541                None
2542            })
2543    }
2544
2545    fn maintain_buffer_languages(
2546        languages: Arc<LanguageRegistry>,
2547        cx: &mut ModelContext<Project>,
2548    ) -> Task<()> {
2549        let mut subscription = languages.subscribe();
2550        let mut prev_reload_count = languages.reload_count();
2551        cx.spawn_weak(|project, mut cx| async move {
2552            while let Some(()) = subscription.next().await {
2553                if let Some(project) = project.upgrade(&cx) {
2554                    // If the language registry has been reloaded, then remove and
2555                    // re-assign the languages on all open buffers.
2556                    let reload_count = languages.reload_count();
2557                    if reload_count > prev_reload_count {
2558                        prev_reload_count = reload_count;
2559                        project.update(&mut cx, |this, cx| {
2560                            let buffers = this
2561                                .opened_buffers
2562                                .values()
2563                                .filter_map(|b| b.upgrade(cx))
2564                                .collect::<Vec<_>>();
2565                            for buffer in buffers {
2566                                if let Some(f) = File::from_dyn(buffer.read(cx).file()).cloned() {
2567                                    this.unregister_buffer_from_language_servers(&buffer, &f, cx);
2568                                    buffer.update(cx, |buffer, cx| buffer.set_language(None, cx));
2569                                }
2570                            }
2571                        });
2572                    }
2573
2574                    project.update(&mut cx, |project, cx| {
2575                        let mut plain_text_buffers = Vec::new();
2576                        let mut buffers_with_unknown_injections = Vec::new();
2577                        for buffer in project.opened_buffers.values() {
2578                            if let Some(handle) = buffer.upgrade(cx) {
2579                                let buffer = &handle.read(cx);
2580                                if buffer.language().is_none()
2581                                    || buffer.language() == Some(&*language::PLAIN_TEXT)
2582                                {
2583                                    plain_text_buffers.push(handle);
2584                                } else if buffer.contains_unknown_injections() {
2585                                    buffers_with_unknown_injections.push(handle);
2586                                }
2587                            }
2588                        }
2589
2590                        for buffer in plain_text_buffers {
2591                            project.detect_language_for_buffer(&buffer, cx);
2592                            project.register_buffer_with_language_servers(&buffer, cx);
2593                        }
2594
2595                        for buffer in buffers_with_unknown_injections {
2596                            buffer.update(cx, |buffer, cx| buffer.reparse(cx));
2597                        }
2598                    });
2599                }
2600            }
2601        })
2602    }
2603
2604    fn maintain_workspace_config(cx: &mut ModelContext<Project>) -> Task<()> {
2605        let (mut settings_changed_tx, mut settings_changed_rx) = watch::channel();
2606        let _ = postage::stream::Stream::try_recv(&mut settings_changed_rx);
2607
2608        let settings_observation = cx.observe_global::<SettingsStore, _>(move |_, _| {
2609            *settings_changed_tx.borrow_mut() = ();
2610        });
2611
2612        cx.spawn_weak(|this, mut cx| async move {
2613            while let Some(_) = settings_changed_rx.next().await {
2614                let Some(this) = this.upgrade(&cx) else {
2615                    break;
2616                };
2617
2618                let servers: Vec<_> = this.read_with(&cx, |this, _| {
2619                    this.language_servers
2620                        .values()
2621                        .filter_map(|state| match state {
2622                            LanguageServerState::Starting(_) => None,
2623                            LanguageServerState::Running {
2624                                adapter, server, ..
2625                            } => Some((adapter.clone(), server.clone())),
2626                        })
2627                        .collect()
2628                });
2629
2630                for (adapter, server) in servers {
2631                    let workspace_config =
2632                        cx.update(|cx| adapter.workspace_configuration(cx)).await;
2633                    server
2634                        .notify::<lsp::notification::DidChangeConfiguration>(
2635                            lsp::DidChangeConfigurationParams {
2636                                settings: workspace_config.clone(),
2637                            },
2638                        )
2639                        .ok();
2640                }
2641            }
2642
2643            drop(settings_observation);
2644        })
2645    }
2646
2647    fn detect_language_for_buffer(
2648        &mut self,
2649        buffer_handle: &ModelHandle<Buffer>,
2650        cx: &mut ModelContext<Self>,
2651    ) -> Option<()> {
2652        // If the buffer has a language, set it and start the language server if we haven't already.
2653        let buffer = buffer_handle.read(cx);
2654        let full_path = buffer.file()?.full_path(cx);
2655        let content = buffer.as_rope();
2656        let new_language = self
2657            .languages
2658            .language_for_file(&full_path, Some(content))
2659            .now_or_never()?
2660            .ok()?;
2661        self.set_language_for_buffer(buffer_handle, new_language, cx);
2662        None
2663    }
2664
2665    pub fn set_language_for_buffer(
2666        &mut self,
2667        buffer: &ModelHandle<Buffer>,
2668        new_language: Arc<Language>,
2669        cx: &mut ModelContext<Self>,
2670    ) {
2671        buffer.update(cx, |buffer, cx| {
2672            if buffer.language().map_or(true, |old_language| {
2673                !Arc::ptr_eq(old_language, &new_language)
2674            }) {
2675                buffer.set_language(Some(new_language.clone()), cx);
2676            }
2677        });
2678
2679        let buffer_file = buffer.read(cx).file().cloned();
2680        let settings = language_settings(Some(&new_language), buffer_file.as_ref(), cx).clone();
2681        let buffer_file = File::from_dyn(buffer_file.as_ref());
2682        let worktree = buffer_file.as_ref().map(|f| f.worktree_id(cx));
2683
2684        self.install_default_formatters(worktree, &new_language, &settings, cx)
2685            .detach_and_log_err(cx);
2686        if let Some(file) = buffer_file {
2687            let worktree = file.worktree.clone();
2688            if let Some(tree) = worktree.read(cx).as_local() {
2689                self.start_language_servers(&worktree, tree.abs_path().clone(), new_language, cx);
2690            }
2691        }
2692    }
2693
2694    fn start_language_servers(
2695        &mut self,
2696        worktree: &ModelHandle<Worktree>,
2697        worktree_path: Arc<Path>,
2698        language: Arc<Language>,
2699        cx: &mut ModelContext<Self>,
2700    ) {
2701        let root_file = worktree.update(cx, |tree, cx| tree.root_file(cx));
2702        let settings = language_settings(Some(&language), root_file.map(|f| f as _).as_ref(), cx);
2703        if !settings.enable_language_server {
2704            return;
2705        }
2706
2707        let worktree_id = worktree.read(cx).id();
2708        for adapter in language.lsp_adapters() {
2709            self.start_language_server(
2710                worktree_id,
2711                worktree_path.clone(),
2712                adapter.clone(),
2713                language.clone(),
2714                cx,
2715            );
2716        }
2717    }
2718
2719    fn start_language_server(
2720        &mut self,
2721        worktree_id: WorktreeId,
2722        worktree_path: Arc<Path>,
2723        adapter: Arc<CachedLspAdapter>,
2724        language: Arc<Language>,
2725        cx: &mut ModelContext<Self>,
2726    ) {
2727        if adapter.reinstall_attempt_count.load(SeqCst) > MAX_SERVER_REINSTALL_ATTEMPT_COUNT {
2728            return;
2729        }
2730
2731        let key = (worktree_id, adapter.name.clone());
2732        if self.language_server_ids.contains_key(&key) {
2733            return;
2734        }
2735
2736        let stderr_capture = Arc::new(Mutex::new(Some(String::new())));
2737        let pending_server = match self.languages.create_pending_language_server(
2738            stderr_capture.clone(),
2739            language.clone(),
2740            adapter.clone(),
2741            worktree_path,
2742            ProjectLspAdapterDelegate::new(self, cx),
2743            cx,
2744        ) {
2745            Some(pending_server) => pending_server,
2746            None => return,
2747        };
2748
2749        let project_settings = settings::get::<ProjectSettings>(cx);
2750        let lsp = project_settings.lsp.get(&adapter.name.0);
2751        let override_options = lsp.map(|s| s.initialization_options.clone()).flatten();
2752
2753        let server_id = pending_server.server_id;
2754        let container_dir = pending_server.container_dir.clone();
2755        let state = LanguageServerState::Starting({
2756            let adapter = adapter.clone();
2757            let server_name = adapter.name.0.clone();
2758            let language = language.clone();
2759            let key = key.clone();
2760
2761            cx.spawn_weak(|this, mut cx| async move {
2762                let result = Self::setup_and_insert_language_server(
2763                    this,
2764                    override_options,
2765                    pending_server,
2766                    adapter.clone(),
2767                    language.clone(),
2768                    server_id,
2769                    key,
2770                    &mut cx,
2771                )
2772                .await;
2773
2774                match result {
2775                    Ok(server) => {
2776                        stderr_capture.lock().take();
2777                        Some(server)
2778                    }
2779
2780                    Err(err) => {
2781                        log::error!("failed to start language server {server_name:?}: {err}");
2782                        log::error!("server stderr: {:?}", stderr_capture.lock().take());
2783
2784                        let this = this.upgrade(&cx)?;
2785                        let container_dir = container_dir?;
2786
2787                        let attempt_count = adapter.reinstall_attempt_count.fetch_add(1, SeqCst);
2788                        if attempt_count >= MAX_SERVER_REINSTALL_ATTEMPT_COUNT {
2789                            let max = MAX_SERVER_REINSTALL_ATTEMPT_COUNT;
2790                            log::error!(
2791                                "Hit {max} max reinstallation attempts for {server_name:?}"
2792                            );
2793                            return None;
2794                        }
2795
2796                        let installation_test_binary = adapter
2797                            .installation_test_binary(container_dir.to_path_buf())
2798                            .await;
2799
2800                        this.update(&mut cx, |_, cx| {
2801                            Self::check_errored_server(
2802                                language,
2803                                adapter,
2804                                server_id,
2805                                installation_test_binary,
2806                                cx,
2807                            )
2808                        });
2809
2810                        None
2811                    }
2812                }
2813            })
2814        });
2815
2816        self.language_servers.insert(server_id, state);
2817        self.language_server_ids.insert(key, server_id);
2818    }
2819
2820    fn reinstall_language_server(
2821        &mut self,
2822        language: Arc<Language>,
2823        adapter: Arc<CachedLspAdapter>,
2824        server_id: LanguageServerId,
2825        cx: &mut ModelContext<Self>,
2826    ) -> Option<Task<()>> {
2827        log::info!("beginning to reinstall server");
2828
2829        let existing_server = match self.language_servers.remove(&server_id) {
2830            Some(LanguageServerState::Running { server, .. }) => Some(server),
2831            _ => None,
2832        };
2833
2834        for worktree in &self.worktrees {
2835            if let Some(worktree) = worktree.upgrade(cx) {
2836                let key = (worktree.read(cx).id(), adapter.name.clone());
2837                self.language_server_ids.remove(&key);
2838            }
2839        }
2840
2841        Some(cx.spawn(move |this, mut cx| async move {
2842            if let Some(task) = existing_server.and_then(|server| server.shutdown()) {
2843                log::info!("shutting down existing server");
2844                task.await;
2845            }
2846
2847            // TODO: This is race-safe with regards to preventing new instances from
2848            // starting while deleting, but existing instances in other projects are going
2849            // to be very confused and messed up
2850            this.update(&mut cx, |this, cx| {
2851                this.languages.delete_server_container(adapter.clone(), cx)
2852            })
2853            .await;
2854
2855            this.update(&mut cx, |this, mut cx| {
2856                let worktrees = this.worktrees.clone();
2857                for worktree in worktrees {
2858                    let worktree = match worktree.upgrade(cx) {
2859                        Some(worktree) => worktree.read(cx),
2860                        None => continue,
2861                    };
2862                    let worktree_id = worktree.id();
2863                    let root_path = worktree.abs_path();
2864
2865                    this.start_language_server(
2866                        worktree_id,
2867                        root_path,
2868                        adapter.clone(),
2869                        language.clone(),
2870                        &mut cx,
2871                    );
2872                }
2873            })
2874        }))
2875    }
2876
2877    async fn setup_and_insert_language_server(
2878        this: WeakModelHandle<Self>,
2879        override_initialization_options: Option<serde_json::Value>,
2880        pending_server: PendingLanguageServer,
2881        adapter: Arc<CachedLspAdapter>,
2882        language: Arc<Language>,
2883        server_id: LanguageServerId,
2884        key: (WorktreeId, LanguageServerName),
2885        cx: &mut AsyncAppContext,
2886    ) -> Result<Arc<LanguageServer>> {
2887        let language_server = Self::setup_pending_language_server(
2888            this,
2889            override_initialization_options,
2890            pending_server,
2891            adapter.clone(),
2892            server_id,
2893            cx,
2894        )
2895        .await?;
2896
2897        let this = match this.upgrade(cx) {
2898            Some(this) => this,
2899            None => return Err(anyhow!("failed to upgrade project handle")),
2900        };
2901
2902        this.update(cx, |this, cx| {
2903            this.insert_newly_running_language_server(
2904                language,
2905                adapter,
2906                language_server.clone(),
2907                server_id,
2908                key,
2909                cx,
2910            )
2911        })?;
2912
2913        Ok(language_server)
2914    }
2915
2916    async fn setup_pending_language_server(
2917        this: WeakModelHandle<Self>,
2918        override_options: Option<serde_json::Value>,
2919        pending_server: PendingLanguageServer,
2920        adapter: Arc<CachedLspAdapter>,
2921        server_id: LanguageServerId,
2922        cx: &mut AsyncAppContext,
2923    ) -> Result<Arc<LanguageServer>> {
2924        let workspace_config = cx.update(|cx| adapter.workspace_configuration(cx)).await;
2925        let language_server = pending_server.task.await?;
2926
2927        language_server
2928            .on_notification::<lsp::notification::PublishDiagnostics, _>({
2929                let adapter = adapter.clone();
2930                move |mut params, mut cx| {
2931                    let this = this;
2932                    let adapter = adapter.clone();
2933                    if let Some(this) = this.upgrade(&cx) {
2934                        adapter.process_diagnostics(&mut params);
2935                        this.update(&mut cx, |this, cx| {
2936                            this.update_diagnostics(
2937                                server_id,
2938                                params,
2939                                &adapter.disk_based_diagnostic_sources,
2940                                cx,
2941                            )
2942                            .log_err();
2943                        });
2944                    }
2945                }
2946            })
2947            .detach();
2948
2949        language_server
2950            .on_request::<lsp::request::WorkspaceConfiguration, _, _>({
2951                let adapter = adapter.clone();
2952                move |params, mut cx| {
2953                    let adapter = adapter.clone();
2954                    async move {
2955                        let workspace_config =
2956                            cx.update(|cx| adapter.workspace_configuration(cx)).await;
2957                        Ok(params
2958                            .items
2959                            .into_iter()
2960                            .map(|item| {
2961                                if let Some(section) = &item.section {
2962                                    workspace_config
2963                                        .get(section)
2964                                        .cloned()
2965                                        .unwrap_or(serde_json::Value::Null)
2966                                } else {
2967                                    workspace_config.clone()
2968                                }
2969                            })
2970                            .collect())
2971                    }
2972                }
2973            })
2974            .detach();
2975
2976        // Even though we don't have handling for these requests, respond to them to
2977        // avoid stalling any language server like `gopls` which waits for a response
2978        // to these requests when initializing.
2979        language_server
2980            .on_request::<lsp::request::WorkDoneProgressCreate, _, _>(
2981                move |params, mut cx| async move {
2982                    if let Some(this) = this.upgrade(&cx) {
2983                        this.update(&mut cx, |this, _| {
2984                            if let Some(status) = this.language_server_statuses.get_mut(&server_id)
2985                            {
2986                                if let lsp::NumberOrString::String(token) = params.token {
2987                                    status.progress_tokens.insert(token);
2988                                }
2989                            }
2990                        });
2991                    }
2992                    Ok(())
2993                },
2994            )
2995            .detach();
2996
2997        language_server
2998            .on_request::<lsp::request::RegisterCapability, _, _>({
2999                move |params, mut cx| async move {
3000                    let this = this
3001                        .upgrade(&cx)
3002                        .ok_or_else(|| anyhow!("project dropped"))?;
3003                    for reg in params.registrations {
3004                        if reg.method == "workspace/didChangeWatchedFiles" {
3005                            if let Some(options) = reg.register_options {
3006                                let options = serde_json::from_value(options)?;
3007                                this.update(&mut cx, |this, cx| {
3008                                    this.on_lsp_did_change_watched_files(server_id, options, cx);
3009                                });
3010                            }
3011                        }
3012                    }
3013                    Ok(())
3014                }
3015            })
3016            .detach();
3017
3018        language_server
3019            .on_request::<lsp::request::ApplyWorkspaceEdit, _, _>({
3020                let adapter = adapter.clone();
3021                move |params, cx| {
3022                    Self::on_lsp_workspace_edit(this, params, server_id, adapter.clone(), cx)
3023                }
3024            })
3025            .detach();
3026
3027        language_server
3028            .on_request::<lsp::request::InlayHintRefreshRequest, _, _>({
3029                move |(), mut cx| async move {
3030                    let this = this
3031                        .upgrade(&cx)
3032                        .ok_or_else(|| anyhow!("project dropped"))?;
3033                    this.update(&mut cx, |project, cx| {
3034                        cx.emit(Event::RefreshInlayHints);
3035                        project.remote_id().map(|project_id| {
3036                            project.client.send(proto::RefreshInlayHints { project_id })
3037                        })
3038                    })
3039                    .transpose()?;
3040                    Ok(())
3041                }
3042            })
3043            .detach();
3044
3045        let disk_based_diagnostics_progress_token =
3046            adapter.disk_based_diagnostics_progress_token.clone();
3047
3048        language_server
3049            .on_notification::<lsp::notification::Progress, _>(move |params, mut cx| {
3050                if let Some(this) = this.upgrade(&cx) {
3051                    this.update(&mut cx, |this, cx| {
3052                        this.on_lsp_progress(
3053                            params,
3054                            server_id,
3055                            disk_based_diagnostics_progress_token.clone(),
3056                            cx,
3057                        );
3058                    });
3059                }
3060            })
3061            .detach();
3062
3063        let mut initialization_options = adapter.adapter.initialization_options().await;
3064        match (&mut initialization_options, override_options) {
3065            (Some(initialization_options), Some(override_options)) => {
3066                merge_json_value_into(override_options, initialization_options);
3067            }
3068            (None, override_options) => initialization_options = override_options,
3069            _ => {}
3070        }
3071
3072        let language_server = language_server.initialize(initialization_options).await?;
3073
3074        language_server
3075            .notify::<lsp::notification::DidChangeConfiguration>(
3076                lsp::DidChangeConfigurationParams {
3077                    settings: workspace_config,
3078                },
3079            )
3080            .ok();
3081
3082        Ok(language_server)
3083    }
3084
3085    fn insert_newly_running_language_server(
3086        &mut self,
3087        language: Arc<Language>,
3088        adapter: Arc<CachedLspAdapter>,
3089        language_server: Arc<LanguageServer>,
3090        server_id: LanguageServerId,
3091        key: (WorktreeId, LanguageServerName),
3092        cx: &mut ModelContext<Self>,
3093    ) -> Result<()> {
3094        // If the language server for this key doesn't match the server id, don't store the
3095        // server. Which will cause it to be dropped, killing the process
3096        if self
3097            .language_server_ids
3098            .get(&key)
3099            .map(|id| id != &server_id)
3100            .unwrap_or(false)
3101        {
3102            return Ok(());
3103        }
3104
3105        // Update language_servers collection with Running variant of LanguageServerState
3106        // indicating that the server is up and running and ready
3107        self.language_servers.insert(
3108            server_id,
3109            LanguageServerState::Running {
3110                adapter: adapter.clone(),
3111                language: language.clone(),
3112                watched_paths: Default::default(),
3113                server: language_server.clone(),
3114                simulate_disk_based_diagnostics_completion: None,
3115            },
3116        );
3117
3118        self.language_server_statuses.insert(
3119            server_id,
3120            LanguageServerStatus {
3121                name: language_server.name().to_string(),
3122                pending_work: Default::default(),
3123                has_pending_diagnostic_updates: false,
3124                progress_tokens: Default::default(),
3125            },
3126        );
3127
3128        cx.emit(Event::LanguageServerAdded(server_id));
3129
3130        if let Some(project_id) = self.remote_id() {
3131            self.client.send(proto::StartLanguageServer {
3132                project_id,
3133                server: Some(proto::LanguageServer {
3134                    id: server_id.0 as u64,
3135                    name: language_server.name().to_string(),
3136                }),
3137            })?;
3138        }
3139
3140        // Tell the language server about every open buffer in the worktree that matches the language.
3141        for buffer in self.opened_buffers.values() {
3142            if let Some(buffer_handle) = buffer.upgrade(cx) {
3143                let buffer = buffer_handle.read(cx);
3144                let file = match File::from_dyn(buffer.file()) {
3145                    Some(file) => file,
3146                    None => continue,
3147                };
3148                let language = match buffer.language() {
3149                    Some(language) => language,
3150                    None => continue,
3151                };
3152
3153                if file.worktree.read(cx).id() != key.0
3154                    || !language.lsp_adapters().iter().any(|a| a.name == key.1)
3155                {
3156                    continue;
3157                }
3158
3159                let file = match file.as_local() {
3160                    Some(file) => file,
3161                    None => continue,
3162                };
3163
3164                let versions = self
3165                    .buffer_snapshots
3166                    .entry(buffer.remote_id())
3167                    .or_default()
3168                    .entry(server_id)
3169                    .or_insert_with(|| {
3170                        vec![LspBufferSnapshot {
3171                            version: 0,
3172                            snapshot: buffer.text_snapshot(),
3173                        }]
3174                    });
3175
3176                let snapshot = versions.last().unwrap();
3177                let version = snapshot.version;
3178                let initial_snapshot = &snapshot.snapshot;
3179                let uri = lsp::Url::from_file_path(file.abs_path(cx)).unwrap();
3180                language_server.notify::<lsp::notification::DidOpenTextDocument>(
3181                    lsp::DidOpenTextDocumentParams {
3182                        text_document: lsp::TextDocumentItem::new(
3183                            uri,
3184                            adapter
3185                                .language_ids
3186                                .get(language.name().as_ref())
3187                                .cloned()
3188                                .unwrap_or_default(),
3189                            version,
3190                            initial_snapshot.text(),
3191                        ),
3192                    },
3193                )?;
3194
3195                buffer_handle.update(cx, |buffer, cx| {
3196                    buffer.set_completion_triggers(
3197                        language_server
3198                            .capabilities()
3199                            .completion_provider
3200                            .as_ref()
3201                            .and_then(|provider| provider.trigger_characters.clone())
3202                            .unwrap_or_default(),
3203                        cx,
3204                    )
3205                });
3206            }
3207        }
3208
3209        cx.notify();
3210        Ok(())
3211    }
3212
3213    // Returns a list of all of the worktrees which no longer have a language server and the root path
3214    // for the stopped server
3215    fn stop_language_server(
3216        &mut self,
3217        worktree_id: WorktreeId,
3218        adapter_name: LanguageServerName,
3219        cx: &mut ModelContext<Self>,
3220    ) -> Task<(Option<PathBuf>, Vec<WorktreeId>)> {
3221        let key = (worktree_id, adapter_name);
3222        if let Some(server_id) = self.language_server_ids.remove(&key) {
3223            log::info!("stopping language server {}", key.1 .0);
3224
3225            // Remove other entries for this language server as well
3226            let mut orphaned_worktrees = vec![worktree_id];
3227            let other_keys = self.language_server_ids.keys().cloned().collect::<Vec<_>>();
3228            for other_key in other_keys {
3229                if self.language_server_ids.get(&other_key) == Some(&server_id) {
3230                    self.language_server_ids.remove(&other_key);
3231                    orphaned_worktrees.push(other_key.0);
3232                }
3233            }
3234
3235            for buffer in self.opened_buffers.values() {
3236                if let Some(buffer) = buffer.upgrade(cx) {
3237                    buffer.update(cx, |buffer, cx| {
3238                        buffer.update_diagnostics(server_id, Default::default(), cx);
3239                    });
3240                }
3241            }
3242            for worktree in &self.worktrees {
3243                if let Some(worktree) = worktree.upgrade(cx) {
3244                    worktree.update(cx, |worktree, cx| {
3245                        if let Some(worktree) = worktree.as_local_mut() {
3246                            worktree.clear_diagnostics_for_language_server(server_id, cx);
3247                        }
3248                    });
3249                }
3250            }
3251
3252            self.language_server_statuses.remove(&server_id);
3253            cx.notify();
3254
3255            let server_state = self.language_servers.remove(&server_id);
3256            cx.emit(Event::LanguageServerRemoved(server_id));
3257            cx.spawn_weak(|this, mut cx| async move {
3258                let mut root_path = None;
3259
3260                let server = match server_state {
3261                    Some(LanguageServerState::Starting(task)) => task.await,
3262                    Some(LanguageServerState::Running { server, .. }) => Some(server),
3263                    None => None,
3264                };
3265
3266                if let Some(server) = server {
3267                    root_path = Some(server.root_path().clone());
3268                    if let Some(shutdown) = server.shutdown() {
3269                        shutdown.await;
3270                    }
3271                }
3272
3273                if let Some(this) = this.upgrade(&cx) {
3274                    this.update(&mut cx, |this, cx| {
3275                        this.language_server_statuses.remove(&server_id);
3276                        cx.notify();
3277                    });
3278                }
3279
3280                (root_path, orphaned_worktrees)
3281            })
3282        } else {
3283            Task::ready((None, Vec::new()))
3284        }
3285    }
3286
3287    pub fn restart_language_servers_for_buffers(
3288        &mut self,
3289        buffers: impl IntoIterator<Item = ModelHandle<Buffer>>,
3290        cx: &mut ModelContext<Self>,
3291    ) -> Option<()> {
3292        let language_server_lookup_info: HashSet<(ModelHandle<Worktree>, Arc<Language>)> = buffers
3293            .into_iter()
3294            .filter_map(|buffer| {
3295                let buffer = buffer.read(cx);
3296                let file = File::from_dyn(buffer.file())?;
3297                let full_path = file.full_path(cx);
3298                let language = self
3299                    .languages
3300                    .language_for_file(&full_path, Some(buffer.as_rope()))
3301                    .now_or_never()?
3302                    .ok()?;
3303                Some((file.worktree.clone(), language))
3304            })
3305            .collect();
3306        for (worktree, language) in language_server_lookup_info {
3307            self.restart_language_servers(worktree, language, cx);
3308        }
3309
3310        None
3311    }
3312
3313    // TODO This will break in the case where the adapter's root paths and worktrees are not equal
3314    fn restart_language_servers(
3315        &mut self,
3316        worktree: ModelHandle<Worktree>,
3317        language: Arc<Language>,
3318        cx: &mut ModelContext<Self>,
3319    ) {
3320        let worktree_id = worktree.read(cx).id();
3321        let fallback_path = worktree.read(cx).abs_path();
3322
3323        let mut stops = Vec::new();
3324        for adapter in language.lsp_adapters() {
3325            stops.push(self.stop_language_server(worktree_id, adapter.name.clone(), cx));
3326        }
3327
3328        if stops.is_empty() {
3329            return;
3330        }
3331        let mut stops = stops.into_iter();
3332
3333        cx.spawn_weak(|this, mut cx| async move {
3334            let (original_root_path, mut orphaned_worktrees) = stops.next().unwrap().await;
3335            for stop in stops {
3336                let (_, worktrees) = stop.await;
3337                orphaned_worktrees.extend_from_slice(&worktrees);
3338            }
3339
3340            let this = match this.upgrade(&cx) {
3341                Some(this) => this,
3342                None => return,
3343            };
3344
3345            this.update(&mut cx, |this, cx| {
3346                // Attempt to restart using original server path. Fallback to passed in
3347                // path if we could not retrieve the root path
3348                let root_path = original_root_path
3349                    .map(|path_buf| Arc::from(path_buf.as_path()))
3350                    .unwrap_or(fallback_path);
3351
3352                this.start_language_servers(&worktree, root_path, language.clone(), cx);
3353
3354                // Lookup new server ids and set them for each of the orphaned worktrees
3355                for adapter in language.lsp_adapters() {
3356                    if let Some(new_server_id) = this
3357                        .language_server_ids
3358                        .get(&(worktree_id, adapter.name.clone()))
3359                        .cloned()
3360                    {
3361                        for &orphaned_worktree in &orphaned_worktrees {
3362                            this.language_server_ids
3363                                .insert((orphaned_worktree, adapter.name.clone()), new_server_id);
3364                        }
3365                    }
3366                }
3367            });
3368        })
3369        .detach();
3370    }
3371
3372    fn check_errored_server(
3373        language: Arc<Language>,
3374        adapter: Arc<CachedLspAdapter>,
3375        server_id: LanguageServerId,
3376        installation_test_binary: Option<LanguageServerBinary>,
3377        cx: &mut ModelContext<Self>,
3378    ) {
3379        if !adapter.can_be_reinstalled() {
3380            log::info!(
3381                "Validation check requested for {:?} but it cannot be reinstalled",
3382                adapter.name.0
3383            );
3384            return;
3385        }
3386
3387        cx.spawn(|this, mut cx| async move {
3388            log::info!("About to spawn test binary");
3389
3390            // A lack of test binary counts as a failure
3391            let process = installation_test_binary.and_then(|binary| {
3392                smol::process::Command::new(&binary.path)
3393                    .current_dir(&binary.path)
3394                    .args(binary.arguments)
3395                    .stdin(Stdio::piped())
3396                    .stdout(Stdio::piped())
3397                    .stderr(Stdio::inherit())
3398                    .kill_on_drop(true)
3399                    .spawn()
3400                    .ok()
3401            });
3402
3403            const PROCESS_TIMEOUT: Duration = Duration::from_secs(5);
3404            let mut timeout = cx.background().timer(PROCESS_TIMEOUT).fuse();
3405
3406            let mut errored = false;
3407            if let Some(mut process) = process {
3408                futures::select! {
3409                    status = process.status().fuse() => match status {
3410                        Ok(status) => errored = !status.success(),
3411                        Err(_) => errored = true,
3412                    },
3413
3414                    _ = timeout => {
3415                        log::info!("test binary time-ed out, this counts as a success");
3416                        _ = process.kill();
3417                    }
3418                }
3419            } else {
3420                log::warn!("test binary failed to launch");
3421                errored = true;
3422            }
3423
3424            if errored {
3425                log::warn!("test binary check failed");
3426                let task = this.update(&mut cx, move |this, mut cx| {
3427                    this.reinstall_language_server(language, adapter, server_id, &mut cx)
3428                });
3429
3430                if let Some(task) = task {
3431                    task.await;
3432                }
3433            }
3434        })
3435        .detach();
3436    }
3437
3438    fn on_lsp_progress(
3439        &mut self,
3440        progress: lsp::ProgressParams,
3441        language_server_id: LanguageServerId,
3442        disk_based_diagnostics_progress_token: Option<String>,
3443        cx: &mut ModelContext<Self>,
3444    ) {
3445        let token = match progress.token {
3446            lsp::NumberOrString::String(token) => token,
3447            lsp::NumberOrString::Number(token) => {
3448                log::info!("skipping numeric progress token {}", token);
3449                return;
3450            }
3451        };
3452        let lsp::ProgressParamsValue::WorkDone(progress) = progress.value;
3453        let language_server_status =
3454            if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3455                status
3456            } else {
3457                return;
3458            };
3459
3460        if !language_server_status.progress_tokens.contains(&token) {
3461            return;
3462        }
3463
3464        let is_disk_based_diagnostics_progress = disk_based_diagnostics_progress_token
3465            .as_ref()
3466            .map_or(false, |disk_based_token| {
3467                token.starts_with(disk_based_token)
3468            });
3469
3470        match progress {
3471            lsp::WorkDoneProgress::Begin(report) => {
3472                if is_disk_based_diagnostics_progress {
3473                    language_server_status.has_pending_diagnostic_updates = true;
3474                    self.disk_based_diagnostics_started(language_server_id, cx);
3475                    self.buffer_ordered_messages_tx
3476                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3477                            language_server_id,
3478                            message: proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(Default::default())
3479                        })
3480                        .ok();
3481                } else {
3482                    self.on_lsp_work_start(
3483                        language_server_id,
3484                        token.clone(),
3485                        LanguageServerProgress {
3486                            message: report.message.clone(),
3487                            percentage: report.percentage.map(|p| p as usize),
3488                            last_update_at: Instant::now(),
3489                        },
3490                        cx,
3491                    );
3492                    self.buffer_ordered_messages_tx
3493                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3494                            language_server_id,
3495                            message: proto::update_language_server::Variant::WorkStart(
3496                                proto::LspWorkStart {
3497                                    token,
3498                                    message: report.message,
3499                                    percentage: report.percentage.map(|p| p as u32),
3500                                },
3501                            ),
3502                        })
3503                        .ok();
3504                }
3505            }
3506            lsp::WorkDoneProgress::Report(report) => {
3507                if !is_disk_based_diagnostics_progress {
3508                    self.on_lsp_work_progress(
3509                        language_server_id,
3510                        token.clone(),
3511                        LanguageServerProgress {
3512                            message: report.message.clone(),
3513                            percentage: report.percentage.map(|p| p as usize),
3514                            last_update_at: Instant::now(),
3515                        },
3516                        cx,
3517                    );
3518                    self.buffer_ordered_messages_tx
3519                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3520                            language_server_id,
3521                            message: proto::update_language_server::Variant::WorkProgress(
3522                                proto::LspWorkProgress {
3523                                    token,
3524                                    message: report.message,
3525                                    percentage: report.percentage.map(|p| p as u32),
3526                                },
3527                            ),
3528                        })
3529                        .ok();
3530                }
3531            }
3532            lsp::WorkDoneProgress::End(_) => {
3533                language_server_status.progress_tokens.remove(&token);
3534
3535                if is_disk_based_diagnostics_progress {
3536                    language_server_status.has_pending_diagnostic_updates = false;
3537                    self.disk_based_diagnostics_finished(language_server_id, cx);
3538                    self.buffer_ordered_messages_tx
3539                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3540                            language_server_id,
3541                            message:
3542                                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(
3543                                    Default::default(),
3544                                ),
3545                        })
3546                        .ok();
3547                } else {
3548                    self.on_lsp_work_end(language_server_id, token.clone(), cx);
3549                    self.buffer_ordered_messages_tx
3550                        .unbounded_send(BufferOrderedMessage::LanguageServerUpdate {
3551                            language_server_id,
3552                            message: proto::update_language_server::Variant::WorkEnd(
3553                                proto::LspWorkEnd { token },
3554                            ),
3555                        })
3556                        .ok();
3557                }
3558            }
3559        }
3560    }
3561
3562    fn on_lsp_work_start(
3563        &mut self,
3564        language_server_id: LanguageServerId,
3565        token: String,
3566        progress: LanguageServerProgress,
3567        cx: &mut ModelContext<Self>,
3568    ) {
3569        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3570            status.pending_work.insert(token, progress);
3571            cx.notify();
3572        }
3573    }
3574
3575    fn on_lsp_work_progress(
3576        &mut self,
3577        language_server_id: LanguageServerId,
3578        token: String,
3579        progress: LanguageServerProgress,
3580        cx: &mut ModelContext<Self>,
3581    ) {
3582        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3583            let entry = status
3584                .pending_work
3585                .entry(token)
3586                .or_insert(LanguageServerProgress {
3587                    message: Default::default(),
3588                    percentage: Default::default(),
3589                    last_update_at: progress.last_update_at,
3590                });
3591            if progress.message.is_some() {
3592                entry.message = progress.message;
3593            }
3594            if progress.percentage.is_some() {
3595                entry.percentage = progress.percentage;
3596            }
3597            entry.last_update_at = progress.last_update_at;
3598            cx.notify();
3599        }
3600    }
3601
3602    fn on_lsp_work_end(
3603        &mut self,
3604        language_server_id: LanguageServerId,
3605        token: String,
3606        cx: &mut ModelContext<Self>,
3607    ) {
3608        if let Some(status) = self.language_server_statuses.get_mut(&language_server_id) {
3609            cx.emit(Event::RefreshInlayHints);
3610            status.pending_work.remove(&token);
3611            cx.notify();
3612        }
3613    }
3614
3615    fn on_lsp_did_change_watched_files(
3616        &mut self,
3617        language_server_id: LanguageServerId,
3618        params: DidChangeWatchedFilesRegistrationOptions,
3619        cx: &mut ModelContext<Self>,
3620    ) {
3621        if let Some(LanguageServerState::Running { watched_paths, .. }) =
3622            self.language_servers.get_mut(&language_server_id)
3623        {
3624            let mut builders = HashMap::default();
3625            for watcher in params.watchers {
3626                for worktree in &self.worktrees {
3627                    if let Some(worktree) = worktree.upgrade(cx) {
3628                        let glob_is_inside_worktree = worktree.update(cx, |tree, _| {
3629                            if let Some(abs_path) = tree.abs_path().to_str() {
3630                                let relative_glob_pattern = match &watcher.glob_pattern {
3631                                    lsp::GlobPattern::String(s) => s
3632                                        .strip_prefix(abs_path)
3633                                        .and_then(|s| s.strip_prefix(std::path::MAIN_SEPARATOR)),
3634                                    lsp::GlobPattern::Relative(rp) => {
3635                                        let base_uri = match &rp.base_uri {
3636                                            lsp::OneOf::Left(workspace_folder) => {
3637                                                &workspace_folder.uri
3638                                            }
3639                                            lsp::OneOf::Right(base_uri) => base_uri,
3640                                        };
3641                                        base_uri.to_file_path().ok().and_then(|file_path| {
3642                                            (file_path.to_str() == Some(abs_path))
3643                                                .then_some(rp.pattern.as_str())
3644                                        })
3645                                    }
3646                                };
3647                                if let Some(relative_glob_pattern) = relative_glob_pattern {
3648                                    let literal_prefix =
3649                                        glob_literal_prefix(&relative_glob_pattern);
3650                                    tree.as_local_mut()
3651                                        .unwrap()
3652                                        .add_path_prefix_to_scan(Path::new(literal_prefix).into());
3653                                    if let Some(glob) = Glob::new(relative_glob_pattern).log_err() {
3654                                        builders
3655                                            .entry(tree.id())
3656                                            .or_insert_with(|| GlobSetBuilder::new())
3657                                            .add(glob);
3658                                    }
3659                                    return true;
3660                                }
3661                            }
3662                            false
3663                        });
3664                        if glob_is_inside_worktree {
3665                            break;
3666                        }
3667                    }
3668                }
3669            }
3670
3671            watched_paths.clear();
3672            for (worktree_id, builder) in builders {
3673                if let Ok(globset) = builder.build() {
3674                    watched_paths.insert(worktree_id, globset);
3675                }
3676            }
3677
3678            cx.notify();
3679        }
3680    }
3681
3682    async fn on_lsp_workspace_edit(
3683        this: WeakModelHandle<Self>,
3684        params: lsp::ApplyWorkspaceEditParams,
3685        server_id: LanguageServerId,
3686        adapter: Arc<CachedLspAdapter>,
3687        mut cx: AsyncAppContext,
3688    ) -> Result<lsp::ApplyWorkspaceEditResponse> {
3689        let this = this
3690            .upgrade(&cx)
3691            .ok_or_else(|| anyhow!("project project closed"))?;
3692        let language_server = this
3693            .read_with(&cx, |this, _| this.language_server_for_id(server_id))
3694            .ok_or_else(|| anyhow!("language server not found"))?;
3695        let transaction = Self::deserialize_workspace_edit(
3696            this.clone(),
3697            params.edit,
3698            true,
3699            adapter.clone(),
3700            language_server.clone(),
3701            &mut cx,
3702        )
3703        .await
3704        .log_err();
3705        this.update(&mut cx, |this, _| {
3706            if let Some(transaction) = transaction {
3707                this.last_workspace_edits_by_language_server
3708                    .insert(server_id, transaction);
3709            }
3710        });
3711        Ok(lsp::ApplyWorkspaceEditResponse {
3712            applied: true,
3713            failed_change: None,
3714            failure_reason: None,
3715        })
3716    }
3717
3718    pub fn language_server_statuses(
3719        &self,
3720    ) -> impl DoubleEndedIterator<Item = &LanguageServerStatus> {
3721        self.language_server_statuses.values()
3722    }
3723
3724    pub fn update_diagnostics(
3725        &mut self,
3726        language_server_id: LanguageServerId,
3727        mut params: lsp::PublishDiagnosticsParams,
3728        disk_based_sources: &[String],
3729        cx: &mut ModelContext<Self>,
3730    ) -> Result<()> {
3731        let abs_path = params
3732            .uri
3733            .to_file_path()
3734            .map_err(|_| anyhow!("URI is not a file"))?;
3735        let mut diagnostics = Vec::default();
3736        let mut primary_diagnostic_group_ids = HashMap::default();
3737        let mut sources_by_group_id = HashMap::default();
3738        let mut supporting_diagnostics = HashMap::default();
3739
3740        // Ensure that primary diagnostics are always the most severe
3741        params.diagnostics.sort_by_key(|item| item.severity);
3742
3743        for diagnostic in &params.diagnostics {
3744            let source = diagnostic.source.as_ref();
3745            let code = diagnostic.code.as_ref().map(|code| match code {
3746                lsp::NumberOrString::Number(code) => code.to_string(),
3747                lsp::NumberOrString::String(code) => code.clone(),
3748            });
3749            let range = range_from_lsp(diagnostic.range);
3750            let is_supporting = diagnostic
3751                .related_information
3752                .as_ref()
3753                .map_or(false, |infos| {
3754                    infos.iter().any(|info| {
3755                        primary_diagnostic_group_ids.contains_key(&(
3756                            source,
3757                            code.clone(),
3758                            range_from_lsp(info.location.range),
3759                        ))
3760                    })
3761                });
3762
3763            let is_unnecessary = diagnostic.tags.as_ref().map_or(false, |tags| {
3764                tags.iter().any(|tag| *tag == DiagnosticTag::UNNECESSARY)
3765            });
3766
3767            if is_supporting {
3768                supporting_diagnostics.insert(
3769                    (source, code.clone(), range),
3770                    (diagnostic.severity, is_unnecessary),
3771                );
3772            } else {
3773                let group_id = post_inc(&mut self.next_diagnostic_group_id);
3774                let is_disk_based =
3775                    source.map_or(false, |source| disk_based_sources.contains(source));
3776
3777                sources_by_group_id.insert(group_id, source);
3778                primary_diagnostic_group_ids
3779                    .insert((source, code.clone(), range.clone()), group_id);
3780
3781                diagnostics.push(DiagnosticEntry {
3782                    range,
3783                    diagnostic: Diagnostic {
3784                        source: diagnostic.source.clone(),
3785                        code: code.clone(),
3786                        severity: diagnostic.severity.unwrap_or(DiagnosticSeverity::ERROR),
3787                        message: diagnostic.message.clone(),
3788                        group_id,
3789                        is_primary: true,
3790                        is_valid: true,
3791                        is_disk_based,
3792                        is_unnecessary,
3793                    },
3794                });
3795                if let Some(infos) = &diagnostic.related_information {
3796                    for info in infos {
3797                        if info.location.uri == params.uri && !info.message.is_empty() {
3798                            let range = range_from_lsp(info.location.range);
3799                            diagnostics.push(DiagnosticEntry {
3800                                range,
3801                                diagnostic: Diagnostic {
3802                                    source: diagnostic.source.clone(),
3803                                    code: code.clone(),
3804                                    severity: DiagnosticSeverity::INFORMATION,
3805                                    message: info.message.clone(),
3806                                    group_id,
3807                                    is_primary: false,
3808                                    is_valid: true,
3809                                    is_disk_based,
3810                                    is_unnecessary: false,
3811                                },
3812                            });
3813                        }
3814                    }
3815                }
3816            }
3817        }
3818
3819        for entry in &mut diagnostics {
3820            let diagnostic = &mut entry.diagnostic;
3821            if !diagnostic.is_primary {
3822                let source = *sources_by_group_id.get(&diagnostic.group_id).unwrap();
3823                if let Some(&(severity, is_unnecessary)) = supporting_diagnostics.get(&(
3824                    source,
3825                    diagnostic.code.clone(),
3826                    entry.range.clone(),
3827                )) {
3828                    if let Some(severity) = severity {
3829                        diagnostic.severity = severity;
3830                    }
3831                    diagnostic.is_unnecessary = is_unnecessary;
3832                }
3833            }
3834        }
3835
3836        self.update_diagnostic_entries(
3837            language_server_id,
3838            abs_path,
3839            params.version,
3840            diagnostics,
3841            cx,
3842        )?;
3843        Ok(())
3844    }
3845
3846    pub fn update_diagnostic_entries(
3847        &mut self,
3848        server_id: LanguageServerId,
3849        abs_path: PathBuf,
3850        version: Option<i32>,
3851        diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
3852        cx: &mut ModelContext<Project>,
3853    ) -> Result<(), anyhow::Error> {
3854        let (worktree, relative_path) = self
3855            .find_local_worktree(&abs_path, cx)
3856            .ok_or_else(|| anyhow!("no worktree found for diagnostics path {abs_path:?}"))?;
3857
3858        let project_path = ProjectPath {
3859            worktree_id: worktree.read(cx).id(),
3860            path: relative_path.into(),
3861        };
3862
3863        if let Some(buffer) = self.get_open_buffer(&project_path, cx) {
3864            self.update_buffer_diagnostics(&buffer, server_id, version, diagnostics.clone(), cx)?;
3865        }
3866
3867        let updated = worktree.update(cx, |worktree, cx| {
3868            worktree
3869                .as_local_mut()
3870                .ok_or_else(|| anyhow!("not a local worktree"))?
3871                .update_diagnostics(server_id, project_path.path.clone(), diagnostics, cx)
3872        })?;
3873        if updated {
3874            cx.emit(Event::DiagnosticsUpdated {
3875                language_server_id: server_id,
3876                path: project_path,
3877            });
3878        }
3879        Ok(())
3880    }
3881
3882    fn update_buffer_diagnostics(
3883        &mut self,
3884        buffer: &ModelHandle<Buffer>,
3885        server_id: LanguageServerId,
3886        version: Option<i32>,
3887        mut diagnostics: Vec<DiagnosticEntry<Unclipped<PointUtf16>>>,
3888        cx: &mut ModelContext<Self>,
3889    ) -> Result<()> {
3890        fn compare_diagnostics(a: &Diagnostic, b: &Diagnostic) -> Ordering {
3891            Ordering::Equal
3892                .then_with(|| b.is_primary.cmp(&a.is_primary))
3893                .then_with(|| a.is_disk_based.cmp(&b.is_disk_based))
3894                .then_with(|| a.severity.cmp(&b.severity))
3895                .then_with(|| a.message.cmp(&b.message))
3896        }
3897
3898        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx)?;
3899
3900        diagnostics.sort_unstable_by(|a, b| {
3901            Ordering::Equal
3902                .then_with(|| a.range.start.cmp(&b.range.start))
3903                .then_with(|| b.range.end.cmp(&a.range.end))
3904                .then_with(|| compare_diagnostics(&a.diagnostic, &b.diagnostic))
3905        });
3906
3907        let mut sanitized_diagnostics = Vec::new();
3908        let edits_since_save = Patch::new(
3909            snapshot
3910                .edits_since::<Unclipped<PointUtf16>>(buffer.read(cx).saved_version())
3911                .collect(),
3912        );
3913        for entry in diagnostics {
3914            let start;
3915            let end;
3916            if entry.diagnostic.is_disk_based {
3917                // Some diagnostics are based on files on disk instead of buffers'
3918                // current contents. Adjust these diagnostics' ranges to reflect
3919                // any unsaved edits.
3920                start = edits_since_save.old_to_new(entry.range.start);
3921                end = edits_since_save.old_to_new(entry.range.end);
3922            } else {
3923                start = entry.range.start;
3924                end = entry.range.end;
3925            }
3926
3927            let mut range = snapshot.clip_point_utf16(start, Bias::Left)
3928                ..snapshot.clip_point_utf16(end, Bias::Right);
3929
3930            // Expand empty ranges by one codepoint
3931            if range.start == range.end {
3932                // This will be go to the next boundary when being clipped
3933                range.end.column += 1;
3934                range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Right);
3935                if range.start == range.end && range.end.column > 0 {
3936                    range.start.column -= 1;
3937                    range.end = snapshot.clip_point_utf16(Unclipped(range.end), Bias::Left);
3938                }
3939            }
3940
3941            sanitized_diagnostics.push(DiagnosticEntry {
3942                range,
3943                diagnostic: entry.diagnostic,
3944            });
3945        }
3946        drop(edits_since_save);
3947
3948        let set = DiagnosticSet::new(sanitized_diagnostics, &snapshot);
3949        buffer.update(cx, |buffer, cx| {
3950            buffer.update_diagnostics(server_id, set, cx)
3951        });
3952        Ok(())
3953    }
3954
3955    pub fn reload_buffers(
3956        &self,
3957        buffers: HashSet<ModelHandle<Buffer>>,
3958        push_to_history: bool,
3959        cx: &mut ModelContext<Self>,
3960    ) -> Task<Result<ProjectTransaction>> {
3961        let mut local_buffers = Vec::new();
3962        let mut remote_buffers = None;
3963        for buffer_handle in buffers {
3964            let buffer = buffer_handle.read(cx);
3965            if buffer.is_dirty() {
3966                if let Some(file) = File::from_dyn(buffer.file()) {
3967                    if file.is_local() {
3968                        local_buffers.push(buffer_handle);
3969                    } else {
3970                        remote_buffers.get_or_insert(Vec::new()).push(buffer_handle);
3971                    }
3972                }
3973            }
3974        }
3975
3976        let remote_buffers = self.remote_id().zip(remote_buffers);
3977        let client = self.client.clone();
3978
3979        cx.spawn(|this, mut cx| async move {
3980            let mut project_transaction = ProjectTransaction::default();
3981
3982            if let Some((project_id, remote_buffers)) = remote_buffers {
3983                let response = client
3984                    .request(proto::ReloadBuffers {
3985                        project_id,
3986                        buffer_ids: remote_buffers
3987                            .iter()
3988                            .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
3989                            .collect(),
3990                    })
3991                    .await?
3992                    .transaction
3993                    .ok_or_else(|| anyhow!("missing transaction"))?;
3994                project_transaction = this
3995                    .update(&mut cx, |this, cx| {
3996                        this.deserialize_project_transaction(response, push_to_history, cx)
3997                    })
3998                    .await?;
3999            }
4000
4001            for buffer in local_buffers {
4002                let transaction = buffer
4003                    .update(&mut cx, |buffer, cx| buffer.reload(cx))
4004                    .await?;
4005                buffer.update(&mut cx, |buffer, cx| {
4006                    if let Some(transaction) = transaction {
4007                        if !push_to_history {
4008                            buffer.forget_transaction(transaction.id);
4009                        }
4010                        project_transaction.0.insert(cx.handle(), transaction);
4011                    }
4012                });
4013            }
4014
4015            Ok(project_transaction)
4016        })
4017    }
4018
4019    pub fn format(
4020        &mut self,
4021        buffers: HashSet<ModelHandle<Buffer>>,
4022        push_to_history: bool,
4023        trigger: FormatTrigger,
4024        cx: &mut ModelContext<Project>,
4025    ) -> Task<anyhow::Result<ProjectTransaction>> {
4026        if self.is_local() {
4027            let mut buffers_with_paths_and_servers = buffers
4028                .into_iter()
4029                .filter_map(|buffer_handle| {
4030                    let buffer = buffer_handle.read(cx);
4031                    let file = File::from_dyn(buffer.file())?;
4032                    let buffer_abs_path = file.as_local().map(|f| f.abs_path(cx));
4033                    let server = self
4034                        .primary_language_server_for_buffer(buffer, cx)
4035                        .map(|s| s.1.clone());
4036                    Some((buffer_handle, buffer_abs_path, server))
4037                })
4038                .collect::<Vec<_>>();
4039
4040            cx.spawn(|project, mut cx| async move {
4041                // Do not allow multiple concurrent formatting requests for the
4042                // same buffer.
4043                project.update(&mut cx, |this, cx| {
4044                    buffers_with_paths_and_servers.retain(|(buffer, _, _)| {
4045                        this.buffers_being_formatted
4046                            .insert(buffer.read(cx).remote_id())
4047                    });
4048                });
4049
4050                let _cleanup = defer({
4051                    let this = project.clone();
4052                    let mut cx = cx.clone();
4053                    let buffers = &buffers_with_paths_and_servers;
4054                    move || {
4055                        this.update(&mut cx, |this, cx| {
4056                            for (buffer, _, _) in buffers {
4057                                this.buffers_being_formatted
4058                                    .remove(&buffer.read(cx).remote_id());
4059                            }
4060                        });
4061                    }
4062                });
4063
4064                let mut project_transaction = ProjectTransaction::default();
4065                for (buffer, buffer_abs_path, language_server) in &buffers_with_paths_and_servers {
4066                    let settings = buffer.read_with(&cx, |buffer, cx| {
4067                        language_settings(buffer.language(), buffer.file(), cx).clone()
4068                    });
4069
4070                    let remove_trailing_whitespace = settings.remove_trailing_whitespace_on_save;
4071                    let ensure_final_newline = settings.ensure_final_newline_on_save;
4072                    let format_on_save = settings.format_on_save.clone();
4073                    let formatter = settings.formatter.clone();
4074                    let tab_size = settings.tab_size;
4075
4076                    // First, format buffer's whitespace according to the settings.
4077                    let trailing_whitespace_diff = if remove_trailing_whitespace {
4078                        Some(
4079                            buffer
4080                                .read_with(&cx, |b, cx| b.remove_trailing_whitespace(cx))
4081                                .await,
4082                        )
4083                    } else {
4084                        None
4085                    };
4086                    let whitespace_transaction_id = buffer.update(&mut cx, |buffer, cx| {
4087                        buffer.finalize_last_transaction();
4088                        buffer.start_transaction();
4089                        if let Some(diff) = trailing_whitespace_diff {
4090                            buffer.apply_diff(diff, cx);
4091                        }
4092                        if ensure_final_newline {
4093                            buffer.ensure_final_newline(cx);
4094                        }
4095                        buffer.end_transaction(cx)
4096                    });
4097
4098                    // Currently, formatting operations are represented differently depending on
4099                    // whether they come from a language server or an external command.
4100                    enum FormatOperation {
4101                        Lsp(Vec<(Range<Anchor>, String)>),
4102                        External(Diff),
4103                        Prettier(Diff),
4104                    }
4105
4106                    // Apply language-specific formatting using either a language server
4107                    // or external command.
4108                    let mut format_operation = None;
4109                    match (formatter, format_on_save) {
4110                        (_, FormatOnSave::Off) if trigger == FormatTrigger::Save => {}
4111
4112                        (Formatter::LanguageServer, FormatOnSave::On | FormatOnSave::Off)
4113                        | (_, FormatOnSave::LanguageServer) => {
4114                            if let Some((language_server, buffer_abs_path)) =
4115                                language_server.as_ref().zip(buffer_abs_path.as_ref())
4116                            {
4117                                format_operation = Some(FormatOperation::Lsp(
4118                                    Self::format_via_lsp(
4119                                        &project,
4120                                        &buffer,
4121                                        buffer_abs_path,
4122                                        &language_server,
4123                                        tab_size,
4124                                        &mut cx,
4125                                    )
4126                                    .await
4127                                    .context("failed to format via language server")?,
4128                                ));
4129                            }
4130                        }
4131
4132                        (
4133                            Formatter::External { command, arguments },
4134                            FormatOnSave::On | FormatOnSave::Off,
4135                        )
4136                        | (_, FormatOnSave::External { command, arguments }) => {
4137                            if let Some(buffer_abs_path) = buffer_abs_path {
4138                                format_operation = Self::format_via_external_command(
4139                                    buffer,
4140                                    buffer_abs_path,
4141                                    &command,
4142                                    &arguments,
4143                                    &mut cx,
4144                                )
4145                                .await
4146                                .context(format!(
4147                                    "failed to format via external command {:?}",
4148                                    command
4149                                ))?
4150                                .map(FormatOperation::External);
4151                            }
4152                        }
4153                        (Formatter::Auto, FormatOnSave::On | FormatOnSave::Off) => {
4154                            if let Some((prettier_path, prettier_task)) = project
4155                                .update(&mut cx, |project, cx| {
4156                                    project.prettier_instance_for_buffer(buffer, cx)
4157                                }).await {
4158                                    match prettier_task.await
4159                                    {
4160                                        Ok(prettier) => {
4161                                            let buffer_path = buffer.update(&mut cx, |buffer, cx| File::from_dyn(buffer.file()).map(|f| f.abs_path(cx)));
4162                                            format_operation = Some(FormatOperation::Prettier(
4163                                                prettier
4164                                                    .format(buffer, buffer_path, &cx)
4165                                                    .await
4166                                                    .context("formatting via prettier")?,
4167                                            ));
4168                                        }
4169                                        Err(e) => {
4170                                            project.update(&mut cx, |project, _| {
4171                                                match &prettier_path {
4172                                                    Some(prettier_path) => {
4173                                                        project.prettier_instances.remove(prettier_path);
4174                                                    },
4175                                                    None => {
4176                                                        if let Some(default_prettier) = project.default_prettier.as_mut() {
4177                                                            default_prettier.instance = None;
4178                                                        }
4179                                                    },
4180                                                }
4181                                            });
4182                                            match &prettier_path {
4183                                                Some(prettier_path) => {
4184                                                    log::error!("Failed to create prettier instance from {prettier_path:?} for buffer during autoformatting: {e:#}");
4185                                                },
4186                                                None => {
4187                                                    log::error!("Failed to create default prettier instance for buffer during autoformatting: {e:#}");
4188                                                },
4189                                            }
4190                                        }
4191                                    }
4192                            } else if let Some((language_server, buffer_abs_path)) =
4193                                language_server.as_ref().zip(buffer_abs_path.as_ref())
4194                            {
4195                                format_operation = Some(FormatOperation::Lsp(
4196                                    Self::format_via_lsp(
4197                                        &project,
4198                                        &buffer,
4199                                        buffer_abs_path,
4200                                        &language_server,
4201                                        tab_size,
4202                                        &mut cx,
4203                                    )
4204                                    .await
4205                                    .context("failed to format via language server")?,
4206                                ));
4207                            }
4208                        }
4209                        (Formatter::Prettier { .. }, FormatOnSave::On | FormatOnSave::Off) => {
4210                            if let Some((prettier_path, prettier_task)) = project
4211                                .update(&mut cx, |project, cx| {
4212                                    project.prettier_instance_for_buffer(buffer, cx)
4213                                }).await {
4214                                    match prettier_task.await
4215                                    {
4216                                        Ok(prettier) => {
4217                                            let buffer_path = buffer.update(&mut cx, |buffer, cx| File::from_dyn(buffer.file()).map(|f| f.abs_path(cx)));
4218                                            format_operation = Some(FormatOperation::Prettier(
4219                                                prettier
4220                                                    .format(buffer, buffer_path, &cx)
4221                                                    .await
4222                                                    .context("formatting via prettier")?,
4223                                            ));
4224                                        }
4225                                        Err(e) => {
4226                                            project.update(&mut cx, |project, _| {
4227                                                match &prettier_path {
4228                                                    Some(prettier_path) => {
4229                                                        project.prettier_instances.remove(prettier_path);
4230                                                    },
4231                                                    None => {
4232                                                        if let Some(default_prettier) = project.default_prettier.as_mut() {
4233                                                            default_prettier.instance = None;
4234                                                        }
4235                                                    },
4236                                                }
4237                                            });
4238                                            match &prettier_path {
4239                                                Some(prettier_path) => {
4240                                                    log::error!("Failed to create prettier instance from {prettier_path:?} for buffer during autoformatting: {e:#}");
4241                                                },
4242                                                None => {
4243                                                    log::error!("Failed to create default prettier instance for buffer during autoformatting: {e:#}");
4244                                                },
4245                                            }
4246                                        }
4247                                    }
4248                                }
4249                        }
4250                    };
4251
4252                    buffer.update(&mut cx, |b, cx| {
4253                        // If the buffer had its whitespace formatted and was edited while the language-specific
4254                        // formatting was being computed, avoid applying the language-specific formatting, because
4255                        // it can't be grouped with the whitespace formatting in the undo history.
4256                        if let Some(transaction_id) = whitespace_transaction_id {
4257                            if b.peek_undo_stack()
4258                                .map_or(true, |e| e.transaction_id() != transaction_id)
4259                            {
4260                                format_operation.take();
4261                            }
4262                        }
4263
4264                        // Apply any language-specific formatting, and group the two formatting operations
4265                        // in the buffer's undo history.
4266                        if let Some(operation) = format_operation {
4267                            match operation {
4268                                FormatOperation::Lsp(edits) => {
4269                                    b.edit(edits, None, cx);
4270                                }
4271                                FormatOperation::External(diff) => {
4272                                    b.apply_diff(diff, cx);
4273                                }
4274                                FormatOperation::Prettier(diff) => {
4275                                    b.apply_diff(diff, cx);
4276                                }
4277                            }
4278
4279                            if let Some(transaction_id) = whitespace_transaction_id {
4280                                b.group_until_transaction(transaction_id);
4281                            }
4282                        }
4283
4284                        if let Some(transaction) = b.finalize_last_transaction().cloned() {
4285                            if !push_to_history {
4286                                b.forget_transaction(transaction.id);
4287                            }
4288                            project_transaction.0.insert(buffer.clone(), transaction);
4289                        }
4290                    });
4291                }
4292
4293                Ok(project_transaction)
4294            })
4295        } else {
4296            let remote_id = self.remote_id();
4297            let client = self.client.clone();
4298            cx.spawn(|this, mut cx| async move {
4299                let mut project_transaction = ProjectTransaction::default();
4300                if let Some(project_id) = remote_id {
4301                    let response = client
4302                        .request(proto::FormatBuffers {
4303                            project_id,
4304                            trigger: trigger as i32,
4305                            buffer_ids: buffers
4306                                .iter()
4307                                .map(|buffer| buffer.read_with(&cx, |buffer, _| buffer.remote_id()))
4308                                .collect(),
4309                        })
4310                        .await?
4311                        .transaction
4312                        .ok_or_else(|| anyhow!("missing transaction"))?;
4313                    project_transaction = this
4314                        .update(&mut cx, |this, cx| {
4315                            this.deserialize_project_transaction(response, push_to_history, cx)
4316                        })
4317                        .await?;
4318                }
4319                Ok(project_transaction)
4320            })
4321        }
4322    }
4323
4324    async fn format_via_lsp(
4325        this: &ModelHandle<Self>,
4326        buffer: &ModelHandle<Buffer>,
4327        abs_path: &Path,
4328        language_server: &Arc<LanguageServer>,
4329        tab_size: NonZeroU32,
4330        cx: &mut AsyncAppContext,
4331    ) -> Result<Vec<(Range<Anchor>, String)>> {
4332        let uri = lsp::Url::from_file_path(abs_path)
4333            .map_err(|_| anyhow!("failed to convert abs path to uri"))?;
4334        let text_document = lsp::TextDocumentIdentifier::new(uri);
4335        let capabilities = &language_server.capabilities();
4336
4337        let formatting_provider = capabilities.document_formatting_provider.as_ref();
4338        let range_formatting_provider = capabilities.document_range_formatting_provider.as_ref();
4339
4340        let lsp_edits = if matches!(formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4341            language_server
4342                .request::<lsp::request::Formatting>(lsp::DocumentFormattingParams {
4343                    text_document,
4344                    options: lsp_command::lsp_formatting_options(tab_size.get()),
4345                    work_done_progress_params: Default::default(),
4346                })
4347                .await?
4348        } else if matches!(range_formatting_provider, Some(p) if *p != OneOf::Left(false)) {
4349            let buffer_start = lsp::Position::new(0, 0);
4350            let buffer_end = buffer.read_with(cx, |b, _| point_to_lsp(b.max_point_utf16()));
4351
4352            language_server
4353                .request::<lsp::request::RangeFormatting>(lsp::DocumentRangeFormattingParams {
4354                    text_document,
4355                    range: lsp::Range::new(buffer_start, buffer_end),
4356                    options: lsp_command::lsp_formatting_options(tab_size.get()),
4357                    work_done_progress_params: Default::default(),
4358                })
4359                .await?
4360        } else {
4361            None
4362        };
4363
4364        if let Some(lsp_edits) = lsp_edits {
4365            this.update(cx, |this, cx| {
4366                this.edits_from_lsp(buffer, lsp_edits, language_server.server_id(), None, cx)
4367            })
4368            .await
4369        } else {
4370            Ok(Vec::new())
4371        }
4372    }
4373
4374    async fn format_via_external_command(
4375        buffer: &ModelHandle<Buffer>,
4376        buffer_abs_path: &Path,
4377        command: &str,
4378        arguments: &[String],
4379        cx: &mut AsyncAppContext,
4380    ) -> Result<Option<Diff>> {
4381        let working_dir_path = buffer.read_with(cx, |buffer, cx| {
4382            let file = File::from_dyn(buffer.file())?;
4383            let worktree = file.worktree.read(cx).as_local()?;
4384            let mut worktree_path = worktree.abs_path().to_path_buf();
4385            if worktree.root_entry()?.is_file() {
4386                worktree_path.pop();
4387            }
4388            Some(worktree_path)
4389        });
4390
4391        if let Some(working_dir_path) = working_dir_path {
4392            let mut child =
4393                smol::process::Command::new(command)
4394                    .args(arguments.iter().map(|arg| {
4395                        arg.replace("{buffer_path}", &buffer_abs_path.to_string_lossy())
4396                    }))
4397                    .current_dir(&working_dir_path)
4398                    .stdin(smol::process::Stdio::piped())
4399                    .stdout(smol::process::Stdio::piped())
4400                    .stderr(smol::process::Stdio::piped())
4401                    .spawn()?;
4402            let stdin = child
4403                .stdin
4404                .as_mut()
4405                .ok_or_else(|| anyhow!("failed to acquire stdin"))?;
4406            let text = buffer.read_with(cx, |buffer, _| buffer.as_rope().clone());
4407            for chunk in text.chunks() {
4408                stdin.write_all(chunk.as_bytes()).await?;
4409            }
4410            stdin.flush().await?;
4411
4412            let output = child.output().await?;
4413            if !output.status.success() {
4414                return Err(anyhow!(
4415                    "command failed with exit code {:?}:\nstdout: {}\nstderr: {}",
4416                    output.status.code(),
4417                    String::from_utf8_lossy(&output.stdout),
4418                    String::from_utf8_lossy(&output.stderr),
4419                ));
4420            }
4421
4422            let stdout = String::from_utf8(output.stdout)?;
4423            Ok(Some(
4424                buffer
4425                    .read_with(cx, |buffer, cx| buffer.diff(stdout, cx))
4426                    .await,
4427            ))
4428        } else {
4429            Ok(None)
4430        }
4431    }
4432
4433    pub fn definition<T: ToPointUtf16>(
4434        &self,
4435        buffer: &ModelHandle<Buffer>,
4436        position: T,
4437        cx: &mut ModelContext<Self>,
4438    ) -> Task<Result<Vec<LocationLink>>> {
4439        let position = position.to_point_utf16(buffer.read(cx));
4440        self.request_lsp(
4441            buffer.clone(),
4442            LanguageServerToQuery::Primary,
4443            GetDefinition { position },
4444            cx,
4445        )
4446    }
4447
4448    pub fn type_definition<T: ToPointUtf16>(
4449        &self,
4450        buffer: &ModelHandle<Buffer>,
4451        position: T,
4452        cx: &mut ModelContext<Self>,
4453    ) -> Task<Result<Vec<LocationLink>>> {
4454        let position = position.to_point_utf16(buffer.read(cx));
4455        self.request_lsp(
4456            buffer.clone(),
4457            LanguageServerToQuery::Primary,
4458            GetTypeDefinition { position },
4459            cx,
4460        )
4461    }
4462
4463    pub fn references<T: ToPointUtf16>(
4464        &self,
4465        buffer: &ModelHandle<Buffer>,
4466        position: T,
4467        cx: &mut ModelContext<Self>,
4468    ) -> Task<Result<Vec<Location>>> {
4469        let position = position.to_point_utf16(buffer.read(cx));
4470        self.request_lsp(
4471            buffer.clone(),
4472            LanguageServerToQuery::Primary,
4473            GetReferences { position },
4474            cx,
4475        )
4476    }
4477
4478    pub fn document_highlights<T: ToPointUtf16>(
4479        &self,
4480        buffer: &ModelHandle<Buffer>,
4481        position: T,
4482        cx: &mut ModelContext<Self>,
4483    ) -> Task<Result<Vec<DocumentHighlight>>> {
4484        let position = position.to_point_utf16(buffer.read(cx));
4485        self.request_lsp(
4486            buffer.clone(),
4487            LanguageServerToQuery::Primary,
4488            GetDocumentHighlights { position },
4489            cx,
4490        )
4491    }
4492
4493    pub fn symbols(&self, query: &str, cx: &mut ModelContext<Self>) -> Task<Result<Vec<Symbol>>> {
4494        if self.is_local() {
4495            let mut requests = Vec::new();
4496            for ((worktree_id, _), server_id) in self.language_server_ids.iter() {
4497                let worktree_id = *worktree_id;
4498                let worktree_handle = self.worktree_for_id(worktree_id, cx);
4499                let worktree = match worktree_handle.and_then(|tree| tree.read(cx).as_local()) {
4500                    Some(worktree) => worktree,
4501                    None => continue,
4502                };
4503                let worktree_abs_path = worktree.abs_path().clone();
4504
4505                let (adapter, language, server) = match self.language_servers.get(server_id) {
4506                    Some(LanguageServerState::Running {
4507                        adapter,
4508                        language,
4509                        server,
4510                        ..
4511                    }) => (adapter.clone(), language.clone(), server),
4512
4513                    _ => continue,
4514                };
4515
4516                requests.push(
4517                    server
4518                        .request::<lsp::request::WorkspaceSymbolRequest>(
4519                            lsp::WorkspaceSymbolParams {
4520                                query: query.to_string(),
4521                                ..Default::default()
4522                            },
4523                        )
4524                        .log_err()
4525                        .map(move |response| {
4526                            let lsp_symbols = response.flatten().map(|symbol_response| match symbol_response {
4527                                lsp::WorkspaceSymbolResponse::Flat(flat_responses) => {
4528                                    flat_responses.into_iter().map(|lsp_symbol| {
4529                                        (lsp_symbol.name, lsp_symbol.kind, lsp_symbol.location)
4530                                    }).collect::<Vec<_>>()
4531                                }
4532                                lsp::WorkspaceSymbolResponse::Nested(nested_responses) => {
4533                                    nested_responses.into_iter().filter_map(|lsp_symbol| {
4534                                        let location = match lsp_symbol.location {
4535                                            OneOf::Left(location) => location,
4536                                            OneOf::Right(_) => {
4537                                                error!("Unexpected: client capabilities forbid symbol resolutions in workspace.symbol.resolveSupport");
4538                                                return None
4539                                            }
4540                                        };
4541                                        Some((lsp_symbol.name, lsp_symbol.kind, location))
4542                                    }).collect::<Vec<_>>()
4543                                }
4544                            }).unwrap_or_default();
4545
4546                            (
4547                                adapter,
4548                                language,
4549                                worktree_id,
4550                                worktree_abs_path,
4551                                lsp_symbols,
4552                            )
4553                        }),
4554                );
4555            }
4556
4557            cx.spawn_weak(|this, cx| async move {
4558                let responses = futures::future::join_all(requests).await;
4559                let this = match this.upgrade(&cx) {
4560                    Some(this) => this,
4561                    None => return Ok(Vec::new()),
4562                };
4563
4564                let symbols = this.read_with(&cx, |this, cx| {
4565                    let mut symbols = Vec::new();
4566                    for (
4567                        adapter,
4568                        adapter_language,
4569                        source_worktree_id,
4570                        worktree_abs_path,
4571                        lsp_symbols,
4572                    ) in responses
4573                    {
4574                        symbols.extend(lsp_symbols.into_iter().filter_map(
4575                            |(symbol_name, symbol_kind, symbol_location)| {
4576                                let abs_path = symbol_location.uri.to_file_path().ok()?;
4577                                let mut worktree_id = source_worktree_id;
4578                                let path;
4579                                if let Some((worktree, rel_path)) =
4580                                    this.find_local_worktree(&abs_path, cx)
4581                                {
4582                                    worktree_id = worktree.read(cx).id();
4583                                    path = rel_path;
4584                                } else {
4585                                    path = relativize_path(&worktree_abs_path, &abs_path);
4586                                }
4587
4588                                let project_path = ProjectPath {
4589                                    worktree_id,
4590                                    path: path.into(),
4591                                };
4592                                let signature = this.symbol_signature(&project_path);
4593                                let adapter_language = adapter_language.clone();
4594                                let language = this
4595                                    .languages
4596                                    .language_for_file(&project_path.path, None)
4597                                    .unwrap_or_else(move |_| adapter_language);
4598                                let language_server_name = adapter.name.clone();
4599                                Some(async move {
4600                                    let language = language.await;
4601                                    let label =
4602                                        language.label_for_symbol(&symbol_name, symbol_kind).await;
4603
4604                                    Symbol {
4605                                        language_server_name,
4606                                        source_worktree_id,
4607                                        path: project_path,
4608                                        label: label.unwrap_or_else(|| {
4609                                            CodeLabel::plain(symbol_name.clone(), None)
4610                                        }),
4611                                        kind: symbol_kind,
4612                                        name: symbol_name,
4613                                        range: range_from_lsp(symbol_location.range),
4614                                        signature,
4615                                    }
4616                                })
4617                            },
4618                        ));
4619                    }
4620
4621                    symbols
4622                });
4623
4624                Ok(futures::future::join_all(symbols).await)
4625            })
4626        } else if let Some(project_id) = self.remote_id() {
4627            let request = self.client.request(proto::GetProjectSymbols {
4628                project_id,
4629                query: query.to_string(),
4630            });
4631            cx.spawn_weak(|this, cx| async move {
4632                let response = request.await?;
4633                let mut symbols = Vec::new();
4634                if let Some(this) = this.upgrade(&cx) {
4635                    let new_symbols = this.read_with(&cx, |this, _| {
4636                        response
4637                            .symbols
4638                            .into_iter()
4639                            .map(|symbol| this.deserialize_symbol(symbol))
4640                            .collect::<Vec<_>>()
4641                    });
4642                    symbols = futures::future::join_all(new_symbols)
4643                        .await
4644                        .into_iter()
4645                        .filter_map(|symbol| symbol.log_err())
4646                        .collect::<Vec<_>>();
4647                }
4648                Ok(symbols)
4649            })
4650        } else {
4651            Task::ready(Ok(Default::default()))
4652        }
4653    }
4654
4655    pub fn open_buffer_for_symbol(
4656        &mut self,
4657        symbol: &Symbol,
4658        cx: &mut ModelContext<Self>,
4659    ) -> Task<Result<ModelHandle<Buffer>>> {
4660        if self.is_local() {
4661            let language_server_id = if let Some(id) = self.language_server_ids.get(&(
4662                symbol.source_worktree_id,
4663                symbol.language_server_name.clone(),
4664            )) {
4665                *id
4666            } else {
4667                return Task::ready(Err(anyhow!(
4668                    "language server for worktree and language not found"
4669                )));
4670            };
4671
4672            let worktree_abs_path = if let Some(worktree_abs_path) = self
4673                .worktree_for_id(symbol.path.worktree_id, cx)
4674                .and_then(|worktree| worktree.read(cx).as_local())
4675                .map(|local_worktree| local_worktree.abs_path())
4676            {
4677                worktree_abs_path
4678            } else {
4679                return Task::ready(Err(anyhow!("worktree not found for symbol")));
4680            };
4681            let symbol_abs_path = worktree_abs_path.join(&symbol.path.path);
4682            let symbol_uri = if let Ok(uri) = lsp::Url::from_file_path(symbol_abs_path) {
4683                uri
4684            } else {
4685                return Task::ready(Err(anyhow!("invalid symbol path")));
4686            };
4687
4688            self.open_local_buffer_via_lsp(
4689                symbol_uri,
4690                language_server_id,
4691                symbol.language_server_name.clone(),
4692                cx,
4693            )
4694        } else if let Some(project_id) = self.remote_id() {
4695            let request = self.client.request(proto::OpenBufferForSymbol {
4696                project_id,
4697                symbol: Some(serialize_symbol(symbol)),
4698            });
4699            cx.spawn(|this, mut cx| async move {
4700                let response = request.await?;
4701                this.update(&mut cx, |this, cx| {
4702                    this.wait_for_remote_buffer(response.buffer_id, cx)
4703                })
4704                .await
4705            })
4706        } else {
4707            Task::ready(Err(anyhow!("project does not have a remote id")))
4708        }
4709    }
4710
4711    pub fn hover<T: ToPointUtf16>(
4712        &self,
4713        buffer: &ModelHandle<Buffer>,
4714        position: T,
4715        cx: &mut ModelContext<Self>,
4716    ) -> Task<Result<Option<Hover>>> {
4717        let position = position.to_point_utf16(buffer.read(cx));
4718        self.request_lsp(
4719            buffer.clone(),
4720            LanguageServerToQuery::Primary,
4721            GetHover { position },
4722            cx,
4723        )
4724    }
4725
4726    pub fn completions<T: ToOffset + ToPointUtf16>(
4727        &self,
4728        buffer: &ModelHandle<Buffer>,
4729        position: T,
4730        cx: &mut ModelContext<Self>,
4731    ) -> Task<Result<Vec<Completion>>> {
4732        let position = position.to_point_utf16(buffer.read(cx));
4733        if self.is_local() {
4734            let snapshot = buffer.read(cx).snapshot();
4735            let offset = position.to_offset(&snapshot);
4736            let scope = snapshot.language_scope_at(offset);
4737
4738            let server_ids: Vec<_> = self
4739                .language_servers_for_buffer(buffer.read(cx), cx)
4740                .filter(|(_, server)| server.capabilities().completion_provider.is_some())
4741                .filter(|(adapter, _)| {
4742                    scope
4743                        .as_ref()
4744                        .map(|scope| scope.language_allowed(&adapter.name))
4745                        .unwrap_or(true)
4746                })
4747                .map(|(_, server)| server.server_id())
4748                .collect();
4749
4750            let buffer = buffer.clone();
4751            cx.spawn(|this, mut cx| async move {
4752                let mut tasks = Vec::with_capacity(server_ids.len());
4753                this.update(&mut cx, |this, cx| {
4754                    for server_id in server_ids {
4755                        tasks.push(this.request_lsp(
4756                            buffer.clone(),
4757                            LanguageServerToQuery::Other(server_id),
4758                            GetCompletions { position },
4759                            cx,
4760                        ));
4761                    }
4762                });
4763
4764                let mut completions = Vec::new();
4765                for task in tasks {
4766                    if let Ok(new_completions) = task.await {
4767                        completions.extend_from_slice(&new_completions);
4768                    }
4769                }
4770
4771                Ok(completions)
4772            })
4773        } else if let Some(project_id) = self.remote_id() {
4774            self.send_lsp_proto_request(buffer.clone(), project_id, GetCompletions { position }, cx)
4775        } else {
4776            Task::ready(Ok(Default::default()))
4777        }
4778    }
4779
4780    pub fn apply_additional_edits_for_completion(
4781        &self,
4782        buffer_handle: ModelHandle<Buffer>,
4783        completion: Completion,
4784        push_to_history: bool,
4785        cx: &mut ModelContext<Self>,
4786    ) -> Task<Result<Option<Transaction>>> {
4787        let buffer = buffer_handle.read(cx);
4788        let buffer_id = buffer.remote_id();
4789
4790        if self.is_local() {
4791            let server_id = completion.server_id;
4792            let lang_server = match self.language_server_for_buffer(buffer, server_id, cx) {
4793                Some((_, server)) => server.clone(),
4794                _ => return Task::ready(Ok(Default::default())),
4795            };
4796
4797            cx.spawn(|this, mut cx| async move {
4798                let can_resolve = lang_server
4799                    .capabilities()
4800                    .completion_provider
4801                    .as_ref()
4802                    .and_then(|options| options.resolve_provider)
4803                    .unwrap_or(false);
4804                let additional_text_edits = if can_resolve {
4805                    lang_server
4806                        .request::<lsp::request::ResolveCompletionItem>(completion.lsp_completion)
4807                        .await?
4808                        .additional_text_edits
4809                } else {
4810                    completion.lsp_completion.additional_text_edits
4811                };
4812                if let Some(edits) = additional_text_edits {
4813                    let edits = this
4814                        .update(&mut cx, |this, cx| {
4815                            this.edits_from_lsp(
4816                                &buffer_handle,
4817                                edits,
4818                                lang_server.server_id(),
4819                                None,
4820                                cx,
4821                            )
4822                        })
4823                        .await?;
4824
4825                    buffer_handle.update(&mut cx, |buffer, cx| {
4826                        buffer.finalize_last_transaction();
4827                        buffer.start_transaction();
4828
4829                        for (range, text) in edits {
4830                            let primary = &completion.old_range;
4831                            let start_within = primary.start.cmp(&range.start, buffer).is_le()
4832                                && primary.end.cmp(&range.start, buffer).is_ge();
4833                            let end_within = range.start.cmp(&primary.end, buffer).is_le()
4834                                && range.end.cmp(&primary.end, buffer).is_ge();
4835
4836                            //Skip additional edits which overlap with the primary completion edit
4837                            //https://github.com/zed-industries/zed/pull/1871
4838                            if !start_within && !end_within {
4839                                buffer.edit([(range, text)], None, cx);
4840                            }
4841                        }
4842
4843                        let transaction = if buffer.end_transaction(cx).is_some() {
4844                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
4845                            if !push_to_history {
4846                                buffer.forget_transaction(transaction.id);
4847                            }
4848                            Some(transaction)
4849                        } else {
4850                            None
4851                        };
4852                        Ok(transaction)
4853                    })
4854                } else {
4855                    Ok(None)
4856                }
4857            })
4858        } else if let Some(project_id) = self.remote_id() {
4859            let client = self.client.clone();
4860            cx.spawn(|_, mut cx| async move {
4861                let response = client
4862                    .request(proto::ApplyCompletionAdditionalEdits {
4863                        project_id,
4864                        buffer_id,
4865                        completion: Some(language::proto::serialize_completion(&completion)),
4866                    })
4867                    .await?;
4868
4869                if let Some(transaction) = response.transaction {
4870                    let transaction = language::proto::deserialize_transaction(transaction)?;
4871                    buffer_handle
4872                        .update(&mut cx, |buffer, _| {
4873                            buffer.wait_for_edits(transaction.edit_ids.iter().copied())
4874                        })
4875                        .await?;
4876                    if push_to_history {
4877                        buffer_handle.update(&mut cx, |buffer, _| {
4878                            buffer.push_transaction(transaction.clone(), Instant::now());
4879                        });
4880                    }
4881                    Ok(Some(transaction))
4882                } else {
4883                    Ok(None)
4884                }
4885            })
4886        } else {
4887            Task::ready(Err(anyhow!("project does not have a remote id")))
4888        }
4889    }
4890
4891    pub fn code_actions<T: Clone + ToOffset>(
4892        &self,
4893        buffer_handle: &ModelHandle<Buffer>,
4894        range: Range<T>,
4895        cx: &mut ModelContext<Self>,
4896    ) -> Task<Result<Vec<CodeAction>>> {
4897        let buffer = buffer_handle.read(cx);
4898        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
4899        self.request_lsp(
4900            buffer_handle.clone(),
4901            LanguageServerToQuery::Primary,
4902            GetCodeActions { range },
4903            cx,
4904        )
4905    }
4906
4907    pub fn apply_code_action(
4908        &self,
4909        buffer_handle: ModelHandle<Buffer>,
4910        mut action: CodeAction,
4911        push_to_history: bool,
4912        cx: &mut ModelContext<Self>,
4913    ) -> Task<Result<ProjectTransaction>> {
4914        if self.is_local() {
4915            let buffer = buffer_handle.read(cx);
4916            let (lsp_adapter, lang_server) = if let Some((adapter, server)) =
4917                self.language_server_for_buffer(buffer, action.server_id, cx)
4918            {
4919                (adapter.clone(), server.clone())
4920            } else {
4921                return Task::ready(Ok(Default::default()));
4922            };
4923            let range = action.range.to_point_utf16(buffer);
4924
4925            cx.spawn(|this, mut cx| async move {
4926                if let Some(lsp_range) = action
4927                    .lsp_action
4928                    .data
4929                    .as_mut()
4930                    .and_then(|d| d.get_mut("codeActionParams"))
4931                    .and_then(|d| d.get_mut("range"))
4932                {
4933                    *lsp_range = serde_json::to_value(&range_to_lsp(range)).unwrap();
4934                    action.lsp_action = lang_server
4935                        .request::<lsp::request::CodeActionResolveRequest>(action.lsp_action)
4936                        .await?;
4937                } else {
4938                    let actions = this
4939                        .update(&mut cx, |this, cx| {
4940                            this.code_actions(&buffer_handle, action.range, cx)
4941                        })
4942                        .await?;
4943                    action.lsp_action = actions
4944                        .into_iter()
4945                        .find(|a| a.lsp_action.title == action.lsp_action.title)
4946                        .ok_or_else(|| anyhow!("code action is outdated"))?
4947                        .lsp_action;
4948                }
4949
4950                if let Some(edit) = action.lsp_action.edit {
4951                    if edit.changes.is_some() || edit.document_changes.is_some() {
4952                        return Self::deserialize_workspace_edit(
4953                            this,
4954                            edit,
4955                            push_to_history,
4956                            lsp_adapter.clone(),
4957                            lang_server.clone(),
4958                            &mut cx,
4959                        )
4960                        .await;
4961                    }
4962                }
4963
4964                if let Some(command) = action.lsp_action.command {
4965                    this.update(&mut cx, |this, _| {
4966                        this.last_workspace_edits_by_language_server
4967                            .remove(&lang_server.server_id());
4968                    });
4969
4970                    let result = lang_server
4971                        .request::<lsp::request::ExecuteCommand>(lsp::ExecuteCommandParams {
4972                            command: command.command,
4973                            arguments: command.arguments.unwrap_or_default(),
4974                            ..Default::default()
4975                        })
4976                        .await;
4977
4978                    if let Err(err) = result {
4979                        // TODO: LSP ERROR
4980                        return Err(err);
4981                    }
4982
4983                    return Ok(this.update(&mut cx, |this, _| {
4984                        this.last_workspace_edits_by_language_server
4985                            .remove(&lang_server.server_id())
4986                            .unwrap_or_default()
4987                    }));
4988                }
4989
4990                Ok(ProjectTransaction::default())
4991            })
4992        } else if let Some(project_id) = self.remote_id() {
4993            let client = self.client.clone();
4994            let request = proto::ApplyCodeAction {
4995                project_id,
4996                buffer_id: buffer_handle.read(cx).remote_id(),
4997                action: Some(language::proto::serialize_code_action(&action)),
4998            };
4999            cx.spawn(|this, mut cx| async move {
5000                let response = client
5001                    .request(request)
5002                    .await?
5003                    .transaction
5004                    .ok_or_else(|| anyhow!("missing transaction"))?;
5005                this.update(&mut cx, |this, cx| {
5006                    this.deserialize_project_transaction(response, push_to_history, cx)
5007                })
5008                .await
5009            })
5010        } else {
5011            Task::ready(Err(anyhow!("project does not have a remote id")))
5012        }
5013    }
5014
5015    fn apply_on_type_formatting(
5016        &self,
5017        buffer: ModelHandle<Buffer>,
5018        position: Anchor,
5019        trigger: String,
5020        cx: &mut ModelContext<Self>,
5021    ) -> Task<Result<Option<Transaction>>> {
5022        if self.is_local() {
5023            cx.spawn(|this, mut cx| async move {
5024                // Do not allow multiple concurrent formatting requests for the
5025                // same buffer.
5026                this.update(&mut cx, |this, cx| {
5027                    this.buffers_being_formatted
5028                        .insert(buffer.read(cx).remote_id())
5029                });
5030
5031                let _cleanup = defer({
5032                    let this = this.clone();
5033                    let mut cx = cx.clone();
5034                    let closure_buffer = buffer.clone();
5035                    move || {
5036                        this.update(&mut cx, |this, cx| {
5037                            this.buffers_being_formatted
5038                                .remove(&closure_buffer.read(cx).remote_id());
5039                        });
5040                    }
5041                });
5042
5043                buffer
5044                    .update(&mut cx, |buffer, _| {
5045                        buffer.wait_for_edits(Some(position.timestamp))
5046                    })
5047                    .await?;
5048                this.update(&mut cx, |this, cx| {
5049                    let position = position.to_point_utf16(buffer.read(cx));
5050                    this.on_type_format(buffer, position, trigger, false, cx)
5051                })
5052                .await
5053            })
5054        } else if let Some(project_id) = self.remote_id() {
5055            let client = self.client.clone();
5056            let request = proto::OnTypeFormatting {
5057                project_id,
5058                buffer_id: buffer.read(cx).remote_id(),
5059                position: Some(serialize_anchor(&position)),
5060                trigger,
5061                version: serialize_version(&buffer.read(cx).version()),
5062            };
5063            cx.spawn(|_, _| async move {
5064                client
5065                    .request(request)
5066                    .await?
5067                    .transaction
5068                    .map(language::proto::deserialize_transaction)
5069                    .transpose()
5070            })
5071        } else {
5072            Task::ready(Err(anyhow!("project does not have a remote id")))
5073        }
5074    }
5075
5076    async fn deserialize_edits(
5077        this: ModelHandle<Self>,
5078        buffer_to_edit: ModelHandle<Buffer>,
5079        edits: Vec<lsp::TextEdit>,
5080        push_to_history: bool,
5081        _: Arc<CachedLspAdapter>,
5082        language_server: Arc<LanguageServer>,
5083        cx: &mut AsyncAppContext,
5084    ) -> Result<Option<Transaction>> {
5085        let edits = this
5086            .update(cx, |this, cx| {
5087                this.edits_from_lsp(
5088                    &buffer_to_edit,
5089                    edits,
5090                    language_server.server_id(),
5091                    None,
5092                    cx,
5093                )
5094            })
5095            .await?;
5096
5097        let transaction = buffer_to_edit.update(cx, |buffer, cx| {
5098            buffer.finalize_last_transaction();
5099            buffer.start_transaction();
5100            for (range, text) in edits {
5101                buffer.edit([(range, text)], None, cx);
5102            }
5103
5104            if buffer.end_transaction(cx).is_some() {
5105                let transaction = buffer.finalize_last_transaction().unwrap().clone();
5106                if !push_to_history {
5107                    buffer.forget_transaction(transaction.id);
5108                }
5109                Some(transaction)
5110            } else {
5111                None
5112            }
5113        });
5114
5115        Ok(transaction)
5116    }
5117
5118    async fn deserialize_workspace_edit(
5119        this: ModelHandle<Self>,
5120        edit: lsp::WorkspaceEdit,
5121        push_to_history: bool,
5122        lsp_adapter: Arc<CachedLspAdapter>,
5123        language_server: Arc<LanguageServer>,
5124        cx: &mut AsyncAppContext,
5125    ) -> Result<ProjectTransaction> {
5126        let fs = this.read_with(cx, |this, _| this.fs.clone());
5127        let mut operations = Vec::new();
5128        if let Some(document_changes) = edit.document_changes {
5129            match document_changes {
5130                lsp::DocumentChanges::Edits(edits) => {
5131                    operations.extend(edits.into_iter().map(lsp::DocumentChangeOperation::Edit))
5132                }
5133                lsp::DocumentChanges::Operations(ops) => operations = ops,
5134            }
5135        } else if let Some(changes) = edit.changes {
5136            operations.extend(changes.into_iter().map(|(uri, edits)| {
5137                lsp::DocumentChangeOperation::Edit(lsp::TextDocumentEdit {
5138                    text_document: lsp::OptionalVersionedTextDocumentIdentifier {
5139                        uri,
5140                        version: None,
5141                    },
5142                    edits: edits.into_iter().map(OneOf::Left).collect(),
5143                })
5144            }));
5145        }
5146
5147        let mut project_transaction = ProjectTransaction::default();
5148        for operation in operations {
5149            match operation {
5150                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Create(op)) => {
5151                    let abs_path = op
5152                        .uri
5153                        .to_file_path()
5154                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5155
5156                    if let Some(parent_path) = abs_path.parent() {
5157                        fs.create_dir(parent_path).await?;
5158                    }
5159                    if abs_path.ends_with("/") {
5160                        fs.create_dir(&abs_path).await?;
5161                    } else {
5162                        fs.create_file(
5163                            &abs_path,
5164                            op.options
5165                                .map(|options| fs::CreateOptions {
5166                                    overwrite: options.overwrite.unwrap_or(false),
5167                                    ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5168                                })
5169                                .unwrap_or_default(),
5170                        )
5171                        .await?;
5172                    }
5173                }
5174
5175                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Rename(op)) => {
5176                    let source_abs_path = op
5177                        .old_uri
5178                        .to_file_path()
5179                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5180                    let target_abs_path = op
5181                        .new_uri
5182                        .to_file_path()
5183                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5184                    fs.rename(
5185                        &source_abs_path,
5186                        &target_abs_path,
5187                        op.options
5188                            .map(|options| fs::RenameOptions {
5189                                overwrite: options.overwrite.unwrap_or(false),
5190                                ignore_if_exists: options.ignore_if_exists.unwrap_or(false),
5191                            })
5192                            .unwrap_or_default(),
5193                    )
5194                    .await?;
5195                }
5196
5197                lsp::DocumentChangeOperation::Op(lsp::ResourceOp::Delete(op)) => {
5198                    let abs_path = op
5199                        .uri
5200                        .to_file_path()
5201                        .map_err(|_| anyhow!("can't convert URI to path"))?;
5202                    let options = op
5203                        .options
5204                        .map(|options| fs::RemoveOptions {
5205                            recursive: options.recursive.unwrap_or(false),
5206                            ignore_if_not_exists: options.ignore_if_not_exists.unwrap_or(false),
5207                        })
5208                        .unwrap_or_default();
5209                    if abs_path.ends_with("/") {
5210                        fs.remove_dir(&abs_path, options).await?;
5211                    } else {
5212                        fs.remove_file(&abs_path, options).await?;
5213                    }
5214                }
5215
5216                lsp::DocumentChangeOperation::Edit(op) => {
5217                    let buffer_to_edit = this
5218                        .update(cx, |this, cx| {
5219                            this.open_local_buffer_via_lsp(
5220                                op.text_document.uri,
5221                                language_server.server_id(),
5222                                lsp_adapter.name.clone(),
5223                                cx,
5224                            )
5225                        })
5226                        .await?;
5227
5228                    let edits = this
5229                        .update(cx, |this, cx| {
5230                            let edits = op.edits.into_iter().map(|edit| match edit {
5231                                OneOf::Left(edit) => edit,
5232                                OneOf::Right(edit) => edit.text_edit,
5233                            });
5234                            this.edits_from_lsp(
5235                                &buffer_to_edit,
5236                                edits,
5237                                language_server.server_id(),
5238                                op.text_document.version,
5239                                cx,
5240                            )
5241                        })
5242                        .await?;
5243
5244                    let transaction = buffer_to_edit.update(cx, |buffer, cx| {
5245                        buffer.finalize_last_transaction();
5246                        buffer.start_transaction();
5247                        for (range, text) in edits {
5248                            buffer.edit([(range, text)], None, cx);
5249                        }
5250                        let transaction = if buffer.end_transaction(cx).is_some() {
5251                            let transaction = buffer.finalize_last_transaction().unwrap().clone();
5252                            if !push_to_history {
5253                                buffer.forget_transaction(transaction.id);
5254                            }
5255                            Some(transaction)
5256                        } else {
5257                            None
5258                        };
5259
5260                        transaction
5261                    });
5262                    if let Some(transaction) = transaction {
5263                        project_transaction.0.insert(buffer_to_edit, transaction);
5264                    }
5265                }
5266            }
5267        }
5268
5269        Ok(project_transaction)
5270    }
5271
5272    pub fn prepare_rename<T: ToPointUtf16>(
5273        &self,
5274        buffer: ModelHandle<Buffer>,
5275        position: T,
5276        cx: &mut ModelContext<Self>,
5277    ) -> Task<Result<Option<Range<Anchor>>>> {
5278        let position = position.to_point_utf16(buffer.read(cx));
5279        self.request_lsp(
5280            buffer,
5281            LanguageServerToQuery::Primary,
5282            PrepareRename { position },
5283            cx,
5284        )
5285    }
5286
5287    pub fn perform_rename<T: ToPointUtf16>(
5288        &self,
5289        buffer: ModelHandle<Buffer>,
5290        position: T,
5291        new_name: String,
5292        push_to_history: bool,
5293        cx: &mut ModelContext<Self>,
5294    ) -> Task<Result<ProjectTransaction>> {
5295        let position = position.to_point_utf16(buffer.read(cx));
5296        self.request_lsp(
5297            buffer,
5298            LanguageServerToQuery::Primary,
5299            PerformRename {
5300                position,
5301                new_name,
5302                push_to_history,
5303            },
5304            cx,
5305        )
5306    }
5307
5308    pub fn on_type_format<T: ToPointUtf16>(
5309        &self,
5310        buffer: ModelHandle<Buffer>,
5311        position: T,
5312        trigger: String,
5313        push_to_history: bool,
5314        cx: &mut ModelContext<Self>,
5315    ) -> Task<Result<Option<Transaction>>> {
5316        let (position, tab_size) = buffer.read_with(cx, |buffer, cx| {
5317            let position = position.to_point_utf16(buffer);
5318            (
5319                position,
5320                language_settings(buffer.language_at(position).as_ref(), buffer.file(), cx)
5321                    .tab_size,
5322            )
5323        });
5324        self.request_lsp(
5325            buffer.clone(),
5326            LanguageServerToQuery::Primary,
5327            OnTypeFormatting {
5328                position,
5329                trigger,
5330                options: lsp_command::lsp_formatting_options(tab_size.get()).into(),
5331                push_to_history,
5332            },
5333            cx,
5334        )
5335    }
5336
5337    pub fn inlay_hints<T: ToOffset>(
5338        &self,
5339        buffer_handle: ModelHandle<Buffer>,
5340        range: Range<T>,
5341        cx: &mut ModelContext<Self>,
5342    ) -> Task<anyhow::Result<Vec<InlayHint>>> {
5343        let buffer = buffer_handle.read(cx);
5344        let range = buffer.anchor_before(range.start)..buffer.anchor_before(range.end);
5345        let range_start = range.start;
5346        let range_end = range.end;
5347        let buffer_id = buffer.remote_id();
5348        let buffer_version = buffer.version().clone();
5349        let lsp_request = InlayHints { range };
5350
5351        if self.is_local() {
5352            let lsp_request_task = self.request_lsp(
5353                buffer_handle.clone(),
5354                LanguageServerToQuery::Primary,
5355                lsp_request,
5356                cx,
5357            );
5358            cx.spawn(|_, mut cx| async move {
5359                buffer_handle
5360                    .update(&mut cx, |buffer, _| {
5361                        buffer.wait_for_edits(vec![range_start.timestamp, range_end.timestamp])
5362                    })
5363                    .await
5364                    .context("waiting for inlay hint request range edits")?;
5365                lsp_request_task.await.context("inlay hints LSP request")
5366            })
5367        } else if let Some(project_id) = self.remote_id() {
5368            let client = self.client.clone();
5369            let request = proto::InlayHints {
5370                project_id,
5371                buffer_id,
5372                start: Some(serialize_anchor(&range_start)),
5373                end: Some(serialize_anchor(&range_end)),
5374                version: serialize_version(&buffer_version),
5375            };
5376            cx.spawn(|project, cx| async move {
5377                let response = client
5378                    .request(request)
5379                    .await
5380                    .context("inlay hints proto request")?;
5381                let hints_request_result = LspCommand::response_from_proto(
5382                    lsp_request,
5383                    response,
5384                    project,
5385                    buffer_handle.clone(),
5386                    cx,
5387                )
5388                .await;
5389
5390                hints_request_result.context("inlay hints proto response conversion")
5391            })
5392        } else {
5393            Task::ready(Err(anyhow!("project does not have a remote id")))
5394        }
5395    }
5396
5397    pub fn resolve_inlay_hint(
5398        &self,
5399        hint: InlayHint,
5400        buffer_handle: ModelHandle<Buffer>,
5401        server_id: LanguageServerId,
5402        cx: &mut ModelContext<Self>,
5403    ) -> Task<anyhow::Result<InlayHint>> {
5404        if self.is_local() {
5405            let buffer = buffer_handle.read(cx);
5406            let (_, lang_server) = if let Some((adapter, server)) =
5407                self.language_server_for_buffer(buffer, server_id, cx)
5408            {
5409                (adapter.clone(), server.clone())
5410            } else {
5411                return Task::ready(Ok(hint));
5412            };
5413            if !InlayHints::can_resolve_inlays(lang_server.capabilities()) {
5414                return Task::ready(Ok(hint));
5415            }
5416
5417            let buffer_snapshot = buffer.snapshot();
5418            cx.spawn(|_, mut cx| async move {
5419                let resolve_task = lang_server.request::<lsp::request::InlayHintResolveRequest>(
5420                    InlayHints::project_to_lsp_hint(hint, &buffer_snapshot),
5421                );
5422                let resolved_hint = resolve_task
5423                    .await
5424                    .context("inlay hint resolve LSP request")?;
5425                let resolved_hint = InlayHints::lsp_to_project_hint(
5426                    resolved_hint,
5427                    &buffer_handle,
5428                    server_id,
5429                    ResolveState::Resolved,
5430                    false,
5431                    &mut cx,
5432                )
5433                .await?;
5434                Ok(resolved_hint)
5435            })
5436        } else if let Some(project_id) = self.remote_id() {
5437            let client = self.client.clone();
5438            let request = proto::ResolveInlayHint {
5439                project_id,
5440                buffer_id: buffer_handle.read(cx).remote_id(),
5441                language_server_id: server_id.0 as u64,
5442                hint: Some(InlayHints::project_to_proto_hint(hint.clone())),
5443            };
5444            cx.spawn(|_, _| async move {
5445                let response = client
5446                    .request(request)
5447                    .await
5448                    .context("inlay hints proto request")?;
5449                match response.hint {
5450                    Some(resolved_hint) => InlayHints::proto_to_project_hint(resolved_hint)
5451                        .context("inlay hints proto resolve response conversion"),
5452                    None => Ok(hint),
5453                }
5454            })
5455        } else {
5456            Task::ready(Err(anyhow!("project does not have a remote id")))
5457        }
5458    }
5459
5460    #[allow(clippy::type_complexity)]
5461    pub fn search(
5462        &self,
5463        query: SearchQuery,
5464        cx: &mut ModelContext<Self>,
5465    ) -> Receiver<(ModelHandle<Buffer>, Vec<Range<Anchor>>)> {
5466        if self.is_local() {
5467            self.search_local(query, cx)
5468        } else if let Some(project_id) = self.remote_id() {
5469            let (tx, rx) = smol::channel::unbounded();
5470            let request = self.client.request(query.to_proto(project_id));
5471            cx.spawn(|this, mut cx| async move {
5472                let response = request.await?;
5473                let mut result = HashMap::default();
5474                for location in response.locations {
5475                    let target_buffer = this
5476                        .update(&mut cx, |this, cx| {
5477                            this.wait_for_remote_buffer(location.buffer_id, cx)
5478                        })
5479                        .await?;
5480                    let start = location
5481                        .start
5482                        .and_then(deserialize_anchor)
5483                        .ok_or_else(|| anyhow!("missing target start"))?;
5484                    let end = location
5485                        .end
5486                        .and_then(deserialize_anchor)
5487                        .ok_or_else(|| anyhow!("missing target end"))?;
5488                    result
5489                        .entry(target_buffer)
5490                        .or_insert(Vec::new())
5491                        .push(start..end)
5492                }
5493                for (buffer, ranges) in result {
5494                    let _ = tx.send((buffer, ranges)).await;
5495                }
5496                Result::<(), anyhow::Error>::Ok(())
5497            })
5498            .detach_and_log_err(cx);
5499            rx
5500        } else {
5501            unimplemented!();
5502        }
5503    }
5504
5505    pub fn search_local(
5506        &self,
5507        query: SearchQuery,
5508        cx: &mut ModelContext<Self>,
5509    ) -> Receiver<(ModelHandle<Buffer>, Vec<Range<Anchor>>)> {
5510        // Local search is split into several phases.
5511        // TL;DR is that we do 2 passes; initial pass to pick files which contain at least one match
5512        // and the second phase that finds positions of all the matches found in the candidate files.
5513        // The Receiver obtained from this function returns matches sorted by buffer path. Files without a buffer path are reported first.
5514        //
5515        // It gets a bit hairy though, because we must account for files that do not have a persistent representation
5516        // on FS. Namely, if you have an untitled buffer or unsaved changes in a buffer, we want to scan that too.
5517        //
5518        // 1. We initialize a queue of match candidates and feed all opened buffers into it (== unsaved files / untitled buffers).
5519        //    Then, we go through a worktree and check for files that do match a predicate. If the file had an opened version, we skip the scan
5520        //    of FS version for that file altogether - after all, what we have in memory is more up-to-date than what's in FS.
5521        // 2. At this point, we have a list of all potentially matching buffers/files.
5522        //    We sort that list by buffer path - this list is retained for later use.
5523        //    We ensure that all buffers are now opened and available in project.
5524        // 3. We run a scan over all the candidate buffers on multiple background threads.
5525        //    We cannot assume that there will even be a match - while at least one match
5526        //    is guaranteed for files obtained from FS, the buffers we got from memory (unsaved files/unnamed buffers) might not have a match at all.
5527        //    There is also an auxilliary background thread responsible for result gathering.
5528        //    This is where the sorted list of buffers comes into play to maintain sorted order; Whenever this background thread receives a notification (buffer has/doesn't have matches),
5529        //    it keeps it around. It reports matches in sorted order, though it accepts them in unsorted order as well.
5530        //    As soon as the match info on next position in sorted order becomes available, it reports it (if it's a match) or skips to the next
5531        //    entry - which might already be available thanks to out-of-order processing.
5532        //
5533        // We could also report matches fully out-of-order, without maintaining a sorted list of matching paths.
5534        // This however would mean that project search (that is the main user of this function) would have to do the sorting itself, on the go.
5535        // This isn't as straightforward as running an insertion sort sadly, and would also mean that it would have to care about maintaining match index
5536        // in face of constantly updating list of sorted matches.
5537        // Meanwhile, this implementation offers index stability, since the matches are already reported in a sorted order.
5538        let snapshots = self
5539            .visible_worktrees(cx)
5540            .filter_map(|tree| {
5541                let tree = tree.read(cx).as_local()?;
5542                Some(tree.snapshot())
5543            })
5544            .collect::<Vec<_>>();
5545
5546        let background = cx.background().clone();
5547        let path_count: usize = snapshots.iter().map(|s| s.visible_file_count()).sum();
5548        if path_count == 0 {
5549            let (_, rx) = smol::channel::bounded(1024);
5550            return rx;
5551        }
5552        let workers = background.num_cpus().min(path_count);
5553        let (matching_paths_tx, matching_paths_rx) = smol::channel::bounded(1024);
5554        let mut unnamed_files = vec![];
5555        let opened_buffers = self
5556            .opened_buffers
5557            .iter()
5558            .filter_map(|(_, b)| {
5559                let buffer = b.upgrade(cx)?;
5560                let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot());
5561                if let Some(path) = snapshot.file().map(|file| file.path()) {
5562                    Some((path.clone(), (buffer, snapshot)))
5563                } else {
5564                    unnamed_files.push(buffer);
5565                    None
5566                }
5567            })
5568            .collect();
5569        cx.background()
5570            .spawn(Self::background_search(
5571                unnamed_files,
5572                opened_buffers,
5573                cx.background().clone(),
5574                self.fs.clone(),
5575                workers,
5576                query.clone(),
5577                path_count,
5578                snapshots,
5579                matching_paths_tx,
5580            ))
5581            .detach();
5582
5583        let (buffers, buffers_rx) = Self::sort_candidates_and_open_buffers(matching_paths_rx, cx);
5584        let background = cx.background().clone();
5585        let (result_tx, result_rx) = smol::channel::bounded(1024);
5586        cx.background()
5587            .spawn(async move {
5588                let Ok(buffers) = buffers.await else {
5589                    return;
5590                };
5591
5592                let buffers_len = buffers.len();
5593                if buffers_len == 0 {
5594                    return;
5595                }
5596                let query = &query;
5597                let (finished_tx, mut finished_rx) = smol::channel::unbounded();
5598                background
5599                    .scoped(|scope| {
5600                        #[derive(Clone)]
5601                        struct FinishedStatus {
5602                            entry: Option<(ModelHandle<Buffer>, Vec<Range<Anchor>>)>,
5603                            buffer_index: SearchMatchCandidateIndex,
5604                        }
5605
5606                        for _ in 0..workers {
5607                            let finished_tx = finished_tx.clone();
5608                            let mut buffers_rx = buffers_rx.clone();
5609                            scope.spawn(async move {
5610                                while let Some((entry, buffer_index)) = buffers_rx.next().await {
5611                                    let buffer_matches = if let Some((_, snapshot)) = entry.as_ref()
5612                                    {
5613                                        if query.file_matches(
5614                                            snapshot.file().map(|file| file.path().as_ref()),
5615                                        ) {
5616                                            query
5617                                                .search(&snapshot, None)
5618                                                .await
5619                                                .iter()
5620                                                .map(|range| {
5621                                                    snapshot.anchor_before(range.start)
5622                                                        ..snapshot.anchor_after(range.end)
5623                                                })
5624                                                .collect()
5625                                        } else {
5626                                            Vec::new()
5627                                        }
5628                                    } else {
5629                                        Vec::new()
5630                                    };
5631
5632                                    let status = if !buffer_matches.is_empty() {
5633                                        let entry = if let Some((buffer, _)) = entry.as_ref() {
5634                                            Some((buffer.clone(), buffer_matches))
5635                                        } else {
5636                                            None
5637                                        };
5638                                        FinishedStatus {
5639                                            entry,
5640                                            buffer_index,
5641                                        }
5642                                    } else {
5643                                        FinishedStatus {
5644                                            entry: None,
5645                                            buffer_index,
5646                                        }
5647                                    };
5648                                    if finished_tx.send(status).await.is_err() {
5649                                        break;
5650                                    }
5651                                }
5652                            });
5653                        }
5654                        // Report sorted matches
5655                        scope.spawn(async move {
5656                            let mut current_index = 0;
5657                            let mut scratch = vec![None; buffers_len];
5658                            while let Some(status) = finished_rx.next().await {
5659                                debug_assert!(
5660                                    scratch[status.buffer_index].is_none(),
5661                                    "Got match status of position {} twice",
5662                                    status.buffer_index
5663                                );
5664                                let index = status.buffer_index;
5665                                scratch[index] = Some(status);
5666                                while current_index < buffers_len {
5667                                    let Some(current_entry) = scratch[current_index].take() else {
5668                                        // We intentionally **do not** increment `current_index` here. When next element arrives
5669                                        // from `finished_rx`, we will inspect the same position again, hoping for it to be Some(_)
5670                                        // this time.
5671                                        break;
5672                                    };
5673                                    if let Some(entry) = current_entry.entry {
5674                                        result_tx.send(entry).await.log_err();
5675                                    }
5676                                    current_index += 1;
5677                                }
5678                                if current_index == buffers_len {
5679                                    break;
5680                                }
5681                            }
5682                        });
5683                    })
5684                    .await;
5685            })
5686            .detach();
5687        result_rx
5688    }
5689    /// Pick paths that might potentially contain a match of a given search query.
5690    async fn background_search(
5691        unnamed_buffers: Vec<ModelHandle<Buffer>>,
5692        opened_buffers: HashMap<Arc<Path>, (ModelHandle<Buffer>, BufferSnapshot)>,
5693        background: Arc<Background>,
5694        fs: Arc<dyn Fs>,
5695        workers: usize,
5696        query: SearchQuery,
5697        path_count: usize,
5698        snapshots: Vec<LocalSnapshot>,
5699        matching_paths_tx: Sender<SearchMatchCandidate>,
5700    ) {
5701        let fs = &fs;
5702        let query = &query;
5703        let matching_paths_tx = &matching_paths_tx;
5704        let snapshots = &snapshots;
5705        let paths_per_worker = (path_count + workers - 1) / workers;
5706        for buffer in unnamed_buffers {
5707            matching_paths_tx
5708                .send(SearchMatchCandidate::OpenBuffer {
5709                    buffer: buffer.clone(),
5710                    path: None,
5711                })
5712                .await
5713                .log_err();
5714        }
5715        for (path, (buffer, _)) in opened_buffers.iter() {
5716            matching_paths_tx
5717                .send(SearchMatchCandidate::OpenBuffer {
5718                    buffer: buffer.clone(),
5719                    path: Some(path.clone()),
5720                })
5721                .await
5722                .log_err();
5723        }
5724        background
5725            .scoped(|scope| {
5726                for worker_ix in 0..workers {
5727                    let worker_start_ix = worker_ix * paths_per_worker;
5728                    let worker_end_ix = worker_start_ix + paths_per_worker;
5729                    let unnamed_buffers = opened_buffers.clone();
5730                    scope.spawn(async move {
5731                        let mut snapshot_start_ix = 0;
5732                        let mut abs_path = PathBuf::new();
5733                        for snapshot in snapshots {
5734                            let snapshot_end_ix = snapshot_start_ix + snapshot.visible_file_count();
5735                            if worker_end_ix <= snapshot_start_ix {
5736                                break;
5737                            } else if worker_start_ix > snapshot_end_ix {
5738                                snapshot_start_ix = snapshot_end_ix;
5739                                continue;
5740                            } else {
5741                                let start_in_snapshot =
5742                                    worker_start_ix.saturating_sub(snapshot_start_ix);
5743                                let end_in_snapshot =
5744                                    cmp::min(worker_end_ix, snapshot_end_ix) - snapshot_start_ix;
5745
5746                                for entry in snapshot
5747                                    .files(false, start_in_snapshot)
5748                                    .take(end_in_snapshot - start_in_snapshot)
5749                                {
5750                                    if matching_paths_tx.is_closed() {
5751                                        break;
5752                                    }
5753                                    if unnamed_buffers.contains_key(&entry.path) {
5754                                        continue;
5755                                    }
5756                                    let matches = if query.file_matches(Some(&entry.path)) {
5757                                        abs_path.clear();
5758                                        abs_path.push(&snapshot.abs_path());
5759                                        abs_path.push(&entry.path);
5760                                        if let Some(file) = fs.open_sync(&abs_path).await.log_err()
5761                                        {
5762                                            query.detect(file).unwrap_or(false)
5763                                        } else {
5764                                            false
5765                                        }
5766                                    } else {
5767                                        false
5768                                    };
5769
5770                                    if matches {
5771                                        let project_path = SearchMatchCandidate::Path {
5772                                            worktree_id: snapshot.id(),
5773                                            path: entry.path.clone(),
5774                                        };
5775                                        if matching_paths_tx.send(project_path).await.is_err() {
5776                                            break;
5777                                        }
5778                                    }
5779                                }
5780
5781                                snapshot_start_ix = snapshot_end_ix;
5782                            }
5783                        }
5784                    });
5785                }
5786            })
5787            .await;
5788    }
5789
5790    fn request_lsp<R: LspCommand>(
5791        &self,
5792        buffer_handle: ModelHandle<Buffer>,
5793        server: LanguageServerToQuery,
5794        request: R,
5795        cx: &mut ModelContext<Self>,
5796    ) -> Task<Result<R::Response>>
5797    where
5798        <R::LspRequest as lsp::request::Request>::Result: Send,
5799    {
5800        let buffer = buffer_handle.read(cx);
5801        if self.is_local() {
5802            let language_server = match server {
5803                LanguageServerToQuery::Primary => {
5804                    match self.primary_language_server_for_buffer(buffer, cx) {
5805                        Some((_, server)) => Some(Arc::clone(server)),
5806                        None => return Task::ready(Ok(Default::default())),
5807                    }
5808                }
5809                LanguageServerToQuery::Other(id) => self
5810                    .language_server_for_buffer(buffer, id, cx)
5811                    .map(|(_, server)| Arc::clone(server)),
5812            };
5813            let file = File::from_dyn(buffer.file()).and_then(File::as_local);
5814            if let (Some(file), Some(language_server)) = (file, language_server) {
5815                let lsp_params = request.to_lsp(&file.abs_path(cx), buffer, &language_server, cx);
5816                return cx.spawn(|this, cx| async move {
5817                    if !request.check_capabilities(language_server.capabilities()) {
5818                        return Ok(Default::default());
5819                    }
5820
5821                    let result = language_server.request::<R::LspRequest>(lsp_params).await;
5822                    let response = match result {
5823                        Ok(response) => response,
5824
5825                        Err(err) => {
5826                            log::warn!(
5827                                "Generic lsp request to {} failed: {}",
5828                                language_server.name(),
5829                                err
5830                            );
5831                            return Err(err);
5832                        }
5833                    };
5834
5835                    request
5836                        .response_from_lsp(
5837                            response,
5838                            this,
5839                            buffer_handle,
5840                            language_server.server_id(),
5841                            cx,
5842                        )
5843                        .await
5844                });
5845            }
5846        } else if let Some(project_id) = self.remote_id() {
5847            return self.send_lsp_proto_request(buffer_handle, project_id, request, cx);
5848        }
5849
5850        Task::ready(Ok(Default::default()))
5851    }
5852
5853    fn send_lsp_proto_request<R: LspCommand>(
5854        &self,
5855        buffer: ModelHandle<Buffer>,
5856        project_id: u64,
5857        request: R,
5858        cx: &mut ModelContext<'_, Project>,
5859    ) -> Task<anyhow::Result<<R as LspCommand>::Response>> {
5860        let rpc = self.client.clone();
5861        let message = request.to_proto(project_id, buffer.read(cx));
5862        cx.spawn_weak(|this, cx| async move {
5863            // Ensure the project is still alive by the time the task
5864            // is scheduled.
5865            this.upgrade(&cx)
5866                .ok_or_else(|| anyhow!("project dropped"))?;
5867            let response = rpc.request(message).await?;
5868            let this = this
5869                .upgrade(&cx)
5870                .ok_or_else(|| anyhow!("project dropped"))?;
5871            if this.read_with(&cx, |this, _| this.is_read_only()) {
5872                Err(anyhow!("disconnected before completing request"))
5873            } else {
5874                request
5875                    .response_from_proto(response, this, buffer, cx)
5876                    .await
5877            }
5878        })
5879    }
5880
5881    fn sort_candidates_and_open_buffers(
5882        mut matching_paths_rx: Receiver<SearchMatchCandidate>,
5883        cx: &mut ModelContext<Self>,
5884    ) -> (
5885        futures::channel::oneshot::Receiver<Vec<SearchMatchCandidate>>,
5886        Receiver<(
5887            Option<(ModelHandle<Buffer>, BufferSnapshot)>,
5888            SearchMatchCandidateIndex,
5889        )>,
5890    ) {
5891        let (buffers_tx, buffers_rx) = smol::channel::bounded(1024);
5892        let (sorted_buffers_tx, sorted_buffers_rx) = futures::channel::oneshot::channel();
5893        cx.spawn(|this, cx| async move {
5894            let mut buffers = vec![];
5895            while let Some(entry) = matching_paths_rx.next().await {
5896                buffers.push(entry);
5897            }
5898            buffers.sort_by_key(|candidate| candidate.path());
5899            let matching_paths = buffers.clone();
5900            let _ = sorted_buffers_tx.send(buffers);
5901            for (index, candidate) in matching_paths.into_iter().enumerate() {
5902                if buffers_tx.is_closed() {
5903                    break;
5904                }
5905                let this = this.clone();
5906                let buffers_tx = buffers_tx.clone();
5907                cx.spawn(|mut cx| async move {
5908                    let buffer = match candidate {
5909                        SearchMatchCandidate::OpenBuffer { buffer, .. } => Some(buffer),
5910                        SearchMatchCandidate::Path { worktree_id, path } => this
5911                            .update(&mut cx, |this, cx| {
5912                                this.open_buffer((worktree_id, path), cx)
5913                            })
5914                            .await
5915                            .log_err(),
5916                    };
5917                    if let Some(buffer) = buffer {
5918                        let snapshot = buffer.read_with(&cx, |buffer, _| buffer.snapshot());
5919                        buffers_tx
5920                            .send((Some((buffer, snapshot)), index))
5921                            .await
5922                            .log_err();
5923                    } else {
5924                        buffers_tx.send((None, index)).await.log_err();
5925                    }
5926
5927                    Ok::<_, anyhow::Error>(())
5928                })
5929                .detach();
5930            }
5931        })
5932        .detach();
5933        (sorted_buffers_rx, buffers_rx)
5934    }
5935
5936    pub fn find_or_create_local_worktree(
5937        &mut self,
5938        abs_path: impl AsRef<Path>,
5939        visible: bool,
5940        cx: &mut ModelContext<Self>,
5941    ) -> Task<Result<(ModelHandle<Worktree>, PathBuf)>> {
5942        let abs_path = abs_path.as_ref();
5943        if let Some((tree, relative_path)) = self.find_local_worktree(abs_path, cx) {
5944            Task::ready(Ok((tree, relative_path)))
5945        } else {
5946            let worktree = self.create_local_worktree(abs_path, visible, cx);
5947            cx.foreground()
5948                .spawn(async move { Ok((worktree.await?, PathBuf::new())) })
5949        }
5950    }
5951
5952    pub fn find_local_worktree(
5953        &self,
5954        abs_path: &Path,
5955        cx: &AppContext,
5956    ) -> Option<(ModelHandle<Worktree>, PathBuf)> {
5957        for tree in &self.worktrees {
5958            if let Some(tree) = tree.upgrade(cx) {
5959                if let Some(relative_path) = tree
5960                    .read(cx)
5961                    .as_local()
5962                    .and_then(|t| abs_path.strip_prefix(t.abs_path()).ok())
5963                {
5964                    return Some((tree.clone(), relative_path.into()));
5965                }
5966            }
5967        }
5968        None
5969    }
5970
5971    pub fn is_shared(&self) -> bool {
5972        match &self.client_state {
5973            Some(ProjectClientState::Local { .. }) => true,
5974            _ => false,
5975        }
5976    }
5977
5978    fn create_local_worktree(
5979        &mut self,
5980        abs_path: impl AsRef<Path>,
5981        visible: bool,
5982        cx: &mut ModelContext<Self>,
5983    ) -> Task<Result<ModelHandle<Worktree>>> {
5984        let fs = self.fs.clone();
5985        let client = self.client.clone();
5986        let next_entry_id = self.next_entry_id.clone();
5987        let path: Arc<Path> = abs_path.as_ref().into();
5988        let task = self
5989            .loading_local_worktrees
5990            .entry(path.clone())
5991            .or_insert_with(|| {
5992                cx.spawn(|project, mut cx| {
5993                    async move {
5994                        let worktree = Worktree::local(
5995                            client.clone(),
5996                            path.clone(),
5997                            visible,
5998                            fs,
5999                            next_entry_id,
6000                            &mut cx,
6001                        )
6002                        .await;
6003
6004                        project.update(&mut cx, |project, _| {
6005                            project.loading_local_worktrees.remove(&path);
6006                        });
6007
6008                        let worktree = worktree?;
6009                        project.update(&mut cx, |project, cx| project.add_worktree(&worktree, cx));
6010                        Ok(worktree)
6011                    }
6012                    .map_err(Arc::new)
6013                })
6014                .shared()
6015            })
6016            .clone();
6017        cx.foreground().spawn(async move {
6018            match task.await {
6019                Ok(worktree) => Ok(worktree),
6020                Err(err) => Err(anyhow!("{}", err)),
6021            }
6022        })
6023    }
6024
6025    pub fn remove_worktree(&mut self, id_to_remove: WorktreeId, cx: &mut ModelContext<Self>) {
6026        self.worktrees.retain(|worktree| {
6027            if let Some(worktree) = worktree.upgrade(cx) {
6028                let id = worktree.read(cx).id();
6029                if id == id_to_remove {
6030                    cx.emit(Event::WorktreeRemoved(id));
6031                    false
6032                } else {
6033                    true
6034                }
6035            } else {
6036                false
6037            }
6038        });
6039        self.metadata_changed(cx);
6040    }
6041
6042    fn add_worktree(&mut self, worktree: &ModelHandle<Worktree>, cx: &mut ModelContext<Self>) {
6043        cx.observe(worktree, |_, _, cx| cx.notify()).detach();
6044        if worktree.read(cx).is_local() {
6045            cx.subscribe(worktree, |this, worktree, event, cx| match event {
6046                worktree::Event::UpdatedEntries(changes) => {
6047                    this.update_local_worktree_buffers(&worktree, changes, cx);
6048                    this.update_local_worktree_language_servers(&worktree, changes, cx);
6049                    this.update_local_worktree_settings(&worktree, changes, cx);
6050                    this.update_prettier_settings(&worktree, changes, cx);
6051                    cx.emit(Event::WorktreeUpdatedEntries(
6052                        worktree.read(cx).id(),
6053                        changes.clone(),
6054                    ));
6055                }
6056                worktree::Event::UpdatedGitRepositories(updated_repos) => {
6057                    this.update_local_worktree_buffers_git_repos(worktree, updated_repos, cx)
6058                }
6059            })
6060            .detach();
6061        }
6062
6063        let push_strong_handle = {
6064            let worktree = worktree.read(cx);
6065            self.is_shared() || worktree.is_visible() || worktree.is_remote()
6066        };
6067        if push_strong_handle {
6068            self.worktrees
6069                .push(WorktreeHandle::Strong(worktree.clone()));
6070        } else {
6071            self.worktrees
6072                .push(WorktreeHandle::Weak(worktree.downgrade()));
6073        }
6074
6075        let handle_id = worktree.id();
6076        cx.observe_release(worktree, move |this, worktree, cx| {
6077            let _ = this.remove_worktree(worktree.id(), cx);
6078            cx.update_global::<SettingsStore, _, _>(|store, cx| {
6079                store.clear_local_settings(handle_id, cx).log_err()
6080            });
6081        })
6082        .detach();
6083
6084        cx.emit(Event::WorktreeAdded);
6085        self.metadata_changed(cx);
6086    }
6087
6088    fn update_local_worktree_buffers(
6089        &mut self,
6090        worktree_handle: &ModelHandle<Worktree>,
6091        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6092        cx: &mut ModelContext<Self>,
6093    ) {
6094        let snapshot = worktree_handle.read(cx).snapshot();
6095
6096        let mut renamed_buffers = Vec::new();
6097        for (path, entry_id, _) in changes {
6098            let worktree_id = worktree_handle.read(cx).id();
6099            let project_path = ProjectPath {
6100                worktree_id,
6101                path: path.clone(),
6102            };
6103
6104            let buffer_id = match self.local_buffer_ids_by_entry_id.get(entry_id) {
6105                Some(&buffer_id) => buffer_id,
6106                None => match self.local_buffer_ids_by_path.get(&project_path) {
6107                    Some(&buffer_id) => buffer_id,
6108                    None => {
6109                        continue;
6110                    }
6111                },
6112            };
6113
6114            let open_buffer = self.opened_buffers.get(&buffer_id);
6115            let buffer = if let Some(buffer) = open_buffer.and_then(|buffer| buffer.upgrade(cx)) {
6116                buffer
6117            } else {
6118                self.opened_buffers.remove(&buffer_id);
6119                self.local_buffer_ids_by_path.remove(&project_path);
6120                self.local_buffer_ids_by_entry_id.remove(entry_id);
6121                continue;
6122            };
6123
6124            buffer.update(cx, |buffer, cx| {
6125                if let Some(old_file) = File::from_dyn(buffer.file()) {
6126                    if old_file.worktree != *worktree_handle {
6127                        return;
6128                    }
6129
6130                    let new_file = if let Some(entry) = snapshot.entry_for_id(old_file.entry_id) {
6131                        File {
6132                            is_local: true,
6133                            entry_id: entry.id,
6134                            mtime: entry.mtime,
6135                            path: entry.path.clone(),
6136                            worktree: worktree_handle.clone(),
6137                            is_deleted: false,
6138                        }
6139                    } else if let Some(entry) = snapshot.entry_for_path(old_file.path().as_ref()) {
6140                        File {
6141                            is_local: true,
6142                            entry_id: entry.id,
6143                            mtime: entry.mtime,
6144                            path: entry.path.clone(),
6145                            worktree: worktree_handle.clone(),
6146                            is_deleted: false,
6147                        }
6148                    } else {
6149                        File {
6150                            is_local: true,
6151                            entry_id: old_file.entry_id,
6152                            path: old_file.path().clone(),
6153                            mtime: old_file.mtime(),
6154                            worktree: worktree_handle.clone(),
6155                            is_deleted: true,
6156                        }
6157                    };
6158
6159                    let old_path = old_file.abs_path(cx);
6160                    if new_file.abs_path(cx) != old_path {
6161                        renamed_buffers.push((cx.handle(), old_file.clone()));
6162                        self.local_buffer_ids_by_path.remove(&project_path);
6163                        self.local_buffer_ids_by_path.insert(
6164                            ProjectPath {
6165                                worktree_id,
6166                                path: path.clone(),
6167                            },
6168                            buffer_id,
6169                        );
6170                    }
6171
6172                    if new_file.entry_id != *entry_id {
6173                        self.local_buffer_ids_by_entry_id.remove(entry_id);
6174                        self.local_buffer_ids_by_entry_id
6175                            .insert(new_file.entry_id, buffer_id);
6176                    }
6177
6178                    if new_file != *old_file {
6179                        if let Some(project_id) = self.remote_id() {
6180                            self.client
6181                                .send(proto::UpdateBufferFile {
6182                                    project_id,
6183                                    buffer_id: buffer_id as u64,
6184                                    file: Some(new_file.to_proto()),
6185                                })
6186                                .log_err();
6187                        }
6188
6189                        buffer.file_updated(Arc::new(new_file), cx).detach();
6190                    }
6191                }
6192            });
6193        }
6194
6195        for (buffer, old_file) in renamed_buffers {
6196            self.unregister_buffer_from_language_servers(&buffer, &old_file, cx);
6197            self.detect_language_for_buffer(&buffer, cx);
6198            self.register_buffer_with_language_servers(&buffer, cx);
6199        }
6200    }
6201
6202    fn update_local_worktree_language_servers(
6203        &mut self,
6204        worktree_handle: &ModelHandle<Worktree>,
6205        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6206        cx: &mut ModelContext<Self>,
6207    ) {
6208        if changes.is_empty() {
6209            return;
6210        }
6211
6212        let worktree_id = worktree_handle.read(cx).id();
6213        let mut language_server_ids = self
6214            .language_server_ids
6215            .iter()
6216            .filter_map(|((server_worktree_id, _), server_id)| {
6217                (*server_worktree_id == worktree_id).then_some(*server_id)
6218            })
6219            .collect::<Vec<_>>();
6220        language_server_ids.sort();
6221        language_server_ids.dedup();
6222
6223        let abs_path = worktree_handle.read(cx).abs_path();
6224        for server_id in &language_server_ids {
6225            if let Some(LanguageServerState::Running {
6226                server,
6227                watched_paths,
6228                ..
6229            }) = self.language_servers.get(server_id)
6230            {
6231                if let Some(watched_paths) = watched_paths.get(&worktree_id) {
6232                    let params = lsp::DidChangeWatchedFilesParams {
6233                        changes: changes
6234                            .iter()
6235                            .filter_map(|(path, _, change)| {
6236                                if !watched_paths.is_match(&path) {
6237                                    return None;
6238                                }
6239                                let typ = match change {
6240                                    PathChange::Loaded => return None,
6241                                    PathChange::Added => lsp::FileChangeType::CREATED,
6242                                    PathChange::Removed => lsp::FileChangeType::DELETED,
6243                                    PathChange::Updated => lsp::FileChangeType::CHANGED,
6244                                    PathChange::AddedOrUpdated => lsp::FileChangeType::CHANGED,
6245                                };
6246                                Some(lsp::FileEvent {
6247                                    uri: lsp::Url::from_file_path(abs_path.join(path)).unwrap(),
6248                                    typ,
6249                                })
6250                            })
6251                            .collect(),
6252                    };
6253
6254                    if !params.changes.is_empty() {
6255                        server
6256                            .notify::<lsp::notification::DidChangeWatchedFiles>(params)
6257                            .log_err();
6258                    }
6259                }
6260            }
6261        }
6262    }
6263
6264    fn update_local_worktree_buffers_git_repos(
6265        &mut self,
6266        worktree_handle: ModelHandle<Worktree>,
6267        changed_repos: &UpdatedGitRepositoriesSet,
6268        cx: &mut ModelContext<Self>,
6269    ) {
6270        debug_assert!(worktree_handle.read(cx).is_local());
6271
6272        // Identify the loading buffers whose containing repository that has changed.
6273        let future_buffers = self
6274            .loading_buffers_by_path
6275            .iter()
6276            .filter_map(|(project_path, receiver)| {
6277                if project_path.worktree_id != worktree_handle.read(cx).id() {
6278                    return None;
6279                }
6280                let path = &project_path.path;
6281                changed_repos
6282                    .iter()
6283                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
6284                let receiver = receiver.clone();
6285                let path = path.clone();
6286                Some(async move {
6287                    wait_for_loading_buffer(receiver)
6288                        .await
6289                        .ok()
6290                        .map(|buffer| (buffer, path))
6291                })
6292            })
6293            .collect::<FuturesUnordered<_>>();
6294
6295        // Identify the current buffers whose containing repository has changed.
6296        let current_buffers = self
6297            .opened_buffers
6298            .values()
6299            .filter_map(|buffer| {
6300                let buffer = buffer.upgrade(cx)?;
6301                let file = File::from_dyn(buffer.read(cx).file())?;
6302                if file.worktree != worktree_handle {
6303                    return None;
6304                }
6305                let path = file.path();
6306                changed_repos
6307                    .iter()
6308                    .find(|(work_dir, _)| path.starts_with(work_dir))?;
6309                Some((buffer, path.clone()))
6310            })
6311            .collect::<Vec<_>>();
6312
6313        if future_buffers.len() + current_buffers.len() == 0 {
6314            return;
6315        }
6316
6317        let remote_id = self.remote_id();
6318        let client = self.client.clone();
6319        cx.spawn_weak(move |_, mut cx| async move {
6320            // Wait for all of the buffers to load.
6321            let future_buffers = future_buffers.collect::<Vec<_>>().await;
6322
6323            // Reload the diff base for every buffer whose containing git repository has changed.
6324            let snapshot =
6325                worktree_handle.read_with(&cx, |tree, _| tree.as_local().unwrap().snapshot());
6326            let diff_bases_by_buffer = cx
6327                .background()
6328                .spawn(async move {
6329                    future_buffers
6330                        .into_iter()
6331                        .filter_map(|e| e)
6332                        .chain(current_buffers)
6333                        .filter_map(|(buffer, path)| {
6334                            let (work_directory, repo) =
6335                                snapshot.repository_and_work_directory_for_path(&path)?;
6336                            let repo = snapshot.get_local_repo(&repo)?;
6337                            let relative_path = path.strip_prefix(&work_directory).ok()?;
6338                            let base_text = repo.repo_ptr.lock().load_index_text(&relative_path);
6339                            Some((buffer, base_text))
6340                        })
6341                        .collect::<Vec<_>>()
6342                })
6343                .await;
6344
6345            // Assign the new diff bases on all of the buffers.
6346            for (buffer, diff_base) in diff_bases_by_buffer {
6347                let buffer_id = buffer.update(&mut cx, |buffer, cx| {
6348                    buffer.set_diff_base(diff_base.clone(), cx);
6349                    buffer.remote_id()
6350                });
6351                if let Some(project_id) = remote_id {
6352                    client
6353                        .send(proto::UpdateDiffBase {
6354                            project_id,
6355                            buffer_id,
6356                            diff_base,
6357                        })
6358                        .log_err();
6359                }
6360            }
6361        })
6362        .detach();
6363    }
6364
6365    fn update_local_worktree_settings(
6366        &mut self,
6367        worktree: &ModelHandle<Worktree>,
6368        changes: &UpdatedEntriesSet,
6369        cx: &mut ModelContext<Self>,
6370    ) {
6371        let project_id = self.remote_id();
6372        let worktree_id = worktree.id();
6373        let worktree = worktree.read(cx).as_local().unwrap();
6374        let remote_worktree_id = worktree.id();
6375
6376        let mut settings_contents = Vec::new();
6377        for (path, _, change) in changes.iter() {
6378            if path.ends_with(&*LOCAL_SETTINGS_RELATIVE_PATH) {
6379                let settings_dir = Arc::from(
6380                    path.ancestors()
6381                        .nth(LOCAL_SETTINGS_RELATIVE_PATH.components().count())
6382                        .unwrap(),
6383                );
6384                let fs = self.fs.clone();
6385                let removed = *change == PathChange::Removed;
6386                let abs_path = worktree.absolutize(path);
6387                settings_contents.push(async move {
6388                    (settings_dir, (!removed).then_some(fs.load(&abs_path).await))
6389                });
6390            }
6391        }
6392
6393        if settings_contents.is_empty() {
6394            return;
6395        }
6396
6397        let client = self.client.clone();
6398        cx.spawn_weak(move |_, mut cx| async move {
6399            let settings_contents: Vec<(Arc<Path>, _)> =
6400                futures::future::join_all(settings_contents).await;
6401            cx.update(|cx| {
6402                cx.update_global::<SettingsStore, _, _>(|store, cx| {
6403                    for (directory, file_content) in settings_contents {
6404                        let file_content = file_content.and_then(|content| content.log_err());
6405                        store
6406                            .set_local_settings(
6407                                worktree_id,
6408                                directory.clone(),
6409                                file_content.as_ref().map(String::as_str),
6410                                cx,
6411                            )
6412                            .log_err();
6413                        if let Some(remote_id) = project_id {
6414                            client
6415                                .send(proto::UpdateWorktreeSettings {
6416                                    project_id: remote_id,
6417                                    worktree_id: remote_worktree_id.to_proto(),
6418                                    path: directory.to_string_lossy().into_owned(),
6419                                    content: file_content,
6420                                })
6421                                .log_err();
6422                        }
6423                    }
6424                });
6425            });
6426        })
6427        .detach();
6428    }
6429
6430    fn update_prettier_settings(
6431        &self,
6432        worktree: &ModelHandle<Worktree>,
6433        changes: &[(Arc<Path>, ProjectEntryId, PathChange)],
6434        cx: &mut ModelContext<'_, Project>,
6435    ) {
6436        let prettier_config_files = Prettier::CONFIG_FILE_NAMES
6437            .iter()
6438            .map(Path::new)
6439            .collect::<HashSet<_>>();
6440
6441        let prettier_config_file_changed = changes
6442            .iter()
6443            .filter(|(_, _, change)| !matches!(change, PathChange::Loaded))
6444            .filter(|(path, _, _)| {
6445                !path
6446                    .components()
6447                    .any(|component| component.as_os_str().to_string_lossy() == "node_modules")
6448            })
6449            .find(|(path, _, _)| prettier_config_files.contains(path.as_ref()));
6450        let current_worktree_id = worktree.read(cx).id();
6451        if let Some((config_path, _, _)) = prettier_config_file_changed {
6452            log::info!(
6453                "Prettier config file {config_path:?} changed, reloading prettier instances for worktree {current_worktree_id}"
6454            );
6455            let prettiers_to_reload = self
6456                .prettiers_per_worktree
6457                .get(&current_worktree_id)
6458                .iter()
6459                .flat_map(|prettier_paths| prettier_paths.iter())
6460                .flatten()
6461                .filter_map(|prettier_path| {
6462                    Some((
6463                        current_worktree_id,
6464                        Some(prettier_path.clone()),
6465                        self.prettier_instances.get(prettier_path)?.clone(),
6466                    ))
6467                })
6468                .chain(self.default_prettier.iter().filter_map(|default_prettier| {
6469                    Some((
6470                        current_worktree_id,
6471                        None,
6472                        default_prettier.instance.clone()?,
6473                    ))
6474                }))
6475                .collect::<Vec<_>>();
6476
6477            cx.background()
6478                .spawn(async move {
6479                    for task_result in future::join_all(prettiers_to_reload.into_iter().map(|(worktree_id, prettier_path, prettier_task)| {
6480                        async move {
6481                            prettier_task.await?
6482                                .clear_cache()
6483                                .await
6484                                .with_context(|| {
6485                                    match prettier_path {
6486                                        Some(prettier_path) => format!(
6487                                            "clearing prettier {prettier_path:?} cache for worktree {worktree_id:?} on prettier settings update"
6488                                        ),
6489                                        None => format!(
6490                                            "clearing default prettier cache for worktree {worktree_id:?} on prettier settings update"
6491                                        ),
6492                                    }
6493
6494                                })
6495                                .map_err(Arc::new)
6496                        }
6497                    }))
6498                    .await
6499                    {
6500                        if let Err(e) = task_result {
6501                            log::error!("Failed to clear cache for prettier: {e:#}");
6502                        }
6503                    }
6504                })
6505                .detach();
6506        }
6507    }
6508
6509    pub fn set_active_path(&mut self, entry: Option<ProjectPath>, cx: &mut ModelContext<Self>) {
6510        let new_active_entry = entry.and_then(|project_path| {
6511            let worktree = self.worktree_for_id(project_path.worktree_id, cx)?;
6512            let entry = worktree.read(cx).entry_for_path(project_path.path)?;
6513            Some(entry.id)
6514        });
6515        if new_active_entry != self.active_entry {
6516            self.active_entry = new_active_entry;
6517            cx.emit(Event::ActiveEntryChanged(new_active_entry));
6518        }
6519    }
6520
6521    pub fn language_servers_running_disk_based_diagnostics(
6522        &self,
6523    ) -> impl Iterator<Item = LanguageServerId> + '_ {
6524        self.language_server_statuses
6525            .iter()
6526            .filter_map(|(id, status)| {
6527                if status.has_pending_diagnostic_updates {
6528                    Some(*id)
6529                } else {
6530                    None
6531                }
6532            })
6533    }
6534
6535    pub fn diagnostic_summary(&self, cx: &AppContext) -> DiagnosticSummary {
6536        let mut summary = DiagnosticSummary::default();
6537        for (_, _, path_summary) in self.diagnostic_summaries(cx) {
6538            summary.error_count += path_summary.error_count;
6539            summary.warning_count += path_summary.warning_count;
6540        }
6541        summary
6542    }
6543
6544    pub fn diagnostic_summaries<'a>(
6545        &'a self,
6546        cx: &'a AppContext,
6547    ) -> impl Iterator<Item = (ProjectPath, LanguageServerId, DiagnosticSummary)> + 'a {
6548        self.visible_worktrees(cx).flat_map(move |worktree| {
6549            let worktree = worktree.read(cx);
6550            let worktree_id = worktree.id();
6551            worktree
6552                .diagnostic_summaries()
6553                .map(move |(path, server_id, summary)| {
6554                    (ProjectPath { worktree_id, path }, server_id, summary)
6555                })
6556        })
6557    }
6558
6559    pub fn disk_based_diagnostics_started(
6560        &mut self,
6561        language_server_id: LanguageServerId,
6562        cx: &mut ModelContext<Self>,
6563    ) {
6564        cx.emit(Event::DiskBasedDiagnosticsStarted { language_server_id });
6565    }
6566
6567    pub fn disk_based_diagnostics_finished(
6568        &mut self,
6569        language_server_id: LanguageServerId,
6570        cx: &mut ModelContext<Self>,
6571    ) {
6572        cx.emit(Event::DiskBasedDiagnosticsFinished { language_server_id });
6573    }
6574
6575    pub fn active_entry(&self) -> Option<ProjectEntryId> {
6576        self.active_entry
6577    }
6578
6579    pub fn entry_for_path(&self, path: &ProjectPath, cx: &AppContext) -> Option<Entry> {
6580        self.worktree_for_id(path.worktree_id, cx)?
6581            .read(cx)
6582            .entry_for_path(&path.path)
6583            .cloned()
6584    }
6585
6586    pub fn path_for_entry(&self, entry_id: ProjectEntryId, cx: &AppContext) -> Option<ProjectPath> {
6587        let worktree = self.worktree_for_entry(entry_id, cx)?;
6588        let worktree = worktree.read(cx);
6589        let worktree_id = worktree.id();
6590        let path = worktree.entry_for_id(entry_id)?.path.clone();
6591        Some(ProjectPath { worktree_id, path })
6592    }
6593
6594    pub fn absolute_path(&self, project_path: &ProjectPath, cx: &AppContext) -> Option<PathBuf> {
6595        let workspace_root = self
6596            .worktree_for_id(project_path.worktree_id, cx)?
6597            .read(cx)
6598            .abs_path();
6599        let project_path = project_path.path.as_ref();
6600
6601        Some(if project_path == Path::new("") {
6602            workspace_root.to_path_buf()
6603        } else {
6604            workspace_root.join(project_path)
6605        })
6606    }
6607
6608    // RPC message handlers
6609
6610    async fn handle_unshare_project(
6611        this: ModelHandle<Self>,
6612        _: TypedEnvelope<proto::UnshareProject>,
6613        _: Arc<Client>,
6614        mut cx: AsyncAppContext,
6615    ) -> Result<()> {
6616        this.update(&mut cx, |this, cx| {
6617            if this.is_local() {
6618                this.unshare(cx)?;
6619            } else {
6620                this.disconnected_from_host(cx);
6621            }
6622            Ok(())
6623        })
6624    }
6625
6626    async fn handle_add_collaborator(
6627        this: ModelHandle<Self>,
6628        mut envelope: TypedEnvelope<proto::AddProjectCollaborator>,
6629        _: Arc<Client>,
6630        mut cx: AsyncAppContext,
6631    ) -> Result<()> {
6632        let collaborator = envelope
6633            .payload
6634            .collaborator
6635            .take()
6636            .ok_or_else(|| anyhow!("empty collaborator"))?;
6637
6638        let collaborator = Collaborator::from_proto(collaborator)?;
6639        this.update(&mut cx, |this, cx| {
6640            this.shared_buffers.remove(&collaborator.peer_id);
6641            cx.emit(Event::CollaboratorJoined(collaborator.peer_id));
6642            this.collaborators
6643                .insert(collaborator.peer_id, collaborator);
6644            cx.notify();
6645        });
6646
6647        Ok(())
6648    }
6649
6650    async fn handle_update_project_collaborator(
6651        this: ModelHandle<Self>,
6652        envelope: TypedEnvelope<proto::UpdateProjectCollaborator>,
6653        _: Arc<Client>,
6654        mut cx: AsyncAppContext,
6655    ) -> Result<()> {
6656        let old_peer_id = envelope
6657            .payload
6658            .old_peer_id
6659            .ok_or_else(|| anyhow!("missing old peer id"))?;
6660        let new_peer_id = envelope
6661            .payload
6662            .new_peer_id
6663            .ok_or_else(|| anyhow!("missing new peer id"))?;
6664        this.update(&mut cx, |this, cx| {
6665            let collaborator = this
6666                .collaborators
6667                .remove(&old_peer_id)
6668                .ok_or_else(|| anyhow!("received UpdateProjectCollaborator for unknown peer"))?;
6669            let is_host = collaborator.replica_id == 0;
6670            this.collaborators.insert(new_peer_id, collaborator);
6671
6672            let buffers = this.shared_buffers.remove(&old_peer_id);
6673            log::info!(
6674                "peer {} became {}. moving buffers {:?}",
6675                old_peer_id,
6676                new_peer_id,
6677                &buffers
6678            );
6679            if let Some(buffers) = buffers {
6680                this.shared_buffers.insert(new_peer_id, buffers);
6681            }
6682
6683            if is_host {
6684                this.opened_buffers
6685                    .retain(|_, buffer| !matches!(buffer, OpenBuffer::Operations(_)));
6686                this.buffer_ordered_messages_tx
6687                    .unbounded_send(BufferOrderedMessage::Resync)
6688                    .unwrap();
6689            }
6690
6691            cx.emit(Event::CollaboratorUpdated {
6692                old_peer_id,
6693                new_peer_id,
6694            });
6695            cx.notify();
6696            Ok(())
6697        })
6698    }
6699
6700    async fn handle_remove_collaborator(
6701        this: ModelHandle<Self>,
6702        envelope: TypedEnvelope<proto::RemoveProjectCollaborator>,
6703        _: Arc<Client>,
6704        mut cx: AsyncAppContext,
6705    ) -> Result<()> {
6706        this.update(&mut cx, |this, cx| {
6707            let peer_id = envelope
6708                .payload
6709                .peer_id
6710                .ok_or_else(|| anyhow!("invalid peer id"))?;
6711            let replica_id = this
6712                .collaborators
6713                .remove(&peer_id)
6714                .ok_or_else(|| anyhow!("unknown peer {:?}", peer_id))?
6715                .replica_id;
6716            for buffer in this.opened_buffers.values() {
6717                if let Some(buffer) = buffer.upgrade(cx) {
6718                    buffer.update(cx, |buffer, cx| buffer.remove_peer(replica_id, cx));
6719                }
6720            }
6721            this.shared_buffers.remove(&peer_id);
6722
6723            cx.emit(Event::CollaboratorLeft(peer_id));
6724            cx.notify();
6725            Ok(())
6726        })
6727    }
6728
6729    async fn handle_update_project(
6730        this: ModelHandle<Self>,
6731        envelope: TypedEnvelope<proto::UpdateProject>,
6732        _: Arc<Client>,
6733        mut cx: AsyncAppContext,
6734    ) -> Result<()> {
6735        this.update(&mut cx, |this, cx| {
6736            // Don't handle messages that were sent before the response to us joining the project
6737            if envelope.message_id > this.join_project_response_message_id {
6738                this.set_worktrees_from_proto(envelope.payload.worktrees, cx)?;
6739            }
6740            Ok(())
6741        })
6742    }
6743
6744    async fn handle_update_worktree(
6745        this: ModelHandle<Self>,
6746        envelope: TypedEnvelope<proto::UpdateWorktree>,
6747        _: Arc<Client>,
6748        mut cx: AsyncAppContext,
6749    ) -> Result<()> {
6750        this.update(&mut cx, |this, cx| {
6751            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6752            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6753                worktree.update(cx, |worktree, _| {
6754                    let worktree = worktree.as_remote_mut().unwrap();
6755                    worktree.update_from_remote(envelope.payload);
6756                });
6757            }
6758            Ok(())
6759        })
6760    }
6761
6762    async fn handle_update_worktree_settings(
6763        this: ModelHandle<Self>,
6764        envelope: TypedEnvelope<proto::UpdateWorktreeSettings>,
6765        _: Arc<Client>,
6766        mut cx: AsyncAppContext,
6767    ) -> Result<()> {
6768        this.update(&mut cx, |this, cx| {
6769            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6770            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6771                cx.update_global::<SettingsStore, _, _>(|store, cx| {
6772                    store
6773                        .set_local_settings(
6774                            worktree.id(),
6775                            PathBuf::from(&envelope.payload.path).into(),
6776                            envelope.payload.content.as_ref().map(String::as_str),
6777                            cx,
6778                        )
6779                        .log_err();
6780                });
6781            }
6782            Ok(())
6783        })
6784    }
6785
6786    async fn handle_create_project_entry(
6787        this: ModelHandle<Self>,
6788        envelope: TypedEnvelope<proto::CreateProjectEntry>,
6789        _: Arc<Client>,
6790        mut cx: AsyncAppContext,
6791    ) -> Result<proto::ProjectEntryResponse> {
6792        let worktree = this.update(&mut cx, |this, cx| {
6793            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6794            this.worktree_for_id(worktree_id, cx)
6795                .ok_or_else(|| anyhow!("worktree not found"))
6796        })?;
6797        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6798        let entry = worktree
6799            .update(&mut cx, |worktree, cx| {
6800                let worktree = worktree.as_local_mut().unwrap();
6801                let path = PathBuf::from(envelope.payload.path);
6802                worktree.create_entry(path, envelope.payload.is_directory, cx)
6803            })
6804            .await?;
6805        Ok(proto::ProjectEntryResponse {
6806            entry: Some((&entry).into()),
6807            worktree_scan_id: worktree_scan_id as u64,
6808        })
6809    }
6810
6811    async fn handle_rename_project_entry(
6812        this: ModelHandle<Self>,
6813        envelope: TypedEnvelope<proto::RenameProjectEntry>,
6814        _: Arc<Client>,
6815        mut cx: AsyncAppContext,
6816    ) -> Result<proto::ProjectEntryResponse> {
6817        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6818        let worktree = this.read_with(&cx, |this, cx| {
6819            this.worktree_for_entry(entry_id, cx)
6820                .ok_or_else(|| anyhow!("worktree not found"))
6821        })?;
6822        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6823        let entry = worktree
6824            .update(&mut cx, |worktree, cx| {
6825                let new_path = PathBuf::from(envelope.payload.new_path);
6826                worktree
6827                    .as_local_mut()
6828                    .unwrap()
6829                    .rename_entry(entry_id, new_path, cx)
6830                    .ok_or_else(|| anyhow!("invalid entry"))
6831            })?
6832            .await?;
6833        Ok(proto::ProjectEntryResponse {
6834            entry: Some((&entry).into()),
6835            worktree_scan_id: worktree_scan_id as u64,
6836        })
6837    }
6838
6839    async fn handle_copy_project_entry(
6840        this: ModelHandle<Self>,
6841        envelope: TypedEnvelope<proto::CopyProjectEntry>,
6842        _: Arc<Client>,
6843        mut cx: AsyncAppContext,
6844    ) -> Result<proto::ProjectEntryResponse> {
6845        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6846        let worktree = this.read_with(&cx, |this, cx| {
6847            this.worktree_for_entry(entry_id, cx)
6848                .ok_or_else(|| anyhow!("worktree not found"))
6849        })?;
6850        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6851        let entry = worktree
6852            .update(&mut cx, |worktree, cx| {
6853                let new_path = PathBuf::from(envelope.payload.new_path);
6854                worktree
6855                    .as_local_mut()
6856                    .unwrap()
6857                    .copy_entry(entry_id, new_path, cx)
6858                    .ok_or_else(|| anyhow!("invalid entry"))
6859            })?
6860            .await?;
6861        Ok(proto::ProjectEntryResponse {
6862            entry: Some((&entry).into()),
6863            worktree_scan_id: worktree_scan_id as u64,
6864        })
6865    }
6866
6867    async fn handle_delete_project_entry(
6868        this: ModelHandle<Self>,
6869        envelope: TypedEnvelope<proto::DeleteProjectEntry>,
6870        _: Arc<Client>,
6871        mut cx: AsyncAppContext,
6872    ) -> Result<proto::ProjectEntryResponse> {
6873        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6874
6875        this.update(&mut cx, |_, cx| cx.emit(Event::DeletedEntry(entry_id)));
6876
6877        let worktree = this.read_with(&cx, |this, cx| {
6878            this.worktree_for_entry(entry_id, cx)
6879                .ok_or_else(|| anyhow!("worktree not found"))
6880        })?;
6881        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id());
6882        worktree
6883            .update(&mut cx, |worktree, cx| {
6884                worktree
6885                    .as_local_mut()
6886                    .unwrap()
6887                    .delete_entry(entry_id, cx)
6888                    .ok_or_else(|| anyhow!("invalid entry"))
6889            })?
6890            .await?;
6891        Ok(proto::ProjectEntryResponse {
6892            entry: None,
6893            worktree_scan_id: worktree_scan_id as u64,
6894        })
6895    }
6896
6897    async fn handle_expand_project_entry(
6898        this: ModelHandle<Self>,
6899        envelope: TypedEnvelope<proto::ExpandProjectEntry>,
6900        _: Arc<Client>,
6901        mut cx: AsyncAppContext,
6902    ) -> Result<proto::ExpandProjectEntryResponse> {
6903        let entry_id = ProjectEntryId::from_proto(envelope.payload.entry_id);
6904        let worktree = this
6905            .read_with(&cx, |this, cx| this.worktree_for_entry(entry_id, cx))
6906            .ok_or_else(|| anyhow!("invalid request"))?;
6907        worktree
6908            .update(&mut cx, |worktree, cx| {
6909                worktree
6910                    .as_local_mut()
6911                    .unwrap()
6912                    .expand_entry(entry_id, cx)
6913                    .ok_or_else(|| anyhow!("invalid entry"))
6914            })?
6915            .await?;
6916        let worktree_scan_id = worktree.read_with(&cx, |worktree, _| worktree.scan_id()) as u64;
6917        Ok(proto::ExpandProjectEntryResponse { worktree_scan_id })
6918    }
6919
6920    async fn handle_update_diagnostic_summary(
6921        this: ModelHandle<Self>,
6922        envelope: TypedEnvelope<proto::UpdateDiagnosticSummary>,
6923        _: Arc<Client>,
6924        mut cx: AsyncAppContext,
6925    ) -> Result<()> {
6926        this.update(&mut cx, |this, cx| {
6927            let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
6928            if let Some(worktree) = this.worktree_for_id(worktree_id, cx) {
6929                if let Some(summary) = envelope.payload.summary {
6930                    let project_path = ProjectPath {
6931                        worktree_id,
6932                        path: Path::new(&summary.path).into(),
6933                    };
6934                    worktree.update(cx, |worktree, _| {
6935                        worktree
6936                            .as_remote_mut()
6937                            .unwrap()
6938                            .update_diagnostic_summary(project_path.path.clone(), &summary);
6939                    });
6940                    cx.emit(Event::DiagnosticsUpdated {
6941                        language_server_id: LanguageServerId(summary.language_server_id as usize),
6942                        path: project_path,
6943                    });
6944                }
6945            }
6946            Ok(())
6947        })
6948    }
6949
6950    async fn handle_start_language_server(
6951        this: ModelHandle<Self>,
6952        envelope: TypedEnvelope<proto::StartLanguageServer>,
6953        _: Arc<Client>,
6954        mut cx: AsyncAppContext,
6955    ) -> Result<()> {
6956        let server = envelope
6957            .payload
6958            .server
6959            .ok_or_else(|| anyhow!("invalid server"))?;
6960        this.update(&mut cx, |this, cx| {
6961            this.language_server_statuses.insert(
6962                LanguageServerId(server.id as usize),
6963                LanguageServerStatus {
6964                    name: server.name,
6965                    pending_work: Default::default(),
6966                    has_pending_diagnostic_updates: false,
6967                    progress_tokens: Default::default(),
6968                },
6969            );
6970            cx.notify();
6971        });
6972        Ok(())
6973    }
6974
6975    async fn handle_update_language_server(
6976        this: ModelHandle<Self>,
6977        envelope: TypedEnvelope<proto::UpdateLanguageServer>,
6978        _: Arc<Client>,
6979        mut cx: AsyncAppContext,
6980    ) -> Result<()> {
6981        this.update(&mut cx, |this, cx| {
6982            let language_server_id = LanguageServerId(envelope.payload.language_server_id as usize);
6983
6984            match envelope
6985                .payload
6986                .variant
6987                .ok_or_else(|| anyhow!("invalid variant"))?
6988            {
6989                proto::update_language_server::Variant::WorkStart(payload) => {
6990                    this.on_lsp_work_start(
6991                        language_server_id,
6992                        payload.token,
6993                        LanguageServerProgress {
6994                            message: payload.message,
6995                            percentage: payload.percentage.map(|p| p as usize),
6996                            last_update_at: Instant::now(),
6997                        },
6998                        cx,
6999                    );
7000                }
7001
7002                proto::update_language_server::Variant::WorkProgress(payload) => {
7003                    this.on_lsp_work_progress(
7004                        language_server_id,
7005                        payload.token,
7006                        LanguageServerProgress {
7007                            message: payload.message,
7008                            percentage: payload.percentage.map(|p| p as usize),
7009                            last_update_at: Instant::now(),
7010                        },
7011                        cx,
7012                    );
7013                }
7014
7015                proto::update_language_server::Variant::WorkEnd(payload) => {
7016                    this.on_lsp_work_end(language_server_id, payload.token, cx);
7017                }
7018
7019                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdating(_) => {
7020                    this.disk_based_diagnostics_started(language_server_id, cx);
7021                }
7022
7023                proto::update_language_server::Variant::DiskBasedDiagnosticsUpdated(_) => {
7024                    this.disk_based_diagnostics_finished(language_server_id, cx)
7025                }
7026            }
7027
7028            Ok(())
7029        })
7030    }
7031
7032    async fn handle_update_buffer(
7033        this: ModelHandle<Self>,
7034        envelope: TypedEnvelope<proto::UpdateBuffer>,
7035        _: Arc<Client>,
7036        mut cx: AsyncAppContext,
7037    ) -> Result<proto::Ack> {
7038        this.update(&mut cx, |this, cx| {
7039            let payload = envelope.payload.clone();
7040            let buffer_id = payload.buffer_id;
7041            let ops = payload
7042                .operations
7043                .into_iter()
7044                .map(language::proto::deserialize_operation)
7045                .collect::<Result<Vec<_>, _>>()?;
7046            let is_remote = this.is_remote();
7047            match this.opened_buffers.entry(buffer_id) {
7048                hash_map::Entry::Occupied(mut e) => match e.get_mut() {
7049                    OpenBuffer::Strong(buffer) => {
7050                        buffer.update(cx, |buffer, cx| buffer.apply_ops(ops, cx))?;
7051                    }
7052                    OpenBuffer::Operations(operations) => operations.extend_from_slice(&ops),
7053                    OpenBuffer::Weak(_) => {}
7054                },
7055                hash_map::Entry::Vacant(e) => {
7056                    assert!(
7057                        is_remote,
7058                        "received buffer update from {:?}",
7059                        envelope.original_sender_id
7060                    );
7061                    e.insert(OpenBuffer::Operations(ops));
7062                }
7063            }
7064            Ok(proto::Ack {})
7065        })
7066    }
7067
7068    async fn handle_create_buffer_for_peer(
7069        this: ModelHandle<Self>,
7070        envelope: TypedEnvelope<proto::CreateBufferForPeer>,
7071        _: Arc<Client>,
7072        mut cx: AsyncAppContext,
7073    ) -> Result<()> {
7074        this.update(&mut cx, |this, cx| {
7075            match envelope
7076                .payload
7077                .variant
7078                .ok_or_else(|| anyhow!("missing variant"))?
7079            {
7080                proto::create_buffer_for_peer::Variant::State(mut state) => {
7081                    let mut buffer_file = None;
7082                    if let Some(file) = state.file.take() {
7083                        let worktree_id = WorktreeId::from_proto(file.worktree_id);
7084                        let worktree = this.worktree_for_id(worktree_id, cx).ok_or_else(|| {
7085                            anyhow!("no worktree found for id {}", file.worktree_id)
7086                        })?;
7087                        buffer_file = Some(Arc::new(File::from_proto(file, worktree.clone(), cx)?)
7088                            as Arc<dyn language::File>);
7089                    }
7090
7091                    let buffer_id = state.id;
7092                    let buffer = cx.add_model(|_| {
7093                        Buffer::from_proto(this.replica_id(), state, buffer_file).unwrap()
7094                    });
7095                    this.incomplete_remote_buffers
7096                        .insert(buffer_id, Some(buffer));
7097                }
7098                proto::create_buffer_for_peer::Variant::Chunk(chunk) => {
7099                    let buffer = this
7100                        .incomplete_remote_buffers
7101                        .get(&chunk.buffer_id)
7102                        .cloned()
7103                        .flatten()
7104                        .ok_or_else(|| {
7105                            anyhow!(
7106                                "received chunk for buffer {} without initial state",
7107                                chunk.buffer_id
7108                            )
7109                        })?;
7110                    let operations = chunk
7111                        .operations
7112                        .into_iter()
7113                        .map(language::proto::deserialize_operation)
7114                        .collect::<Result<Vec<_>>>()?;
7115                    buffer.update(cx, |buffer, cx| buffer.apply_ops(operations, cx))?;
7116
7117                    if chunk.is_last {
7118                        this.incomplete_remote_buffers.remove(&chunk.buffer_id);
7119                        this.register_buffer(&buffer, cx)?;
7120                    }
7121                }
7122            }
7123
7124            Ok(())
7125        })
7126    }
7127
7128    async fn handle_update_diff_base(
7129        this: ModelHandle<Self>,
7130        envelope: TypedEnvelope<proto::UpdateDiffBase>,
7131        _: Arc<Client>,
7132        mut cx: AsyncAppContext,
7133    ) -> Result<()> {
7134        this.update(&mut cx, |this, cx| {
7135            let buffer_id = envelope.payload.buffer_id;
7136            let diff_base = envelope.payload.diff_base;
7137            if let Some(buffer) = this
7138                .opened_buffers
7139                .get_mut(&buffer_id)
7140                .and_then(|b| b.upgrade(cx))
7141                .or_else(|| {
7142                    this.incomplete_remote_buffers
7143                        .get(&buffer_id)
7144                        .cloned()
7145                        .flatten()
7146                })
7147            {
7148                buffer.update(cx, |buffer, cx| buffer.set_diff_base(diff_base, cx));
7149            }
7150            Ok(())
7151        })
7152    }
7153
7154    async fn handle_update_buffer_file(
7155        this: ModelHandle<Self>,
7156        envelope: TypedEnvelope<proto::UpdateBufferFile>,
7157        _: Arc<Client>,
7158        mut cx: AsyncAppContext,
7159    ) -> Result<()> {
7160        let buffer_id = envelope.payload.buffer_id;
7161
7162        this.update(&mut cx, |this, cx| {
7163            let payload = envelope.payload.clone();
7164            if let Some(buffer) = this
7165                .opened_buffers
7166                .get(&buffer_id)
7167                .and_then(|b| b.upgrade(cx))
7168                .or_else(|| {
7169                    this.incomplete_remote_buffers
7170                        .get(&buffer_id)
7171                        .cloned()
7172                        .flatten()
7173                })
7174            {
7175                let file = payload.file.ok_or_else(|| anyhow!("invalid file"))?;
7176                let worktree = this
7177                    .worktree_for_id(WorktreeId::from_proto(file.worktree_id), cx)
7178                    .ok_or_else(|| anyhow!("no such worktree"))?;
7179                let file = File::from_proto(file, worktree, cx)?;
7180                buffer.update(cx, |buffer, cx| {
7181                    buffer.file_updated(Arc::new(file), cx).detach();
7182                });
7183                this.detect_language_for_buffer(&buffer, cx);
7184            }
7185            Ok(())
7186        })
7187    }
7188
7189    async fn handle_save_buffer(
7190        this: ModelHandle<Self>,
7191        envelope: TypedEnvelope<proto::SaveBuffer>,
7192        _: Arc<Client>,
7193        mut cx: AsyncAppContext,
7194    ) -> Result<proto::BufferSaved> {
7195        let buffer_id = envelope.payload.buffer_id;
7196        let (project_id, buffer) = this.update(&mut cx, |this, cx| {
7197            let project_id = this.remote_id().ok_or_else(|| anyhow!("not connected"))?;
7198            let buffer = this
7199                .opened_buffers
7200                .get(&buffer_id)
7201                .and_then(|buffer| buffer.upgrade(cx))
7202                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?;
7203            anyhow::Ok((project_id, buffer))
7204        })?;
7205        buffer
7206            .update(&mut cx, |buffer, _| {
7207                buffer.wait_for_version(deserialize_version(&envelope.payload.version))
7208            })
7209            .await?;
7210        let buffer_id = buffer.read_with(&cx, |buffer, _| buffer.remote_id());
7211
7212        this.update(&mut cx, |this, cx| this.save_buffer(buffer.clone(), cx))
7213            .await?;
7214        Ok(buffer.read_with(&cx, |buffer, _| proto::BufferSaved {
7215            project_id,
7216            buffer_id,
7217            version: serialize_version(buffer.saved_version()),
7218            mtime: Some(buffer.saved_mtime().into()),
7219            fingerprint: language::proto::serialize_fingerprint(buffer.saved_version_fingerprint()),
7220        }))
7221    }
7222
7223    async fn handle_reload_buffers(
7224        this: ModelHandle<Self>,
7225        envelope: TypedEnvelope<proto::ReloadBuffers>,
7226        _: Arc<Client>,
7227        mut cx: AsyncAppContext,
7228    ) -> Result<proto::ReloadBuffersResponse> {
7229        let sender_id = envelope.original_sender_id()?;
7230        let reload = this.update(&mut cx, |this, cx| {
7231            let mut buffers = HashSet::default();
7232            for buffer_id in &envelope.payload.buffer_ids {
7233                buffers.insert(
7234                    this.opened_buffers
7235                        .get(buffer_id)
7236                        .and_then(|buffer| buffer.upgrade(cx))
7237                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
7238                );
7239            }
7240            Ok::<_, anyhow::Error>(this.reload_buffers(buffers, false, cx))
7241        })?;
7242
7243        let project_transaction = reload.await?;
7244        let project_transaction = this.update(&mut cx, |this, cx| {
7245            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7246        });
7247        Ok(proto::ReloadBuffersResponse {
7248            transaction: Some(project_transaction),
7249        })
7250    }
7251
7252    async fn handle_synchronize_buffers(
7253        this: ModelHandle<Self>,
7254        envelope: TypedEnvelope<proto::SynchronizeBuffers>,
7255        _: Arc<Client>,
7256        mut cx: AsyncAppContext,
7257    ) -> Result<proto::SynchronizeBuffersResponse> {
7258        let project_id = envelope.payload.project_id;
7259        let mut response = proto::SynchronizeBuffersResponse {
7260            buffers: Default::default(),
7261        };
7262
7263        this.update(&mut cx, |this, cx| {
7264            let Some(guest_id) = envelope.original_sender_id else {
7265                error!("missing original_sender_id on SynchronizeBuffers request");
7266                return;
7267            };
7268
7269            this.shared_buffers.entry(guest_id).or_default().clear();
7270            for buffer in envelope.payload.buffers {
7271                let buffer_id = buffer.id;
7272                let remote_version = language::proto::deserialize_version(&buffer.version);
7273                if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
7274                    this.shared_buffers
7275                        .entry(guest_id)
7276                        .or_default()
7277                        .insert(buffer_id);
7278
7279                    let buffer = buffer.read(cx);
7280                    response.buffers.push(proto::BufferVersion {
7281                        id: buffer_id,
7282                        version: language::proto::serialize_version(&buffer.version),
7283                    });
7284
7285                    let operations = buffer.serialize_ops(Some(remote_version), cx);
7286                    let client = this.client.clone();
7287                    if let Some(file) = buffer.file() {
7288                        client
7289                            .send(proto::UpdateBufferFile {
7290                                project_id,
7291                                buffer_id: buffer_id as u64,
7292                                file: Some(file.to_proto()),
7293                            })
7294                            .log_err();
7295                    }
7296
7297                    client
7298                        .send(proto::UpdateDiffBase {
7299                            project_id,
7300                            buffer_id: buffer_id as u64,
7301                            diff_base: buffer.diff_base().map(Into::into),
7302                        })
7303                        .log_err();
7304
7305                    client
7306                        .send(proto::BufferReloaded {
7307                            project_id,
7308                            buffer_id,
7309                            version: language::proto::serialize_version(buffer.saved_version()),
7310                            mtime: Some(buffer.saved_mtime().into()),
7311                            fingerprint: language::proto::serialize_fingerprint(
7312                                buffer.saved_version_fingerprint(),
7313                            ),
7314                            line_ending: language::proto::serialize_line_ending(
7315                                buffer.line_ending(),
7316                            ) as i32,
7317                        })
7318                        .log_err();
7319
7320                    cx.background()
7321                        .spawn(
7322                            async move {
7323                                let operations = operations.await;
7324                                for chunk in split_operations(operations) {
7325                                    client
7326                                        .request(proto::UpdateBuffer {
7327                                            project_id,
7328                                            buffer_id,
7329                                            operations: chunk,
7330                                        })
7331                                        .await?;
7332                                }
7333                                anyhow::Ok(())
7334                            }
7335                            .log_err(),
7336                        )
7337                        .detach();
7338                }
7339            }
7340        });
7341
7342        Ok(response)
7343    }
7344
7345    async fn handle_format_buffers(
7346        this: ModelHandle<Self>,
7347        envelope: TypedEnvelope<proto::FormatBuffers>,
7348        _: Arc<Client>,
7349        mut cx: AsyncAppContext,
7350    ) -> Result<proto::FormatBuffersResponse> {
7351        let sender_id = envelope.original_sender_id()?;
7352        let format = this.update(&mut cx, |this, cx| {
7353            let mut buffers = HashSet::default();
7354            for buffer_id in &envelope.payload.buffer_ids {
7355                buffers.insert(
7356                    this.opened_buffers
7357                        .get(buffer_id)
7358                        .and_then(|buffer| buffer.upgrade(cx))
7359                        .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))?,
7360                );
7361            }
7362            let trigger = FormatTrigger::from_proto(envelope.payload.trigger);
7363            Ok::<_, anyhow::Error>(this.format(buffers, false, trigger, cx))
7364        })?;
7365
7366        let project_transaction = format.await?;
7367        let project_transaction = this.update(&mut cx, |this, cx| {
7368            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7369        });
7370        Ok(proto::FormatBuffersResponse {
7371            transaction: Some(project_transaction),
7372        })
7373    }
7374
7375    async fn handle_apply_additional_edits_for_completion(
7376        this: ModelHandle<Self>,
7377        envelope: TypedEnvelope<proto::ApplyCompletionAdditionalEdits>,
7378        _: Arc<Client>,
7379        mut cx: AsyncAppContext,
7380    ) -> Result<proto::ApplyCompletionAdditionalEditsResponse> {
7381        let (buffer, completion) = this.update(&mut cx, |this, cx| {
7382            let buffer = this
7383                .opened_buffers
7384                .get(&envelope.payload.buffer_id)
7385                .and_then(|buffer| buffer.upgrade(cx))
7386                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7387            let language = buffer.read(cx).language();
7388            let completion = language::proto::deserialize_completion(
7389                envelope
7390                    .payload
7391                    .completion
7392                    .ok_or_else(|| anyhow!("invalid completion"))?,
7393                language.cloned(),
7394            );
7395            Ok::<_, anyhow::Error>((buffer, completion))
7396        })?;
7397
7398        let completion = completion.await?;
7399
7400        let apply_additional_edits = this.update(&mut cx, |this, cx| {
7401            this.apply_additional_edits_for_completion(buffer, completion, false, cx)
7402        });
7403
7404        Ok(proto::ApplyCompletionAdditionalEditsResponse {
7405            transaction: apply_additional_edits
7406                .await?
7407                .as_ref()
7408                .map(language::proto::serialize_transaction),
7409        })
7410    }
7411
7412    async fn handle_resolve_completion_documentation(
7413        this: ModelHandle<Self>,
7414        envelope: TypedEnvelope<proto::ResolveCompletionDocumentation>,
7415        _: Arc<Client>,
7416        mut cx: AsyncAppContext,
7417    ) -> Result<proto::ResolveCompletionDocumentationResponse> {
7418        let lsp_completion = serde_json::from_slice(&envelope.payload.lsp_completion)?;
7419
7420        let completion = this
7421            .read_with(&mut cx, |this, _| {
7422                let id = LanguageServerId(envelope.payload.language_server_id as usize);
7423                let Some(server) = this.language_server_for_id(id) else {
7424                    return Err(anyhow!("No language server {id}"));
7425                };
7426
7427                Ok(server.request::<lsp::request::ResolveCompletionItem>(lsp_completion))
7428            })?
7429            .await?;
7430
7431        let mut is_markdown = false;
7432        let text = match completion.documentation {
7433            Some(lsp::Documentation::String(text)) => text,
7434
7435            Some(lsp::Documentation::MarkupContent(lsp::MarkupContent { kind, value })) => {
7436                is_markdown = kind == lsp::MarkupKind::Markdown;
7437                value
7438            }
7439
7440            _ => String::new(),
7441        };
7442
7443        Ok(proto::ResolveCompletionDocumentationResponse { text, is_markdown })
7444    }
7445
7446    async fn handle_apply_code_action(
7447        this: ModelHandle<Self>,
7448        envelope: TypedEnvelope<proto::ApplyCodeAction>,
7449        _: Arc<Client>,
7450        mut cx: AsyncAppContext,
7451    ) -> Result<proto::ApplyCodeActionResponse> {
7452        let sender_id = envelope.original_sender_id()?;
7453        let action = language::proto::deserialize_code_action(
7454            envelope
7455                .payload
7456                .action
7457                .ok_or_else(|| anyhow!("invalid action"))?,
7458        )?;
7459        let apply_code_action = this.update(&mut cx, |this, cx| {
7460            let buffer = this
7461                .opened_buffers
7462                .get(&envelope.payload.buffer_id)
7463                .and_then(|buffer| buffer.upgrade(cx))
7464                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7465            Ok::<_, anyhow::Error>(this.apply_code_action(buffer, action, false, cx))
7466        })?;
7467
7468        let project_transaction = apply_code_action.await?;
7469        let project_transaction = this.update(&mut cx, |this, cx| {
7470            this.serialize_project_transaction_for_peer(project_transaction, sender_id, cx)
7471        });
7472        Ok(proto::ApplyCodeActionResponse {
7473            transaction: Some(project_transaction),
7474        })
7475    }
7476
7477    async fn handle_on_type_formatting(
7478        this: ModelHandle<Self>,
7479        envelope: TypedEnvelope<proto::OnTypeFormatting>,
7480        _: Arc<Client>,
7481        mut cx: AsyncAppContext,
7482    ) -> Result<proto::OnTypeFormattingResponse> {
7483        let on_type_formatting = this.update(&mut cx, |this, cx| {
7484            let buffer = this
7485                .opened_buffers
7486                .get(&envelope.payload.buffer_id)
7487                .and_then(|buffer| buffer.upgrade(cx))
7488                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))?;
7489            let position = envelope
7490                .payload
7491                .position
7492                .and_then(deserialize_anchor)
7493                .ok_or_else(|| anyhow!("invalid position"))?;
7494            Ok::<_, anyhow::Error>(this.apply_on_type_formatting(
7495                buffer,
7496                position,
7497                envelope.payload.trigger.clone(),
7498                cx,
7499            ))
7500        })?;
7501
7502        let transaction = on_type_formatting
7503            .await?
7504            .as_ref()
7505            .map(language::proto::serialize_transaction);
7506        Ok(proto::OnTypeFormattingResponse { transaction })
7507    }
7508
7509    async fn handle_inlay_hints(
7510        this: ModelHandle<Self>,
7511        envelope: TypedEnvelope<proto::InlayHints>,
7512        _: Arc<Client>,
7513        mut cx: AsyncAppContext,
7514    ) -> Result<proto::InlayHintsResponse> {
7515        let sender_id = envelope.original_sender_id()?;
7516        let buffer = this.update(&mut cx, |this, cx| {
7517            this.opened_buffers
7518                .get(&envelope.payload.buffer_id)
7519                .and_then(|buffer| buffer.upgrade(cx))
7520                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
7521        })?;
7522        let buffer_version = deserialize_version(&envelope.payload.version);
7523
7524        buffer
7525            .update(&mut cx, |buffer, _| {
7526                buffer.wait_for_version(buffer_version.clone())
7527            })
7528            .await
7529            .with_context(|| {
7530                format!(
7531                    "waiting for version {:?} for buffer {}",
7532                    buffer_version,
7533                    buffer.id()
7534                )
7535            })?;
7536
7537        let start = envelope
7538            .payload
7539            .start
7540            .and_then(deserialize_anchor)
7541            .context("missing range start")?;
7542        let end = envelope
7543            .payload
7544            .end
7545            .and_then(deserialize_anchor)
7546            .context("missing range end")?;
7547        let buffer_hints = this
7548            .update(&mut cx, |project, cx| {
7549                project.inlay_hints(buffer, start..end, cx)
7550            })
7551            .await
7552            .context("inlay hints fetch")?;
7553
7554        Ok(this.update(&mut cx, |project, cx| {
7555            InlayHints::response_to_proto(buffer_hints, project, sender_id, &buffer_version, cx)
7556        }))
7557    }
7558
7559    async fn handle_resolve_inlay_hint(
7560        this: ModelHandle<Self>,
7561        envelope: TypedEnvelope<proto::ResolveInlayHint>,
7562        _: Arc<Client>,
7563        mut cx: AsyncAppContext,
7564    ) -> Result<proto::ResolveInlayHintResponse> {
7565        let proto_hint = envelope
7566            .payload
7567            .hint
7568            .expect("incorrect protobuf resolve inlay hint message: missing the inlay hint");
7569        let hint = InlayHints::proto_to_project_hint(proto_hint)
7570            .context("resolved proto inlay hint conversion")?;
7571        let buffer = this.update(&mut cx, |this, cx| {
7572            this.opened_buffers
7573                .get(&envelope.payload.buffer_id)
7574                .and_then(|buffer| buffer.upgrade(cx))
7575                .ok_or_else(|| anyhow!("unknown buffer id {}", envelope.payload.buffer_id))
7576        })?;
7577        let response_hint = this
7578            .update(&mut cx, |project, cx| {
7579                project.resolve_inlay_hint(
7580                    hint,
7581                    buffer,
7582                    LanguageServerId(envelope.payload.language_server_id as usize),
7583                    cx,
7584                )
7585            })
7586            .await
7587            .context("inlay hints fetch")?;
7588        Ok(proto::ResolveInlayHintResponse {
7589            hint: Some(InlayHints::project_to_proto_hint(response_hint)),
7590        })
7591    }
7592
7593    async fn handle_refresh_inlay_hints(
7594        this: ModelHandle<Self>,
7595        _: TypedEnvelope<proto::RefreshInlayHints>,
7596        _: Arc<Client>,
7597        mut cx: AsyncAppContext,
7598    ) -> Result<proto::Ack> {
7599        this.update(&mut cx, |_, cx| {
7600            cx.emit(Event::RefreshInlayHints);
7601        });
7602        Ok(proto::Ack {})
7603    }
7604
7605    async fn handle_lsp_command<T: LspCommand>(
7606        this: ModelHandle<Self>,
7607        envelope: TypedEnvelope<T::ProtoRequest>,
7608        _: Arc<Client>,
7609        mut cx: AsyncAppContext,
7610    ) -> Result<<T::ProtoRequest as proto::RequestMessage>::Response>
7611    where
7612        <T::LspRequest as lsp::request::Request>::Result: Send,
7613    {
7614        let sender_id = envelope.original_sender_id()?;
7615        let buffer_id = T::buffer_id_from_proto(&envelope.payload);
7616        let buffer_handle = this.read_with(&cx, |this, _| {
7617            this.opened_buffers
7618                .get(&buffer_id)
7619                .and_then(|buffer| buffer.upgrade(&cx))
7620                .ok_or_else(|| anyhow!("unknown buffer id {}", buffer_id))
7621        })?;
7622        let request = T::from_proto(
7623            envelope.payload,
7624            this.clone(),
7625            buffer_handle.clone(),
7626            cx.clone(),
7627        )
7628        .await?;
7629        let buffer_version = buffer_handle.read_with(&cx, |buffer, _| buffer.version());
7630        let response = this
7631            .update(&mut cx, |this, cx| {
7632                this.request_lsp(buffer_handle, LanguageServerToQuery::Primary, request, cx)
7633            })
7634            .await?;
7635        this.update(&mut cx, |this, cx| {
7636            Ok(T::response_to_proto(
7637                response,
7638                this,
7639                sender_id,
7640                &buffer_version,
7641                cx,
7642            ))
7643        })
7644    }
7645
7646    async fn handle_get_project_symbols(
7647        this: ModelHandle<Self>,
7648        envelope: TypedEnvelope<proto::GetProjectSymbols>,
7649        _: Arc<Client>,
7650        mut cx: AsyncAppContext,
7651    ) -> Result<proto::GetProjectSymbolsResponse> {
7652        let symbols = this
7653            .update(&mut cx, |this, cx| {
7654                this.symbols(&envelope.payload.query, cx)
7655            })
7656            .await?;
7657
7658        Ok(proto::GetProjectSymbolsResponse {
7659            symbols: symbols.iter().map(serialize_symbol).collect(),
7660        })
7661    }
7662
7663    async fn handle_search_project(
7664        this: ModelHandle<Self>,
7665        envelope: TypedEnvelope<proto::SearchProject>,
7666        _: Arc<Client>,
7667        mut cx: AsyncAppContext,
7668    ) -> Result<proto::SearchProjectResponse> {
7669        let peer_id = envelope.original_sender_id()?;
7670        let query = SearchQuery::from_proto(envelope.payload)?;
7671        let mut result = this.update(&mut cx, |this, cx| this.search(query, cx));
7672
7673        cx.spawn(|mut cx| async move {
7674            let mut locations = Vec::new();
7675            while let Some((buffer, ranges)) = result.next().await {
7676                for range in ranges {
7677                    let start = serialize_anchor(&range.start);
7678                    let end = serialize_anchor(&range.end);
7679                    let buffer_id = this.update(&mut cx, |this, cx| {
7680                        this.create_buffer_for_peer(&buffer, peer_id, cx)
7681                    });
7682                    locations.push(proto::Location {
7683                        buffer_id,
7684                        start: Some(start),
7685                        end: Some(end),
7686                    });
7687                }
7688            }
7689            Ok(proto::SearchProjectResponse { locations })
7690        })
7691        .await
7692    }
7693
7694    async fn handle_open_buffer_for_symbol(
7695        this: ModelHandle<Self>,
7696        envelope: TypedEnvelope<proto::OpenBufferForSymbol>,
7697        _: Arc<Client>,
7698        mut cx: AsyncAppContext,
7699    ) -> Result<proto::OpenBufferForSymbolResponse> {
7700        let peer_id = envelope.original_sender_id()?;
7701        let symbol = envelope
7702            .payload
7703            .symbol
7704            .ok_or_else(|| anyhow!("invalid symbol"))?;
7705        let symbol = this
7706            .read_with(&cx, |this, _| this.deserialize_symbol(symbol))
7707            .await?;
7708        let symbol = this.read_with(&cx, |this, _| {
7709            let signature = this.symbol_signature(&symbol.path);
7710            if signature == symbol.signature {
7711                Ok(symbol)
7712            } else {
7713                Err(anyhow!("invalid symbol signature"))
7714            }
7715        })?;
7716        let buffer = this
7717            .update(&mut cx, |this, cx| this.open_buffer_for_symbol(&symbol, cx))
7718            .await?;
7719
7720        Ok(proto::OpenBufferForSymbolResponse {
7721            buffer_id: this.update(&mut cx, |this, cx| {
7722                this.create_buffer_for_peer(&buffer, peer_id, cx)
7723            }),
7724        })
7725    }
7726
7727    fn symbol_signature(&self, project_path: &ProjectPath) -> [u8; 32] {
7728        let mut hasher = Sha256::new();
7729        hasher.update(project_path.worktree_id.to_proto().to_be_bytes());
7730        hasher.update(project_path.path.to_string_lossy().as_bytes());
7731        hasher.update(self.nonce.to_be_bytes());
7732        hasher.finalize().as_slice().try_into().unwrap()
7733    }
7734
7735    async fn handle_open_buffer_by_id(
7736        this: ModelHandle<Self>,
7737        envelope: TypedEnvelope<proto::OpenBufferById>,
7738        _: Arc<Client>,
7739        mut cx: AsyncAppContext,
7740    ) -> Result<proto::OpenBufferResponse> {
7741        let peer_id = envelope.original_sender_id()?;
7742        let buffer = this
7743            .update(&mut cx, |this, cx| {
7744                this.open_buffer_by_id(envelope.payload.id, cx)
7745            })
7746            .await?;
7747        this.update(&mut cx, |this, cx| {
7748            Ok(proto::OpenBufferResponse {
7749                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
7750            })
7751        })
7752    }
7753
7754    async fn handle_open_buffer_by_path(
7755        this: ModelHandle<Self>,
7756        envelope: TypedEnvelope<proto::OpenBufferByPath>,
7757        _: Arc<Client>,
7758        mut cx: AsyncAppContext,
7759    ) -> Result<proto::OpenBufferResponse> {
7760        let peer_id = envelope.original_sender_id()?;
7761        let worktree_id = WorktreeId::from_proto(envelope.payload.worktree_id);
7762        let open_buffer = this.update(&mut cx, |this, cx| {
7763            this.open_buffer(
7764                ProjectPath {
7765                    worktree_id,
7766                    path: PathBuf::from(envelope.payload.path).into(),
7767                },
7768                cx,
7769            )
7770        });
7771
7772        let buffer = open_buffer.await?;
7773        this.update(&mut cx, |this, cx| {
7774            Ok(proto::OpenBufferResponse {
7775                buffer_id: this.create_buffer_for_peer(&buffer, peer_id, cx),
7776            })
7777        })
7778    }
7779
7780    fn serialize_project_transaction_for_peer(
7781        &mut self,
7782        project_transaction: ProjectTransaction,
7783        peer_id: proto::PeerId,
7784        cx: &mut AppContext,
7785    ) -> proto::ProjectTransaction {
7786        let mut serialized_transaction = proto::ProjectTransaction {
7787            buffer_ids: Default::default(),
7788            transactions: Default::default(),
7789        };
7790        for (buffer, transaction) in project_transaction.0 {
7791            serialized_transaction
7792                .buffer_ids
7793                .push(self.create_buffer_for_peer(&buffer, peer_id, cx));
7794            serialized_transaction
7795                .transactions
7796                .push(language::proto::serialize_transaction(&transaction));
7797        }
7798        serialized_transaction
7799    }
7800
7801    fn deserialize_project_transaction(
7802        &mut self,
7803        message: proto::ProjectTransaction,
7804        push_to_history: bool,
7805        cx: &mut ModelContext<Self>,
7806    ) -> Task<Result<ProjectTransaction>> {
7807        cx.spawn(|this, mut cx| async move {
7808            let mut project_transaction = ProjectTransaction::default();
7809            for (buffer_id, transaction) in message.buffer_ids.into_iter().zip(message.transactions)
7810            {
7811                let buffer = this
7812                    .update(&mut cx, |this, cx| {
7813                        this.wait_for_remote_buffer(buffer_id, cx)
7814                    })
7815                    .await?;
7816                let transaction = language::proto::deserialize_transaction(transaction)?;
7817                project_transaction.0.insert(buffer, transaction);
7818            }
7819
7820            for (buffer, transaction) in &project_transaction.0 {
7821                buffer
7822                    .update(&mut cx, |buffer, _| {
7823                        buffer.wait_for_edits(transaction.edit_ids.iter().copied())
7824                    })
7825                    .await?;
7826
7827                if push_to_history {
7828                    buffer.update(&mut cx, |buffer, _| {
7829                        buffer.push_transaction(transaction.clone(), Instant::now());
7830                    });
7831                }
7832            }
7833
7834            Ok(project_transaction)
7835        })
7836    }
7837
7838    fn create_buffer_for_peer(
7839        &mut self,
7840        buffer: &ModelHandle<Buffer>,
7841        peer_id: proto::PeerId,
7842        cx: &mut AppContext,
7843    ) -> u64 {
7844        let buffer_id = buffer.read(cx).remote_id();
7845        if let Some(ProjectClientState::Local { updates_tx, .. }) = &self.client_state {
7846            updates_tx
7847                .unbounded_send(LocalProjectUpdate::CreateBufferForPeer { peer_id, buffer_id })
7848                .ok();
7849        }
7850        buffer_id
7851    }
7852
7853    fn wait_for_remote_buffer(
7854        &mut self,
7855        id: u64,
7856        cx: &mut ModelContext<Self>,
7857    ) -> Task<Result<ModelHandle<Buffer>>> {
7858        let mut opened_buffer_rx = self.opened_buffer.1.clone();
7859
7860        cx.spawn_weak(|this, mut cx| async move {
7861            let buffer = loop {
7862                let Some(this) = this.upgrade(&cx) else {
7863                    return Err(anyhow!("project dropped"));
7864                };
7865
7866                let buffer = this.read_with(&cx, |this, cx| {
7867                    this.opened_buffers
7868                        .get(&id)
7869                        .and_then(|buffer| buffer.upgrade(cx))
7870                });
7871
7872                if let Some(buffer) = buffer {
7873                    break buffer;
7874                } else if this.read_with(&cx, |this, _| this.is_read_only()) {
7875                    return Err(anyhow!("disconnected before buffer {} could be opened", id));
7876                }
7877
7878                this.update(&mut cx, |this, _| {
7879                    this.incomplete_remote_buffers.entry(id).or_default();
7880                });
7881                drop(this);
7882
7883                opened_buffer_rx
7884                    .next()
7885                    .await
7886                    .ok_or_else(|| anyhow!("project dropped while waiting for buffer"))?;
7887            };
7888
7889            Ok(buffer)
7890        })
7891    }
7892
7893    fn synchronize_remote_buffers(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
7894        let project_id = match self.client_state.as_ref() {
7895            Some(ProjectClientState::Remote {
7896                sharing_has_stopped,
7897                remote_id,
7898                ..
7899            }) => {
7900                if *sharing_has_stopped {
7901                    return Task::ready(Err(anyhow!(
7902                        "can't synchronize remote buffers on a readonly project"
7903                    )));
7904                } else {
7905                    *remote_id
7906                }
7907            }
7908            Some(ProjectClientState::Local { .. }) | None => {
7909                return Task::ready(Err(anyhow!(
7910                    "can't synchronize remote buffers on a local project"
7911                )))
7912            }
7913        };
7914
7915        let client = self.client.clone();
7916        cx.spawn(|this, cx| async move {
7917            let (buffers, incomplete_buffer_ids) = this.read_with(&cx, |this, cx| {
7918                let buffers = this
7919                    .opened_buffers
7920                    .iter()
7921                    .filter_map(|(id, buffer)| {
7922                        let buffer = buffer.upgrade(cx)?;
7923                        Some(proto::BufferVersion {
7924                            id: *id,
7925                            version: language::proto::serialize_version(&buffer.read(cx).version),
7926                        })
7927                    })
7928                    .collect();
7929                let incomplete_buffer_ids = this
7930                    .incomplete_remote_buffers
7931                    .keys()
7932                    .copied()
7933                    .collect::<Vec<_>>();
7934
7935                (buffers, incomplete_buffer_ids)
7936            });
7937            let response = client
7938                .request(proto::SynchronizeBuffers {
7939                    project_id,
7940                    buffers,
7941                })
7942                .await?;
7943
7944            let send_updates_for_buffers = response.buffers.into_iter().map(|buffer| {
7945                let client = client.clone();
7946                let buffer_id = buffer.id;
7947                let remote_version = language::proto::deserialize_version(&buffer.version);
7948                this.read_with(&cx, |this, cx| {
7949                    if let Some(buffer) = this.buffer_for_id(buffer_id, cx) {
7950                        let operations = buffer.read(cx).serialize_ops(Some(remote_version), cx);
7951                        cx.background().spawn(async move {
7952                            let operations = operations.await;
7953                            for chunk in split_operations(operations) {
7954                                client
7955                                    .request(proto::UpdateBuffer {
7956                                        project_id,
7957                                        buffer_id,
7958                                        operations: chunk,
7959                                    })
7960                                    .await?;
7961                            }
7962                            anyhow::Ok(())
7963                        })
7964                    } else {
7965                        Task::ready(Ok(()))
7966                    }
7967                })
7968            });
7969
7970            // Any incomplete buffers have open requests waiting. Request that the host sends
7971            // creates these buffers for us again to unblock any waiting futures.
7972            for id in incomplete_buffer_ids {
7973                cx.background()
7974                    .spawn(client.request(proto::OpenBufferById { project_id, id }))
7975                    .detach();
7976            }
7977
7978            futures::future::join_all(send_updates_for_buffers)
7979                .await
7980                .into_iter()
7981                .collect()
7982        })
7983    }
7984
7985    pub fn worktree_metadata_protos(&self, cx: &AppContext) -> Vec<proto::WorktreeMetadata> {
7986        self.worktrees(cx)
7987            .map(|worktree| {
7988                let worktree = worktree.read(cx);
7989                proto::WorktreeMetadata {
7990                    id: worktree.id().to_proto(),
7991                    root_name: worktree.root_name().into(),
7992                    visible: worktree.is_visible(),
7993                    abs_path: worktree.abs_path().to_string_lossy().into(),
7994                }
7995            })
7996            .collect()
7997    }
7998
7999    fn set_worktrees_from_proto(
8000        &mut self,
8001        worktrees: Vec<proto::WorktreeMetadata>,
8002        cx: &mut ModelContext<Project>,
8003    ) -> Result<()> {
8004        let replica_id = self.replica_id();
8005        let remote_id = self.remote_id().ok_or_else(|| anyhow!("invalid project"))?;
8006
8007        let mut old_worktrees_by_id = self
8008            .worktrees
8009            .drain(..)
8010            .filter_map(|worktree| {
8011                let worktree = worktree.upgrade(cx)?;
8012                Some((worktree.read(cx).id(), worktree))
8013            })
8014            .collect::<HashMap<_, _>>();
8015
8016        for worktree in worktrees {
8017            if let Some(old_worktree) =
8018                old_worktrees_by_id.remove(&WorktreeId::from_proto(worktree.id))
8019            {
8020                self.worktrees.push(WorktreeHandle::Strong(old_worktree));
8021            } else {
8022                let worktree =
8023                    Worktree::remote(remote_id, replica_id, worktree, self.client.clone(), cx);
8024                let _ = self.add_worktree(&worktree, cx);
8025            }
8026        }
8027
8028        self.metadata_changed(cx);
8029        for id in old_worktrees_by_id.keys() {
8030            cx.emit(Event::WorktreeRemoved(*id));
8031        }
8032
8033        Ok(())
8034    }
8035
8036    fn set_collaborators_from_proto(
8037        &mut self,
8038        messages: Vec<proto::Collaborator>,
8039        cx: &mut ModelContext<Self>,
8040    ) -> Result<()> {
8041        let mut collaborators = HashMap::default();
8042        for message in messages {
8043            let collaborator = Collaborator::from_proto(message)?;
8044            collaborators.insert(collaborator.peer_id, collaborator);
8045        }
8046        for old_peer_id in self.collaborators.keys() {
8047            if !collaborators.contains_key(old_peer_id) {
8048                cx.emit(Event::CollaboratorLeft(*old_peer_id));
8049            }
8050        }
8051        self.collaborators = collaborators;
8052        Ok(())
8053    }
8054
8055    fn deserialize_symbol(
8056        &self,
8057        serialized_symbol: proto::Symbol,
8058    ) -> impl Future<Output = Result<Symbol>> {
8059        let languages = self.languages.clone();
8060        async move {
8061            let source_worktree_id = WorktreeId::from_proto(serialized_symbol.source_worktree_id);
8062            let worktree_id = WorktreeId::from_proto(serialized_symbol.worktree_id);
8063            let start = serialized_symbol
8064                .start
8065                .ok_or_else(|| anyhow!("invalid start"))?;
8066            let end = serialized_symbol
8067                .end
8068                .ok_or_else(|| anyhow!("invalid end"))?;
8069            let kind = unsafe { mem::transmute(serialized_symbol.kind) };
8070            let path = ProjectPath {
8071                worktree_id,
8072                path: PathBuf::from(serialized_symbol.path).into(),
8073            };
8074            let language = languages
8075                .language_for_file(&path.path, None)
8076                .await
8077                .log_err();
8078            Ok(Symbol {
8079                language_server_name: LanguageServerName(
8080                    serialized_symbol.language_server_name.into(),
8081                ),
8082                source_worktree_id,
8083                path,
8084                label: {
8085                    match language {
8086                        Some(language) => {
8087                            language
8088                                .label_for_symbol(&serialized_symbol.name, kind)
8089                                .await
8090                        }
8091                        None => None,
8092                    }
8093                    .unwrap_or_else(|| CodeLabel::plain(serialized_symbol.name.clone(), None))
8094                },
8095
8096                name: serialized_symbol.name,
8097                range: Unclipped(PointUtf16::new(start.row, start.column))
8098                    ..Unclipped(PointUtf16::new(end.row, end.column)),
8099                kind,
8100                signature: serialized_symbol
8101                    .signature
8102                    .try_into()
8103                    .map_err(|_| anyhow!("invalid signature"))?,
8104            })
8105        }
8106    }
8107
8108    async fn handle_buffer_saved(
8109        this: ModelHandle<Self>,
8110        envelope: TypedEnvelope<proto::BufferSaved>,
8111        _: Arc<Client>,
8112        mut cx: AsyncAppContext,
8113    ) -> Result<()> {
8114        let fingerprint = deserialize_fingerprint(&envelope.payload.fingerprint)?;
8115        let version = deserialize_version(&envelope.payload.version);
8116        let mtime = envelope
8117            .payload
8118            .mtime
8119            .ok_or_else(|| anyhow!("missing mtime"))?
8120            .into();
8121
8122        this.update(&mut cx, |this, cx| {
8123            let buffer = this
8124                .opened_buffers
8125                .get(&envelope.payload.buffer_id)
8126                .and_then(|buffer| buffer.upgrade(cx))
8127                .or_else(|| {
8128                    this.incomplete_remote_buffers
8129                        .get(&envelope.payload.buffer_id)
8130                        .and_then(|b| b.clone())
8131                });
8132            if let Some(buffer) = buffer {
8133                buffer.update(cx, |buffer, cx| {
8134                    buffer.did_save(version, fingerprint, mtime, cx);
8135                });
8136            }
8137            Ok(())
8138        })
8139    }
8140
8141    async fn handle_buffer_reloaded(
8142        this: ModelHandle<Self>,
8143        envelope: TypedEnvelope<proto::BufferReloaded>,
8144        _: Arc<Client>,
8145        mut cx: AsyncAppContext,
8146    ) -> Result<()> {
8147        let payload = envelope.payload;
8148        let version = deserialize_version(&payload.version);
8149        let fingerprint = deserialize_fingerprint(&payload.fingerprint)?;
8150        let line_ending = deserialize_line_ending(
8151            proto::LineEnding::from_i32(payload.line_ending)
8152                .ok_or_else(|| anyhow!("missing line ending"))?,
8153        );
8154        let mtime = payload
8155            .mtime
8156            .ok_or_else(|| anyhow!("missing mtime"))?
8157            .into();
8158        this.update(&mut cx, |this, cx| {
8159            let buffer = this
8160                .opened_buffers
8161                .get(&payload.buffer_id)
8162                .and_then(|buffer| buffer.upgrade(cx))
8163                .or_else(|| {
8164                    this.incomplete_remote_buffers
8165                        .get(&payload.buffer_id)
8166                        .cloned()
8167                        .flatten()
8168                });
8169            if let Some(buffer) = buffer {
8170                buffer.update(cx, |buffer, cx| {
8171                    buffer.did_reload(version, fingerprint, line_ending, mtime, cx);
8172                });
8173            }
8174            Ok(())
8175        })
8176    }
8177
8178    #[allow(clippy::type_complexity)]
8179    fn edits_from_lsp(
8180        &mut self,
8181        buffer: &ModelHandle<Buffer>,
8182        lsp_edits: impl 'static + Send + IntoIterator<Item = lsp::TextEdit>,
8183        server_id: LanguageServerId,
8184        version: Option<i32>,
8185        cx: &mut ModelContext<Self>,
8186    ) -> Task<Result<Vec<(Range<Anchor>, String)>>> {
8187        let snapshot = self.buffer_snapshot_for_lsp_version(buffer, server_id, version, cx);
8188        cx.background().spawn(async move {
8189            let snapshot = snapshot?;
8190            let mut lsp_edits = lsp_edits
8191                .into_iter()
8192                .map(|edit| (range_from_lsp(edit.range), edit.new_text))
8193                .collect::<Vec<_>>();
8194            lsp_edits.sort_by_key(|(range, _)| range.start);
8195
8196            let mut lsp_edits = lsp_edits.into_iter().peekable();
8197            let mut edits = Vec::new();
8198            while let Some((range, mut new_text)) = lsp_edits.next() {
8199                // Clip invalid ranges provided by the language server.
8200                let mut range = snapshot.clip_point_utf16(range.start, Bias::Left)
8201                    ..snapshot.clip_point_utf16(range.end, Bias::Left);
8202
8203                // Combine any LSP edits that are adjacent.
8204                //
8205                // Also, combine LSP edits that are separated from each other by only
8206                // a newline. This is important because for some code actions,
8207                // Rust-analyzer rewrites the entire buffer via a series of edits that
8208                // are separated by unchanged newline characters.
8209                //
8210                // In order for the diffing logic below to work properly, any edits that
8211                // cancel each other out must be combined into one.
8212                while let Some((next_range, next_text)) = lsp_edits.peek() {
8213                    if next_range.start.0 > range.end {
8214                        if next_range.start.0.row > range.end.row + 1
8215                            || next_range.start.0.column > 0
8216                            || snapshot.clip_point_utf16(
8217                                Unclipped(PointUtf16::new(range.end.row, u32::MAX)),
8218                                Bias::Left,
8219                            ) > range.end
8220                        {
8221                            break;
8222                        }
8223                        new_text.push('\n');
8224                    }
8225                    range.end = snapshot.clip_point_utf16(next_range.end, Bias::Left);
8226                    new_text.push_str(next_text);
8227                    lsp_edits.next();
8228                }
8229
8230                // For multiline edits, perform a diff of the old and new text so that
8231                // we can identify the changes more precisely, preserving the locations
8232                // of any anchors positioned in the unchanged regions.
8233                if range.end.row > range.start.row {
8234                    let mut offset = range.start.to_offset(&snapshot);
8235                    let old_text = snapshot.text_for_range(range).collect::<String>();
8236
8237                    let diff = TextDiff::from_lines(old_text.as_str(), &new_text);
8238                    let mut moved_since_edit = true;
8239                    for change in diff.iter_all_changes() {
8240                        let tag = change.tag();
8241                        let value = change.value();
8242                        match tag {
8243                            ChangeTag::Equal => {
8244                                offset += value.len();
8245                                moved_since_edit = true;
8246                            }
8247                            ChangeTag::Delete => {
8248                                let start = snapshot.anchor_after(offset);
8249                                let end = snapshot.anchor_before(offset + value.len());
8250                                if moved_since_edit {
8251                                    edits.push((start..end, String::new()));
8252                                } else {
8253                                    edits.last_mut().unwrap().0.end = end;
8254                                }
8255                                offset += value.len();
8256                                moved_since_edit = false;
8257                            }
8258                            ChangeTag::Insert => {
8259                                if moved_since_edit {
8260                                    let anchor = snapshot.anchor_after(offset);
8261                                    edits.push((anchor..anchor, value.to_string()));
8262                                } else {
8263                                    edits.last_mut().unwrap().1.push_str(value);
8264                                }
8265                                moved_since_edit = false;
8266                            }
8267                        }
8268                    }
8269                } else if range.end == range.start {
8270                    let anchor = snapshot.anchor_after(range.start);
8271                    edits.push((anchor..anchor, new_text));
8272                } else {
8273                    let edit_start = snapshot.anchor_after(range.start);
8274                    let edit_end = snapshot.anchor_before(range.end);
8275                    edits.push((edit_start..edit_end, new_text));
8276                }
8277            }
8278
8279            Ok(edits)
8280        })
8281    }
8282
8283    fn buffer_snapshot_for_lsp_version(
8284        &mut self,
8285        buffer: &ModelHandle<Buffer>,
8286        server_id: LanguageServerId,
8287        version: Option<i32>,
8288        cx: &AppContext,
8289    ) -> Result<TextBufferSnapshot> {
8290        const OLD_VERSIONS_TO_RETAIN: i32 = 10;
8291
8292        if let Some(version) = version {
8293            let buffer_id = buffer.read(cx).remote_id();
8294            let snapshots = self
8295                .buffer_snapshots
8296                .get_mut(&buffer_id)
8297                .and_then(|m| m.get_mut(&server_id))
8298                .ok_or_else(|| {
8299                    anyhow!("no snapshots found for buffer {buffer_id} and server {server_id}")
8300                })?;
8301
8302            let found_snapshot = snapshots
8303                .binary_search_by_key(&version, |e| e.version)
8304                .map(|ix| snapshots[ix].snapshot.clone())
8305                .map_err(|_| {
8306                    anyhow!("snapshot not found for buffer {buffer_id} server {server_id} at version {version}")
8307                })?;
8308
8309            snapshots.retain(|snapshot| snapshot.version + OLD_VERSIONS_TO_RETAIN >= version);
8310            Ok(found_snapshot)
8311        } else {
8312            Ok((buffer.read(cx)).text_snapshot())
8313        }
8314    }
8315
8316    pub fn language_servers(
8317        &self,
8318    ) -> impl '_ + Iterator<Item = (LanguageServerId, LanguageServerName, WorktreeId)> {
8319        self.language_server_ids
8320            .iter()
8321            .map(|((worktree_id, server_name), server_id)| {
8322                (*server_id, server_name.clone(), *worktree_id)
8323            })
8324    }
8325
8326    pub fn supplementary_language_servers(
8327        &self,
8328    ) -> impl '_
8329           + Iterator<
8330        Item = (
8331            &LanguageServerId,
8332            &(LanguageServerName, Arc<LanguageServer>),
8333        ),
8334    > {
8335        self.supplementary_language_servers.iter()
8336    }
8337
8338    pub fn language_server_for_id(&self, id: LanguageServerId) -> Option<Arc<LanguageServer>> {
8339        if let Some(LanguageServerState::Running { server, .. }) = self.language_servers.get(&id) {
8340            Some(server.clone())
8341        } else if let Some((_, server)) = self.supplementary_language_servers.get(&id) {
8342            Some(Arc::clone(server))
8343        } else {
8344            None
8345        }
8346    }
8347
8348    pub fn language_servers_for_buffer(
8349        &self,
8350        buffer: &Buffer,
8351        cx: &AppContext,
8352    ) -> impl Iterator<Item = (&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8353        self.language_server_ids_for_buffer(buffer, cx)
8354            .into_iter()
8355            .filter_map(|server_id| match self.language_servers.get(&server_id)? {
8356                LanguageServerState::Running {
8357                    adapter, server, ..
8358                } => Some((adapter, server)),
8359                _ => None,
8360            })
8361    }
8362
8363    fn primary_language_server_for_buffer(
8364        &self,
8365        buffer: &Buffer,
8366        cx: &AppContext,
8367    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8368        self.language_servers_for_buffer(buffer, cx).next()
8369    }
8370
8371    pub fn language_server_for_buffer(
8372        &self,
8373        buffer: &Buffer,
8374        server_id: LanguageServerId,
8375        cx: &AppContext,
8376    ) -> Option<(&Arc<CachedLspAdapter>, &Arc<LanguageServer>)> {
8377        self.language_servers_for_buffer(buffer, cx)
8378            .find(|(_, s)| s.server_id() == server_id)
8379    }
8380
8381    fn language_server_ids_for_buffer(
8382        &self,
8383        buffer: &Buffer,
8384        cx: &AppContext,
8385    ) -> Vec<LanguageServerId> {
8386        if let Some((file, language)) = File::from_dyn(buffer.file()).zip(buffer.language()) {
8387            let worktree_id = file.worktree_id(cx);
8388            language
8389                .lsp_adapters()
8390                .iter()
8391                .flat_map(|adapter| {
8392                    let key = (worktree_id, adapter.name.clone());
8393                    self.language_server_ids.get(&key).copied()
8394                })
8395                .collect()
8396        } else {
8397            Vec::new()
8398        }
8399    }
8400
8401    fn prettier_instance_for_buffer(
8402        &mut self,
8403        buffer: &ModelHandle<Buffer>,
8404        cx: &mut ModelContext<Self>,
8405    ) -> Task<
8406        Option<(
8407            Option<PathBuf>,
8408            Shared<Task<Result<Arc<Prettier>, Arc<anyhow::Error>>>>,
8409        )>,
8410    > {
8411        let buffer = buffer.read(cx);
8412        let buffer_file = buffer.file();
8413        let Some(buffer_language) = buffer.language() else {
8414            return Task::ready(None);
8415        };
8416        if buffer_language.prettier_parser_name().is_none() {
8417            return Task::ready(None);
8418        }
8419
8420        if self.is_local() {
8421            let Some(node) = self.node.as_ref().map(Arc::clone) else {
8422                return Task::ready(None);
8423            };
8424            match File::from_dyn(buffer_file).map(|file| (file.worktree_id(cx), file.abs_path(cx)))
8425            {
8426                Some((worktree_id, buffer_path)) => {
8427                    let fs = Arc::clone(&self.fs);
8428                    let installed_prettiers = self.prettier_instances.keys().cloned().collect();
8429                    return cx.spawn(|project, mut cx| async move {
8430                        match cx
8431                            .background()
8432                            .spawn(async move {
8433                                Prettier::locate_prettier_installation(
8434                                    fs.as_ref(),
8435                                    &installed_prettiers,
8436                                    &buffer_path,
8437                                )
8438                                .await
8439                            })
8440                            .await
8441                        {
8442                            Ok(None) => {
8443                                let started_default_prettier =
8444                                    project.update(&mut cx, |project, _| {
8445                                        project
8446                                            .prettiers_per_worktree
8447                                            .entry(worktree_id)
8448                                            .or_default()
8449                                            .insert(None);
8450                                        project.default_prettier.as_ref().and_then(
8451                                            |default_prettier| default_prettier.instance.clone(),
8452                                        )
8453                                    });
8454                                match started_default_prettier {
8455                                    Some(old_task) => return Some((None, old_task)),
8456                                    None => {
8457                                        let new_task = project.update(&mut cx, |project, cx| {
8458                                            let new_task = start_prettier(
8459                                                node,
8460                                                DEFAULT_PRETTIER_DIR.clone(),
8461                                                Some(worktree_id),
8462                                                cx,
8463                                            );
8464                                            project
8465                                                .default_prettier
8466                                                .get_or_insert_with(|| DefaultPrettier {
8467                                                    instance: None,
8468                                                    #[cfg(not(any(
8469                                                        test,
8470                                                        feature = "test-support"
8471                                                    )))]
8472                                                    installed_plugins: HashSet::default(),
8473                                                })
8474                                                .instance = Some(new_task.clone());
8475                                            new_task
8476                                        });
8477                                        return Some((None, new_task));
8478                                    }
8479                                }
8480                            }
8481                            Ok(Some(prettier_dir)) => {
8482                                project.update(&mut cx, |project, _| {
8483                                    project
8484                                        .prettiers_per_worktree
8485                                        .entry(worktree_id)
8486                                        .or_default()
8487                                        .insert(Some(prettier_dir.clone()))
8488                                });
8489                                if let Some(existing_prettier) =
8490                                    project.update(&mut cx, |project, _| {
8491                                        project.prettier_instances.get(&prettier_dir).cloned()
8492                                    })
8493                                {
8494                                    log::debug!(
8495                                        "Found already started prettier in {prettier_dir:?}"
8496                                    );
8497                                    return Some((Some(prettier_dir), existing_prettier));
8498                                }
8499
8500                                log::info!("Found prettier in {prettier_dir:?}, starting.");
8501                                let new_prettier_task = project.update(&mut cx, |project, cx| {
8502                                    let new_prettier_task = start_prettier(
8503                                        node,
8504                                        prettier_dir.clone(),
8505                                        Some(worktree_id),
8506                                        cx,
8507                                    );
8508                                    project
8509                                        .prettier_instances
8510                                        .insert(prettier_dir.clone(), new_prettier_task.clone());
8511                                    new_prettier_task
8512                                });
8513                                Some((Some(prettier_dir), new_prettier_task))
8514                            }
8515                            Err(e) => {
8516                                return Some((
8517                                    None,
8518                                    Task::ready(Err(Arc::new(
8519                                        e.context("determining prettier path"),
8520                                    )))
8521                                    .shared(),
8522                                ));
8523                            }
8524                        }
8525                    });
8526                }
8527                None => {
8528                    let started_default_prettier = self
8529                        .default_prettier
8530                        .as_ref()
8531                        .and_then(|default_prettier| default_prettier.instance.clone());
8532                    match started_default_prettier {
8533                        Some(old_task) => return Task::ready(Some((None, old_task))),
8534                        None => {
8535                            let new_task =
8536                                start_prettier(node, DEFAULT_PRETTIER_DIR.clone(), None, cx);
8537                            self.default_prettier
8538                                .get_or_insert_with(|| DefaultPrettier {
8539                                    instance: None,
8540                                    #[cfg(not(any(test, feature = "test-support")))]
8541                                    installed_plugins: HashSet::default(),
8542                                })
8543                                .instance = Some(new_task.clone());
8544                            return Task::ready(Some((None, new_task)));
8545                        }
8546                    }
8547                }
8548            }
8549        } else if self.remote_id().is_some() {
8550            return Task::ready(None);
8551        } else {
8552            Task::ready(Some((
8553                None,
8554                Task::ready(Err(Arc::new(anyhow!("project does not have a remote id")))).shared(),
8555            )))
8556        }
8557    }
8558
8559    #[cfg(any(test, feature = "test-support"))]
8560    fn install_default_formatters(
8561        &mut self,
8562        _worktree: Option<WorktreeId>,
8563        _new_language: &Language,
8564        _language_settings: &LanguageSettings,
8565        _cx: &mut ModelContext<Self>,
8566    ) -> Task<anyhow::Result<()>> {
8567        return Task::ready(Ok(()));
8568    }
8569
8570    #[cfg(not(any(test, feature = "test-support")))]
8571    fn install_default_formatters(
8572        &mut self,
8573        worktree: Option<WorktreeId>,
8574        new_language: &Language,
8575        language_settings: &LanguageSettings,
8576        cx: &mut ModelContext<Self>,
8577    ) -> Task<anyhow::Result<()>> {
8578        match &language_settings.formatter {
8579            Formatter::Prettier { .. } | Formatter::Auto => {}
8580            Formatter::LanguageServer | Formatter::External { .. } => return Task::ready(Ok(())),
8581        };
8582        let Some(node) = self.node.as_ref().cloned() else {
8583            return Task::ready(Ok(()));
8584        };
8585
8586        let mut prettier_plugins = None;
8587        if new_language.prettier_parser_name().is_some() {
8588            prettier_plugins
8589                .get_or_insert_with(|| HashSet::<&'static str>::default())
8590                .extend(
8591                    new_language
8592                        .lsp_adapters()
8593                        .iter()
8594                        .flat_map(|adapter| adapter.prettier_plugins()),
8595                )
8596        }
8597        let Some(prettier_plugins) = prettier_plugins else {
8598            return Task::ready(Ok(()));
8599        };
8600
8601        let fs = Arc::clone(&self.fs);
8602        let locate_prettier_installation = match worktree.and_then(|worktree_id| {
8603            self.worktree_for_id(worktree_id, cx)
8604                .map(|worktree| worktree.read(cx).abs_path())
8605        }) {
8606            Some(locate_from) => {
8607                let installed_prettiers = self.prettier_instances.keys().cloned().collect();
8608                cx.background().spawn(async move {
8609                    Prettier::locate_prettier_installation(
8610                        fs.as_ref(),
8611                        &installed_prettiers,
8612                        locate_from.as_ref(),
8613                    )
8614                    .await
8615                })
8616            }
8617            None => Task::ready(Ok(None)),
8618        };
8619        let mut plugins_to_install = prettier_plugins;
8620        let previous_installation_process =
8621            if let Some(default_prettier) = &mut self.default_prettier {
8622                plugins_to_install
8623                    .retain(|plugin| !default_prettier.installed_plugins.contains(plugin));
8624                if plugins_to_install.is_empty() {
8625                    return Task::ready(Ok(()));
8626                }
8627                default_prettier.instance.clone()
8628            } else {
8629                None
8630            };
8631        let fs = Arc::clone(&self.fs);
8632        cx.spawn(|this, mut cx| async move {
8633            match locate_prettier_installation
8634                .await
8635                .context("locate prettier installation")?
8636            {
8637                Some(_non_default_prettier) => return Ok(()),
8638                None => {
8639                    let mut needs_restart = match previous_installation_process {
8640                        Some(previous_installation_process) => {
8641                            previous_installation_process.await.is_err()
8642                        }
8643                        None => true,
8644                    };
8645                    this.update(&mut cx, |this, _| {
8646                        if let Some(default_prettier) = &mut this.default_prettier {
8647                            plugins_to_install.retain(|plugin| {
8648                                !default_prettier.installed_plugins.contains(plugin)
8649                            });
8650                            needs_restart |= !plugins_to_install.is_empty();
8651                        }
8652                    });
8653                    if needs_restart {
8654                        let installed_plugins = plugins_to_install.clone();
8655                        cx.background()
8656                            .spawn(async move {
8657                                install_default_prettier(plugins_to_install, node, fs).await
8658                            })
8659                            .await
8660                            .context("prettier & plugins install")?;
8661                        this.update(&mut cx, |this, _| {
8662                            let default_prettier =
8663                                this.default_prettier
8664                                    .get_or_insert_with(|| DefaultPrettier {
8665                                        instance: None,
8666                                        installed_plugins: HashSet::default(),
8667                                    });
8668                            default_prettier.instance = None;
8669                            default_prettier.installed_plugins.extend(installed_plugins);
8670                        });
8671                    }
8672                }
8673            }
8674            Ok(())
8675        })
8676    }
8677}
8678
8679fn start_prettier(
8680    node: Arc<dyn NodeRuntime>,
8681    prettier_dir: PathBuf,
8682    worktree_id: Option<WorktreeId>,
8683    cx: &mut ModelContext<'_, Project>,
8684) -> Shared<Task<Result<Arc<Prettier>, Arc<anyhow::Error>>>> {
8685    cx.spawn(|project, mut cx| async move {
8686        let new_server_id = project.update(&mut cx, |project, _| {
8687            project.languages.next_language_server_id()
8688        });
8689        let new_prettier = Prettier::start(new_server_id, prettier_dir, node, cx.clone())
8690            .await
8691            .context("default prettier spawn")
8692            .map(Arc::new)
8693            .map_err(Arc::new)?;
8694        register_new_prettier(&project, &new_prettier, worktree_id, new_server_id, &mut cx);
8695        Ok(new_prettier)
8696    })
8697    .shared()
8698}
8699
8700fn register_new_prettier(
8701    project: &ModelHandle<Project>,
8702    prettier: &Prettier,
8703    worktree_id: Option<WorktreeId>,
8704    new_server_id: LanguageServerId,
8705    cx: &mut AsyncAppContext,
8706) {
8707    let prettier_dir = prettier.prettier_dir();
8708    let is_default = prettier.is_default();
8709    if is_default {
8710        log::info!("Started default prettier in {prettier_dir:?}");
8711    } else {
8712        log::info!("Started prettier in {prettier_dir:?}");
8713    }
8714    if let Some(prettier_server) = prettier.server() {
8715        project.update(cx, |project, cx| {
8716            let name = if is_default {
8717                LanguageServerName(Arc::from("prettier (default)"))
8718            } else {
8719                let worktree_path = worktree_id
8720                    .and_then(|id| project.worktree_for_id(id, cx))
8721                    .map(|worktree| worktree.update(cx, |worktree, _| worktree.abs_path()));
8722                let name = match worktree_path {
8723                    Some(worktree_path) => {
8724                        if prettier_dir == worktree_path.as_ref() {
8725                            let name = prettier_dir
8726                                .file_name()
8727                                .and_then(|name| name.to_str())
8728                                .unwrap_or_default();
8729                            format!("prettier ({name})")
8730                        } else {
8731                            let dir_to_display = prettier_dir
8732                                .strip_prefix(worktree_path.as_ref())
8733                                .ok()
8734                                .unwrap_or(prettier_dir);
8735                            format!("prettier ({})", dir_to_display.display())
8736                        }
8737                    }
8738                    None => format!("prettier ({})", prettier_dir.display()),
8739                };
8740                LanguageServerName(Arc::from(name))
8741            };
8742            project
8743                .supplementary_language_servers
8744                .insert(new_server_id, (name, Arc::clone(prettier_server)));
8745            cx.emit(Event::LanguageServerAdded(new_server_id));
8746        });
8747    }
8748}
8749
8750#[cfg(not(any(test, feature = "test-support")))]
8751async fn install_default_prettier(
8752    plugins_to_install: HashSet<&'static str>,
8753    node: Arc<dyn NodeRuntime>,
8754    fs: Arc<dyn Fs>,
8755) -> anyhow::Result<()> {
8756    let prettier_wrapper_path = DEFAULT_PRETTIER_DIR.join(prettier::PRETTIER_SERVER_FILE);
8757    // method creates parent directory if it doesn't exist
8758    fs.save(
8759        &prettier_wrapper_path,
8760        &text::Rope::from(prettier::PRETTIER_SERVER_JS),
8761        text::LineEnding::Unix,
8762    )
8763    .await
8764    .with_context(|| {
8765        format!(
8766            "writing {} file at {prettier_wrapper_path:?}",
8767            prettier::PRETTIER_SERVER_FILE
8768        )
8769    })?;
8770
8771    let packages_to_versions =
8772        future::try_join_all(plugins_to_install.iter().chain(Some(&"prettier")).map(
8773            |package_name| async {
8774                let returned_package_name = package_name.to_string();
8775                let latest_version = node
8776                    .npm_package_latest_version(package_name)
8777                    .await
8778                    .with_context(|| {
8779                        format!("fetching latest npm version for package {returned_package_name}")
8780                    })?;
8781                anyhow::Ok((returned_package_name, latest_version))
8782            },
8783        ))
8784        .await
8785        .context("fetching latest npm versions")?;
8786
8787    log::info!("Fetching default prettier and plugins: {packages_to_versions:?}");
8788    let borrowed_packages = packages_to_versions
8789        .iter()
8790        .map(|(package, version)| (package.as_str(), version.as_str()))
8791        .collect::<Vec<_>>();
8792    node.npm_install_packages(DEFAULT_PRETTIER_DIR.as_path(), &borrowed_packages)
8793        .await
8794        .context("fetching formatter packages")?;
8795    anyhow::Ok(())
8796}
8797
8798fn subscribe_for_copilot_events(
8799    copilot: &ModelHandle<Copilot>,
8800    cx: &mut ModelContext<'_, Project>,
8801) -> gpui::Subscription {
8802    cx.subscribe(
8803        copilot,
8804        |project, copilot, copilot_event, cx| match copilot_event {
8805            copilot::Event::CopilotLanguageServerStarted => {
8806                match copilot.read(cx).language_server() {
8807                    Some((name, copilot_server)) => {
8808                        // Another event wants to re-add the server that was already added and subscribed to, avoid doing it again.
8809                        if !copilot_server.has_notification_handler::<copilot::request::LogMessage>() {
8810                            let new_server_id = copilot_server.server_id();
8811                            let weak_project = cx.weak_handle();
8812                            let copilot_log_subscription = copilot_server
8813                                .on_notification::<copilot::request::LogMessage, _>(
8814                                    move |params, mut cx| {
8815                                        if let Some(project) = weak_project.upgrade(&mut cx) {
8816                                            project.update(&mut cx, |_, cx| {
8817                                                cx.emit(Event::LanguageServerLog(
8818                                                    new_server_id,
8819                                                    params.message,
8820                                                ));
8821                                            })
8822                                        }
8823                                    },
8824                                );
8825                            project.supplementary_language_servers.insert(new_server_id, (name.clone(), Arc::clone(copilot_server)));
8826                            project.copilot_log_subscription = Some(copilot_log_subscription);
8827                            cx.emit(Event::LanguageServerAdded(new_server_id));
8828                        }
8829                    }
8830                    None => debug_panic!("Received Copilot language server started event, but no language server is running"),
8831                }
8832            }
8833        },
8834    )
8835}
8836
8837fn glob_literal_prefix<'a>(glob: &'a str) -> &'a str {
8838    let mut literal_end = 0;
8839    for (i, part) in glob.split(path::MAIN_SEPARATOR).enumerate() {
8840        if part.contains(&['*', '?', '{', '}']) {
8841            break;
8842        } else {
8843            if i > 0 {
8844                // Acount for separator prior to this part
8845                literal_end += path::MAIN_SEPARATOR.len_utf8();
8846            }
8847            literal_end += part.len();
8848        }
8849    }
8850    &glob[..literal_end]
8851}
8852
8853impl WorktreeHandle {
8854    pub fn upgrade(&self, cx: &AppContext) -> Option<ModelHandle<Worktree>> {
8855        match self {
8856            WorktreeHandle::Strong(handle) => Some(handle.clone()),
8857            WorktreeHandle::Weak(handle) => handle.upgrade(cx),
8858        }
8859    }
8860
8861    pub fn handle_id(&self) -> usize {
8862        match self {
8863            WorktreeHandle::Strong(handle) => handle.id(),
8864            WorktreeHandle::Weak(handle) => handle.id(),
8865        }
8866    }
8867}
8868
8869impl OpenBuffer {
8870    pub fn upgrade(&self, cx: &impl BorrowAppContext) -> Option<ModelHandle<Buffer>> {
8871        match self {
8872            OpenBuffer::Strong(handle) => Some(handle.clone()),
8873            OpenBuffer::Weak(handle) => handle.upgrade(cx),
8874            OpenBuffer::Operations(_) => None,
8875        }
8876    }
8877}
8878
8879pub struct PathMatchCandidateSet {
8880    pub snapshot: Snapshot,
8881    pub include_ignored: bool,
8882    pub include_root_name: bool,
8883}
8884
8885impl<'a> fuzzy::PathMatchCandidateSet<'a> for PathMatchCandidateSet {
8886    type Candidates = PathMatchCandidateSetIter<'a>;
8887
8888    fn id(&self) -> usize {
8889        self.snapshot.id().to_usize()
8890    }
8891
8892    fn len(&self) -> usize {
8893        if self.include_ignored {
8894            self.snapshot.file_count()
8895        } else {
8896            self.snapshot.visible_file_count()
8897        }
8898    }
8899
8900    fn prefix(&self) -> Arc<str> {
8901        if self.snapshot.root_entry().map_or(false, |e| e.is_file()) {
8902            self.snapshot.root_name().into()
8903        } else if self.include_root_name {
8904            format!("{}/", self.snapshot.root_name()).into()
8905        } else {
8906            "".into()
8907        }
8908    }
8909
8910    fn candidates(&'a self, start: usize) -> Self::Candidates {
8911        PathMatchCandidateSetIter {
8912            traversal: self.snapshot.files(self.include_ignored, start),
8913        }
8914    }
8915}
8916
8917pub struct PathMatchCandidateSetIter<'a> {
8918    traversal: Traversal<'a>,
8919}
8920
8921impl<'a> Iterator for PathMatchCandidateSetIter<'a> {
8922    type Item = fuzzy::PathMatchCandidate<'a>;
8923
8924    fn next(&mut self) -> Option<Self::Item> {
8925        self.traversal.next().map(|entry| {
8926            if let EntryKind::File(char_bag) = entry.kind {
8927                fuzzy::PathMatchCandidate {
8928                    path: &entry.path,
8929                    char_bag,
8930                }
8931            } else {
8932                unreachable!()
8933            }
8934        })
8935    }
8936}
8937
8938impl Entity for Project {
8939    type Event = Event;
8940
8941    fn release(&mut self, cx: &mut gpui::AppContext) {
8942        match &self.client_state {
8943            Some(ProjectClientState::Local { .. }) => {
8944                let _ = self.unshare_internal(cx);
8945            }
8946            Some(ProjectClientState::Remote { remote_id, .. }) => {
8947                let _ = self.client.send(proto::LeaveProject {
8948                    project_id: *remote_id,
8949                });
8950                self.disconnected_from_host_internal(cx);
8951            }
8952            _ => {}
8953        }
8954    }
8955
8956    fn app_will_quit(
8957        &mut self,
8958        _: &mut AppContext,
8959    ) -> Option<std::pin::Pin<Box<dyn 'static + Future<Output = ()>>>> {
8960        let shutdown_futures = self
8961            .language_servers
8962            .drain()
8963            .map(|(_, server_state)| async {
8964                use LanguageServerState::*;
8965                match server_state {
8966                    Running { server, .. } => server.shutdown()?.await,
8967                    Starting(task) => task.await?.shutdown()?.await,
8968                }
8969            })
8970            .collect::<Vec<_>>();
8971
8972        Some(
8973            async move {
8974                futures::future::join_all(shutdown_futures).await;
8975            }
8976            .boxed(),
8977        )
8978    }
8979}
8980
8981impl<P: AsRef<Path>> From<(WorktreeId, P)> for ProjectPath {
8982    fn from((worktree_id, path): (WorktreeId, P)) -> Self {
8983        Self {
8984            worktree_id,
8985            path: path.as_ref().into(),
8986        }
8987    }
8988}
8989
8990impl ProjectLspAdapterDelegate {
8991    fn new(project: &Project, cx: &ModelContext<Project>) -> Arc<Self> {
8992        Arc::new(Self {
8993            project: cx.handle(),
8994            http_client: project.client.http_client(),
8995        })
8996    }
8997}
8998
8999impl LspAdapterDelegate for ProjectLspAdapterDelegate {
9000    fn show_notification(&self, message: &str, cx: &mut AppContext) {
9001        self.project
9002            .update(cx, |_, cx| cx.emit(Event::Notification(message.to_owned())));
9003    }
9004
9005    fn http_client(&self) -> Arc<dyn HttpClient> {
9006        self.http_client.clone()
9007    }
9008}
9009
9010fn serialize_symbol(symbol: &Symbol) -> proto::Symbol {
9011    proto::Symbol {
9012        language_server_name: symbol.language_server_name.0.to_string(),
9013        source_worktree_id: symbol.source_worktree_id.to_proto(),
9014        worktree_id: symbol.path.worktree_id.to_proto(),
9015        path: symbol.path.path.to_string_lossy().to_string(),
9016        name: symbol.name.clone(),
9017        kind: unsafe { mem::transmute(symbol.kind) },
9018        start: Some(proto::PointUtf16 {
9019            row: symbol.range.start.0.row,
9020            column: symbol.range.start.0.column,
9021        }),
9022        end: Some(proto::PointUtf16 {
9023            row: symbol.range.end.0.row,
9024            column: symbol.range.end.0.column,
9025        }),
9026        signature: symbol.signature.to_vec(),
9027    }
9028}
9029
9030fn relativize_path(base: &Path, path: &Path) -> PathBuf {
9031    let mut path_components = path.components();
9032    let mut base_components = base.components();
9033    let mut components: Vec<Component> = Vec::new();
9034    loop {
9035        match (path_components.next(), base_components.next()) {
9036            (None, None) => break,
9037            (Some(a), None) => {
9038                components.push(a);
9039                components.extend(path_components.by_ref());
9040                break;
9041            }
9042            (None, _) => components.push(Component::ParentDir),
9043            (Some(a), Some(b)) if components.is_empty() && a == b => (),
9044            (Some(a), Some(b)) if b == Component::CurDir => components.push(a),
9045            (Some(a), Some(_)) => {
9046                components.push(Component::ParentDir);
9047                for _ in base_components {
9048                    components.push(Component::ParentDir);
9049                }
9050                components.push(a);
9051                components.extend(path_components.by_ref());
9052                break;
9053            }
9054        }
9055    }
9056    components.iter().map(|c| c.as_os_str()).collect()
9057}
9058
9059impl Item for Buffer {
9060    fn entry_id(&self, cx: &AppContext) -> Option<ProjectEntryId> {
9061        File::from_dyn(self.file()).and_then(|file| file.project_entry_id(cx))
9062    }
9063
9064    fn project_path(&self, cx: &AppContext) -> Option<ProjectPath> {
9065        File::from_dyn(self.file()).map(|file| ProjectPath {
9066            worktree_id: file.worktree_id(cx),
9067            path: file.path().clone(),
9068        })
9069    }
9070}
9071
9072async fn wait_for_loading_buffer(
9073    mut receiver: postage::watch::Receiver<Option<Result<ModelHandle<Buffer>, Arc<anyhow::Error>>>>,
9074) -> Result<ModelHandle<Buffer>, Arc<anyhow::Error>> {
9075    loop {
9076        if let Some(result) = receiver.borrow().as_ref() {
9077            match result {
9078                Ok(buffer) => return Ok(buffer.to_owned()),
9079                Err(e) => return Err(e.to_owned()),
9080            }
9081        }
9082        receiver.next().await;
9083    }
9084}
9085
9086fn include_text(server: &lsp::LanguageServer) -> bool {
9087    server
9088        .capabilities()
9089        .text_document_sync
9090        .as_ref()
9091        .and_then(|sync| match sync {
9092            lsp::TextDocumentSyncCapability::Kind(_) => None,
9093            lsp::TextDocumentSyncCapability::Options(options) => options.save.as_ref(),
9094        })
9095        .and_then(|save_options| match save_options {
9096            lsp::TextDocumentSyncSaveOptions::Supported(_) => None,
9097            lsp::TextDocumentSyncSaveOptions::SaveOptions(options) => options.include_text,
9098        })
9099        .unwrap_or(false)
9100}