project.rs

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