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