project.rs

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