project.rs

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