copilot.rs

   1pub mod copilot_chat;
   2mod copilot_edit_prediction_delegate;
   3pub mod copilot_responses;
   4pub mod request;
   5mod sign_in;
   6
   7use crate::sign_in::initiate_sign_in_within_workspace;
   8use ::fs::Fs;
   9use anyhow::{Context as _, Result, anyhow};
  10use collections::{HashMap, HashSet};
  11use command_palette_hooks::CommandPaletteFilter;
  12use futures::{Future, FutureExt, TryFutureExt, channel::oneshot, future::Shared};
  13use gpui::{
  14    App, AppContext as _, AsyncApp, Context, Entity, EntityId, EventEmitter, Global, Task,
  15    WeakEntity, actions,
  16};
  17use http_client::HttpClient;
  18use language::language_settings::CopilotSettings;
  19use language::{
  20    Anchor, Bias, Buffer, BufferSnapshot, Language, PointUtf16, ToPointUtf16,
  21    language_settings::{EditPredictionProvider, all_language_settings, language_settings},
  22    point_from_lsp, point_to_lsp,
  23};
  24use lsp::{LanguageServer, LanguageServerBinary, LanguageServerId, LanguageServerName};
  25use node_runtime::{NodeRuntime, VersionStrategy};
  26use parking_lot::Mutex;
  27use project::DisableAiSettings;
  28use request::StatusNotification;
  29use semver::Version;
  30use serde_json::json;
  31use settings::Settings;
  32use settings::SettingsStore;
  33use sign_in::{reinstall_and_sign_in_within_workspace, sign_out_within_workspace};
  34use std::collections::hash_map::Entry;
  35use std::{
  36    any::TypeId,
  37    env,
  38    ffi::OsString,
  39    mem,
  40    ops::Range,
  41    path::{Path, PathBuf},
  42    sync::Arc,
  43};
  44use sum_tree::Dimensions;
  45use util::rel_path::RelPath;
  46use util::{ResultExt, fs::remove_matching};
  47use workspace::Workspace;
  48
  49pub use crate::copilot_edit_prediction_delegate::CopilotEditPredictionDelegate;
  50pub use crate::sign_in::{CopilotCodeVerification, initiate_sign_in, reinstall_and_sign_in};
  51
  52actions!(
  53    copilot,
  54    [
  55        /// Requests a code completion suggestion from Copilot.
  56        Suggest,
  57        /// Cycles to the next Copilot suggestion.
  58        NextSuggestion,
  59        /// Cycles to the previous Copilot suggestion.
  60        PreviousSuggestion,
  61        /// Reinstalls the Copilot language server.
  62        Reinstall,
  63        /// Signs in to GitHub Copilot.
  64        SignIn,
  65        /// Signs out of GitHub Copilot.
  66        SignOut
  67    ]
  68);
  69
  70pub fn init(
  71    new_server_id: LanguageServerId,
  72    fs: Arc<dyn Fs>,
  73    http: Arc<dyn HttpClient>,
  74    node_runtime: NodeRuntime,
  75    cx: &mut App,
  76) {
  77    let language_settings = all_language_settings(None, cx);
  78    let configuration = copilot_chat::CopilotChatConfiguration {
  79        enterprise_uri: language_settings
  80            .edit_predictions
  81            .copilot
  82            .enterprise_uri
  83            .clone(),
  84    };
  85    copilot_chat::init(fs.clone(), http.clone(), configuration, cx);
  86
  87    let copilot = cx.new(move |cx| Copilot::start(new_server_id, fs, node_runtime, cx));
  88    Copilot::set_global(copilot.clone(), cx);
  89    cx.observe(&copilot, |copilot, cx| {
  90        copilot.update(cx, |copilot, cx| copilot.update_action_visibilities(cx));
  91    })
  92    .detach();
  93    cx.observe_global::<SettingsStore>(|cx| {
  94        if let Some(copilot) = Copilot::global(cx) {
  95            copilot.update(cx, |copilot, cx| copilot.update_action_visibilities(cx));
  96        }
  97    })
  98    .detach();
  99
 100    cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
 101        workspace.register_action(|workspace, _: &SignIn, window, cx| {
 102            if let Some(copilot) = Copilot::global(cx) {
 103                let is_reinstall = false;
 104                initiate_sign_in_within_workspace(workspace, copilot, is_reinstall, window, cx);
 105            }
 106        });
 107        workspace.register_action(|workspace, _: &Reinstall, window, cx| {
 108            if let Some(copilot) = Copilot::global(cx) {
 109                reinstall_and_sign_in_within_workspace(workspace, copilot, window, cx);
 110            }
 111        });
 112        workspace.register_action(|workspace, _: &SignOut, _window, cx| {
 113            if let Some(copilot) = Copilot::global(cx) {
 114                sign_out_within_workspace(workspace, copilot, cx);
 115            }
 116        });
 117    })
 118    .detach();
 119}
 120
 121enum CopilotServer {
 122    Disabled,
 123    Starting { task: Shared<Task<()>> },
 124    Error(Arc<str>),
 125    Running(RunningCopilotServer),
 126}
 127
 128impl CopilotServer {
 129    fn as_authenticated(&mut self) -> Result<&mut RunningCopilotServer> {
 130        let server = self.as_running()?;
 131        anyhow::ensure!(
 132            matches!(server.sign_in_status, SignInStatus::Authorized),
 133            "must sign in before using copilot"
 134        );
 135        Ok(server)
 136    }
 137
 138    fn as_running(&mut self) -> Result<&mut RunningCopilotServer> {
 139        match self {
 140            CopilotServer::Starting { .. } => anyhow::bail!("copilot is still starting"),
 141            CopilotServer::Disabled => anyhow::bail!("copilot is disabled"),
 142            CopilotServer::Error(error) => {
 143                anyhow::bail!("copilot was not started because of an error: {error}")
 144            }
 145            CopilotServer::Running(server) => Ok(server),
 146        }
 147    }
 148}
 149
 150struct RunningCopilotServer {
 151    lsp: Arc<LanguageServer>,
 152    sign_in_status: SignInStatus,
 153    registered_buffers: HashMap<EntityId, RegisteredBuffer>,
 154}
 155
 156#[derive(Clone, Debug)]
 157enum SignInStatus {
 158    Authorized,
 159    Unauthorized,
 160    SigningIn {
 161        prompt: Option<request::PromptUserDeviceFlow>,
 162        task: Shared<Task<Result<(), Arc<anyhow::Error>>>>,
 163    },
 164    SignedOut {
 165        awaiting_signing_in: bool,
 166    },
 167}
 168
 169#[derive(Debug, Clone)]
 170pub enum Status {
 171    Starting {
 172        task: Shared<Task<()>>,
 173    },
 174    Error(Arc<str>),
 175    Disabled,
 176    SignedOut {
 177        awaiting_signing_in: bool,
 178    },
 179    SigningIn {
 180        prompt: Option<request::PromptUserDeviceFlow>,
 181    },
 182    Unauthorized,
 183    Authorized,
 184}
 185
 186impl Status {
 187    pub fn is_authorized(&self) -> bool {
 188        matches!(self, Status::Authorized)
 189    }
 190
 191    pub fn is_configured(&self) -> bool {
 192        matches!(
 193            self,
 194            Status::Starting { .. }
 195                | Status::Error(_)
 196                | Status::SigningIn { .. }
 197                | Status::Authorized
 198        )
 199    }
 200}
 201
 202struct RegisteredBuffer {
 203    uri: lsp::Uri,
 204    language_id: String,
 205    snapshot: BufferSnapshot,
 206    snapshot_version: i32,
 207    _subscriptions: [gpui::Subscription; 2],
 208    pending_buffer_change: Task<Option<()>>,
 209}
 210
 211impl RegisteredBuffer {
 212    fn report_changes(
 213        &mut self,
 214        buffer: &Entity<Buffer>,
 215        cx: &mut Context<Copilot>,
 216    ) -> oneshot::Receiver<(i32, BufferSnapshot)> {
 217        let (done_tx, done_rx) = oneshot::channel();
 218
 219        if buffer.read(cx).version() == self.snapshot.version {
 220            let _ = done_tx.send((self.snapshot_version, self.snapshot.clone()));
 221        } else {
 222            let buffer = buffer.downgrade();
 223            let id = buffer.entity_id();
 224            let prev_pending_change =
 225                mem::replace(&mut self.pending_buffer_change, Task::ready(None));
 226            self.pending_buffer_change = cx.spawn(async move |copilot, cx| {
 227                prev_pending_change.await;
 228
 229                let old_version = copilot
 230                    .update(cx, |copilot, _| {
 231                        let server = copilot.server.as_authenticated().log_err()?;
 232                        let buffer = server.registered_buffers.get_mut(&id)?;
 233                        Some(buffer.snapshot.version.clone())
 234                    })
 235                    .ok()??;
 236                let new_snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot()).ok()?;
 237
 238                let content_changes = cx
 239                    .background_spawn({
 240                        let new_snapshot = new_snapshot.clone();
 241                        async move {
 242                            new_snapshot
 243                                .edits_since::<Dimensions<PointUtf16, usize>>(&old_version)
 244                                .map(|edit| {
 245                                    let edit_start = edit.new.start.0;
 246                                    let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
 247                                    let new_text = new_snapshot
 248                                        .text_for_range(edit.new.start.1..edit.new.end.1)
 249                                        .collect();
 250                                    lsp::TextDocumentContentChangeEvent {
 251                                        range: Some(lsp::Range::new(
 252                                            point_to_lsp(edit_start),
 253                                            point_to_lsp(edit_end),
 254                                        )),
 255                                        range_length: None,
 256                                        text: new_text,
 257                                    }
 258                                })
 259                                .collect::<Vec<_>>()
 260                        }
 261                    })
 262                    .await;
 263
 264                copilot
 265                    .update(cx, |copilot, _| {
 266                        let server = copilot.server.as_authenticated().log_err()?;
 267                        let buffer = server.registered_buffers.get_mut(&id)?;
 268                        if !content_changes.is_empty() {
 269                            buffer.snapshot_version += 1;
 270                            buffer.snapshot = new_snapshot;
 271                            server
 272                                .lsp
 273                                .notify::<lsp::notification::DidChangeTextDocument>(
 274                                    lsp::DidChangeTextDocumentParams {
 275                                        text_document: lsp::VersionedTextDocumentIdentifier::new(
 276                                            buffer.uri.clone(),
 277                                            buffer.snapshot_version,
 278                                        ),
 279                                        content_changes,
 280                                    },
 281                                )
 282                                .ok();
 283                        }
 284                        let _ = done_tx.send((buffer.snapshot_version, buffer.snapshot.clone()));
 285                        Some(())
 286                    })
 287                    .ok()?;
 288
 289                Some(())
 290            });
 291        }
 292
 293        done_rx
 294    }
 295}
 296
 297#[derive(Debug)]
 298pub struct Completion {
 299    pub uuid: String,
 300    pub range: Range<Anchor>,
 301    pub text: String,
 302}
 303
 304pub struct Copilot {
 305    fs: Arc<dyn Fs>,
 306    node_runtime: NodeRuntime,
 307    server: CopilotServer,
 308    buffers: HashSet<WeakEntity<Buffer>>,
 309    server_id: LanguageServerId,
 310    _subscription: gpui::Subscription,
 311}
 312
 313pub enum Event {
 314    CopilotLanguageServerStarted,
 315    CopilotAuthSignedIn,
 316    CopilotAuthSignedOut,
 317}
 318
 319impl EventEmitter<Event> for Copilot {}
 320
 321struct GlobalCopilot(Entity<Copilot>);
 322
 323impl Global for GlobalCopilot {}
 324
 325impl Copilot {
 326    pub fn global(cx: &App) -> Option<Entity<Self>> {
 327        cx.try_global::<GlobalCopilot>()
 328            .map(|model| model.0.clone())
 329    }
 330
 331    pub fn set_global(copilot: Entity<Self>, cx: &mut App) {
 332        cx.set_global(GlobalCopilot(copilot));
 333    }
 334
 335    fn start(
 336        new_server_id: LanguageServerId,
 337        fs: Arc<dyn Fs>,
 338        node_runtime: NodeRuntime,
 339        cx: &mut Context<Self>,
 340    ) -> Self {
 341        let mut this = Self {
 342            server_id: new_server_id,
 343            fs,
 344            node_runtime,
 345            server: CopilotServer::Disabled,
 346            buffers: Default::default(),
 347            _subscription: cx.on_app_quit(Self::shutdown_language_server),
 348        };
 349        this.start_copilot(true, false, cx);
 350        cx.observe_global::<SettingsStore>(move |this, cx| {
 351            this.start_copilot(true, false, cx);
 352            if let Ok(server) = this.server.as_running() {
 353                notify_did_change_config_to_server(&server.lsp, cx)
 354                    .context("copilot setting change: did change configuration")
 355                    .log_err();
 356            }
 357        })
 358        .detach();
 359        this
 360    }
 361
 362    fn shutdown_language_server(
 363        &mut self,
 364        _cx: &mut Context<Self>,
 365    ) -> impl Future<Output = ()> + use<> {
 366        let shutdown = match mem::replace(&mut self.server, CopilotServer::Disabled) {
 367            CopilotServer::Running(server) => Some(Box::pin(async move { server.lsp.shutdown() })),
 368            _ => None,
 369        };
 370
 371        async move {
 372            if let Some(shutdown) = shutdown {
 373                shutdown.await;
 374            }
 375        }
 376    }
 377
 378    fn start_copilot(
 379        &mut self,
 380        check_edit_prediction_provider: bool,
 381        awaiting_sign_in_after_start: bool,
 382        cx: &mut Context<Self>,
 383    ) {
 384        if !matches!(self.server, CopilotServer::Disabled) {
 385            return;
 386        }
 387        let language_settings = all_language_settings(None, cx);
 388        if check_edit_prediction_provider
 389            && language_settings.edit_predictions.provider != EditPredictionProvider::Copilot
 390        {
 391            return;
 392        }
 393        let server_id = self.server_id;
 394        let fs = self.fs.clone();
 395        let node_runtime = self.node_runtime.clone();
 396        let env = self.build_env(&language_settings.edit_predictions.copilot);
 397        let start_task = cx
 398            .spawn(async move |this, cx| {
 399                Self::start_language_server(
 400                    server_id,
 401                    fs,
 402                    node_runtime,
 403                    env,
 404                    this,
 405                    awaiting_sign_in_after_start,
 406                    cx,
 407                )
 408                .await
 409            })
 410            .shared();
 411        self.server = CopilotServer::Starting { task: start_task };
 412        cx.notify();
 413    }
 414
 415    fn build_env(&self, copilot_settings: &CopilotSettings) -> Option<HashMap<String, String>> {
 416        let proxy_url = copilot_settings.proxy.clone()?;
 417        let no_verify = copilot_settings.proxy_no_verify;
 418        let http_or_https_proxy = if proxy_url.starts_with("http:") {
 419            Some("HTTP_PROXY")
 420        } else if proxy_url.starts_with("https:") {
 421            Some("HTTPS_PROXY")
 422        } else {
 423            log::error!(
 424                "Unsupported protocol scheme for language server proxy (must be http or https)"
 425            );
 426            None
 427        };
 428
 429        let mut env = HashMap::default();
 430
 431        if let Some(proxy_type) = http_or_https_proxy {
 432            env.insert(proxy_type.to_string(), proxy_url);
 433            if let Some(true) = no_verify {
 434                env.insert("NODE_TLS_REJECT_UNAUTHORIZED".to_string(), "0".to_string());
 435            };
 436        }
 437
 438        if let Ok(oauth_token) = env::var(copilot_chat::COPILOT_OAUTH_ENV_VAR) {
 439            env.insert(copilot_chat::COPILOT_OAUTH_ENV_VAR.to_string(), oauth_token);
 440        }
 441
 442        if env.is_empty() { None } else { Some(env) }
 443    }
 444
 445    #[cfg(any(test, feature = "test-support"))]
 446    pub fn fake(cx: &mut gpui::TestAppContext) -> (Entity<Self>, lsp::FakeLanguageServer) {
 447        use fs::FakeFs;
 448        use lsp::FakeLanguageServer;
 449        use node_runtime::NodeRuntime;
 450
 451        let (server, fake_server) = FakeLanguageServer::new(
 452            LanguageServerId(0),
 453            LanguageServerBinary {
 454                path: "path/to/copilot".into(),
 455                arguments: vec![],
 456                env: None,
 457            },
 458            "copilot".into(),
 459            Default::default(),
 460            &mut cx.to_async(),
 461        );
 462        let node_runtime = NodeRuntime::unavailable();
 463        let this = cx.new(|cx| Self {
 464            server_id: LanguageServerId(0),
 465            fs: FakeFs::new(cx.background_executor().clone()),
 466            node_runtime,
 467            server: CopilotServer::Running(RunningCopilotServer {
 468                lsp: Arc::new(server),
 469                sign_in_status: SignInStatus::Authorized,
 470                registered_buffers: Default::default(),
 471            }),
 472            _subscription: cx.on_app_quit(Self::shutdown_language_server),
 473            buffers: Default::default(),
 474        });
 475        (this, fake_server)
 476    }
 477
 478    async fn start_language_server(
 479        new_server_id: LanguageServerId,
 480        fs: Arc<dyn Fs>,
 481        node_runtime: NodeRuntime,
 482        env: Option<HashMap<String, String>>,
 483        this: WeakEntity<Self>,
 484        awaiting_sign_in_after_start: bool,
 485        cx: &mut AsyncApp,
 486    ) {
 487        let start_language_server = async {
 488            let server_path = get_copilot_lsp(fs, node_runtime.clone()).await?;
 489            let node_path = node_runtime.binary_path().await?;
 490            ensure_node_version_for_copilot(&node_path).await?;
 491
 492            let arguments: Vec<OsString> = vec![
 493                "--experimental-sqlite".into(),
 494                server_path.into(),
 495                "--stdio".into(),
 496            ];
 497            let binary = LanguageServerBinary {
 498                path: node_path,
 499                arguments,
 500                env,
 501            };
 502
 503            let root_path = if cfg!(target_os = "windows") {
 504                Path::new("C:/")
 505            } else {
 506                Path::new("/")
 507            };
 508
 509            let server_name = LanguageServerName("copilot".into());
 510            let server = LanguageServer::new(
 511                Arc::new(Mutex::new(None)),
 512                new_server_id,
 513                server_name,
 514                binary,
 515                root_path,
 516                None,
 517                Default::default(),
 518                cx,
 519            )
 520            .await?;
 521
 522            server
 523                .on_notification::<StatusNotification, _>(|_, _| { /* Silence the notification */ })
 524                .detach();
 525
 526            let configuration = lsp::DidChangeConfigurationParams {
 527                settings: Default::default(),
 528            };
 529
 530            let editor_info = request::SetEditorInfoParams {
 531                editor_info: request::EditorInfo {
 532                    name: "zed".into(),
 533                    version: env!("CARGO_PKG_VERSION").into(),
 534                },
 535                editor_plugin_info: request::EditorPluginInfo {
 536                    name: "zed-copilot".into(),
 537                    version: "0.0.1".into(),
 538                },
 539            };
 540            let editor_info_json = serde_json::to_value(&editor_info)?;
 541
 542            let server = cx
 543                .update(|cx| {
 544                    let mut params = server.default_initialize_params(false, cx);
 545                    params.initialization_options = Some(editor_info_json);
 546                    server.initialize(params, configuration.into(), cx)
 547                })?
 548                .await?;
 549
 550            this.update(cx, |_, cx| notify_did_change_config_to_server(&server, cx))?
 551                .context("copilot: did change configuration")?;
 552
 553            let status = server
 554                .request::<request::CheckStatus>(request::CheckStatusParams {
 555                    local_checks_only: false,
 556                })
 557                .await
 558                .into_response()
 559                .context("copilot: check status")?;
 560
 561            anyhow::Ok((server, status))
 562        };
 563
 564        let server = start_language_server.await;
 565        this.update(cx, |this, cx| {
 566            cx.notify();
 567            match server {
 568                Ok((server, status)) => {
 569                    this.server = CopilotServer::Running(RunningCopilotServer {
 570                        lsp: server,
 571                        sign_in_status: SignInStatus::SignedOut {
 572                            awaiting_signing_in: awaiting_sign_in_after_start,
 573                        },
 574                        registered_buffers: Default::default(),
 575                    });
 576                    cx.emit(Event::CopilotLanguageServerStarted);
 577                    this.update_sign_in_status(status, cx);
 578                }
 579                Err(error) => {
 580                    this.server = CopilotServer::Error(error.to_string().into());
 581                    cx.notify()
 582                }
 583            }
 584        })
 585        .ok();
 586    }
 587
 588    pub(crate) fn sign_in(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
 589        if let CopilotServer::Running(server) = &mut self.server {
 590            let task = match &server.sign_in_status {
 591                SignInStatus::Authorized => Task::ready(Ok(())).shared(),
 592                SignInStatus::SigningIn { task, .. } => {
 593                    cx.notify();
 594                    task.clone()
 595                }
 596                SignInStatus::SignedOut { .. } | SignInStatus::Unauthorized => {
 597                    let lsp = server.lsp.clone();
 598                    let task = cx
 599                        .spawn(async move |this, cx| {
 600                            let sign_in = async {
 601                                let sign_in = lsp
 602                                    .request::<request::SignInInitiate>(
 603                                        request::SignInInitiateParams {},
 604                                    )
 605                                    .await
 606                                    .into_response()
 607                                    .context("copilot sign-in")?;
 608                                match sign_in {
 609                                    request::SignInInitiateResult::AlreadySignedIn { user } => {
 610                                        Ok(request::SignInStatus::Ok { user: Some(user) })
 611                                    }
 612                                    request::SignInInitiateResult::PromptUserDeviceFlow(flow) => {
 613                                        this.update(cx, |this, cx| {
 614                                            if let CopilotServer::Running(RunningCopilotServer {
 615                                                sign_in_status: status,
 616                                                ..
 617                                            }) = &mut this.server
 618                                                && let SignInStatus::SigningIn {
 619                                                    prompt: prompt_flow,
 620                                                    ..
 621                                                } = status
 622                                            {
 623                                                *prompt_flow = Some(flow.clone());
 624                                                cx.notify();
 625                                            }
 626                                        })?;
 627                                        let response = lsp
 628                                            .request::<request::SignInConfirm>(
 629                                                request::SignInConfirmParams {
 630                                                    user_code: flow.user_code,
 631                                                },
 632                                            )
 633                                            .await
 634                                            .into_response()
 635                                            .context("copilot: sign in confirm")?;
 636                                        Ok(response)
 637                                    }
 638                                }
 639                            };
 640
 641                            let sign_in = sign_in.await;
 642                            this.update(cx, |this, cx| match sign_in {
 643                                Ok(status) => {
 644                                    this.update_sign_in_status(status, cx);
 645                                    Ok(())
 646                                }
 647                                Err(error) => {
 648                                    this.update_sign_in_status(
 649                                        request::SignInStatus::NotSignedIn,
 650                                        cx,
 651                                    );
 652                                    Err(Arc::new(error))
 653                                }
 654                            })?
 655                        })
 656                        .shared();
 657                    server.sign_in_status = SignInStatus::SigningIn {
 658                        prompt: None,
 659                        task: task.clone(),
 660                    };
 661                    cx.notify();
 662                    task
 663                }
 664            };
 665
 666            cx.background_spawn(task.map_err(|err| anyhow!("{err:?}")))
 667        } else {
 668            // If we're downloading, wait until download is finished
 669            // If we're in a stuck state, display to the user
 670            Task::ready(Err(anyhow!("copilot hasn't started yet")))
 671        }
 672    }
 673
 674    pub(crate) fn sign_out(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
 675        self.update_sign_in_status(request::SignInStatus::NotSignedIn, cx);
 676        match &self.server {
 677            CopilotServer::Running(RunningCopilotServer { lsp: server, .. }) => {
 678                let server = server.clone();
 679                cx.background_spawn(async move {
 680                    server
 681                        .request::<request::SignOut>(request::SignOutParams {})
 682                        .await
 683                        .into_response()
 684                        .context("copilot: sign in confirm")?;
 685                    anyhow::Ok(())
 686                })
 687            }
 688            CopilotServer::Disabled => cx.background_spawn(async {
 689                clear_copilot_config_dir().await;
 690                anyhow::Ok(())
 691            }),
 692            _ => Task::ready(Err(anyhow!("copilot hasn't started yet"))),
 693        }
 694    }
 695
 696    pub(crate) fn reinstall(&mut self, cx: &mut Context<Self>) -> Shared<Task<()>> {
 697        let language_settings = all_language_settings(None, cx);
 698        let env = self.build_env(&language_settings.edit_predictions.copilot);
 699        let start_task = cx
 700            .spawn({
 701                let fs = self.fs.clone();
 702                let node_runtime = self.node_runtime.clone();
 703                let server_id = self.server_id;
 704                async move |this, cx| {
 705                    clear_copilot_dir().await;
 706                    Self::start_language_server(server_id, fs, node_runtime, env, this, false, cx)
 707                        .await
 708                }
 709            })
 710            .shared();
 711
 712        self.server = CopilotServer::Starting {
 713            task: start_task.clone(),
 714        };
 715
 716        cx.notify();
 717
 718        start_task
 719    }
 720
 721    pub fn language_server(&self) -> Option<&Arc<LanguageServer>> {
 722        if let CopilotServer::Running(server) = &self.server {
 723            Some(&server.lsp)
 724        } else {
 725            None
 726        }
 727    }
 728
 729    pub fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) {
 730        let weak_buffer = buffer.downgrade();
 731        self.buffers.insert(weak_buffer.clone());
 732
 733        if let CopilotServer::Running(RunningCopilotServer {
 734            lsp: server,
 735            sign_in_status: status,
 736            registered_buffers,
 737            ..
 738        }) = &mut self.server
 739        {
 740            if !matches!(status, SignInStatus::Authorized) {
 741                return;
 742            }
 743
 744            let entry = registered_buffers.entry(buffer.entity_id());
 745            if let Entry::Vacant(e) = entry {
 746                let Ok(uri) = uri_for_buffer(buffer, cx) else {
 747                    return;
 748                };
 749                let language_id = id_for_language(buffer.read(cx).language());
 750                let snapshot = buffer.read(cx).snapshot();
 751                server
 752                    .notify::<lsp::notification::DidOpenTextDocument>(
 753                        lsp::DidOpenTextDocumentParams {
 754                            text_document: lsp::TextDocumentItem {
 755                                uri: uri.clone(),
 756                                language_id: language_id.clone(),
 757                                version: 0,
 758                                text: snapshot.text(),
 759                            },
 760                        },
 761                    )
 762                    .ok();
 763
 764                e.insert(RegisteredBuffer {
 765                    uri,
 766                    language_id,
 767                    snapshot,
 768                    snapshot_version: 0,
 769                    pending_buffer_change: Task::ready(Some(())),
 770                    _subscriptions: [
 771                        cx.subscribe(buffer, |this, buffer, event, cx| {
 772                            this.handle_buffer_event(buffer, event, cx).log_err();
 773                        }),
 774                        cx.observe_release(buffer, move |this, _buffer, _cx| {
 775                            this.buffers.remove(&weak_buffer);
 776                            this.unregister_buffer(&weak_buffer);
 777                        }),
 778                    ],
 779                });
 780            }
 781        }
 782    }
 783
 784    fn handle_buffer_event(
 785        &mut self,
 786        buffer: Entity<Buffer>,
 787        event: &language::BufferEvent,
 788        cx: &mut Context<Self>,
 789    ) -> Result<()> {
 790        if let Ok(server) = self.server.as_running()
 791            && let Some(registered_buffer) = server.registered_buffers.get_mut(&buffer.entity_id())
 792        {
 793            match event {
 794                language::BufferEvent::Edited => {
 795                    drop(registered_buffer.report_changes(&buffer, cx));
 796                }
 797                language::BufferEvent::Saved => {
 798                    server
 799                        .lsp
 800                        .notify::<lsp::notification::DidSaveTextDocument>(
 801                            lsp::DidSaveTextDocumentParams {
 802                                text_document: lsp::TextDocumentIdentifier::new(
 803                                    registered_buffer.uri.clone(),
 804                                ),
 805                                text: None,
 806                            },
 807                        )
 808                        .ok();
 809                }
 810                language::BufferEvent::FileHandleChanged
 811                | language::BufferEvent::LanguageChanged(_) => {
 812                    let new_language_id = id_for_language(buffer.read(cx).language());
 813                    let Ok(new_uri) = uri_for_buffer(&buffer, cx) else {
 814                        return Ok(());
 815                    };
 816                    if new_uri != registered_buffer.uri
 817                        || new_language_id != registered_buffer.language_id
 818                    {
 819                        let old_uri = mem::replace(&mut registered_buffer.uri, new_uri);
 820                        registered_buffer.language_id = new_language_id;
 821                        server
 822                            .lsp
 823                            .notify::<lsp::notification::DidCloseTextDocument>(
 824                                lsp::DidCloseTextDocumentParams {
 825                                    text_document: lsp::TextDocumentIdentifier::new(old_uri),
 826                                },
 827                            )
 828                            .ok();
 829                        server
 830                            .lsp
 831                            .notify::<lsp::notification::DidOpenTextDocument>(
 832                                lsp::DidOpenTextDocumentParams {
 833                                    text_document: lsp::TextDocumentItem::new(
 834                                        registered_buffer.uri.clone(),
 835                                        registered_buffer.language_id.clone(),
 836                                        registered_buffer.snapshot_version,
 837                                        registered_buffer.snapshot.text(),
 838                                    ),
 839                                },
 840                            )
 841                            .ok();
 842                    }
 843                }
 844                _ => {}
 845            }
 846        }
 847
 848        Ok(())
 849    }
 850
 851    fn unregister_buffer(&mut self, buffer: &WeakEntity<Buffer>) {
 852        if let Ok(server) = self.server.as_running()
 853            && let Some(buffer) = server.registered_buffers.remove(&buffer.entity_id())
 854        {
 855            server
 856                .lsp
 857                .notify::<lsp::notification::DidCloseTextDocument>(
 858                    lsp::DidCloseTextDocumentParams {
 859                        text_document: lsp::TextDocumentIdentifier::new(buffer.uri),
 860                    },
 861                )
 862                .ok();
 863        }
 864    }
 865
 866    pub fn completions<T>(
 867        &mut self,
 868        buffer: &Entity<Buffer>,
 869        position: T,
 870        cx: &mut Context<Self>,
 871    ) -> Task<Result<Vec<Completion>>>
 872    where
 873        T: ToPointUtf16,
 874    {
 875        self.request_completions::<request::GetCompletions, _>(buffer, position, cx)
 876    }
 877
 878    pub fn completions_cycling<T>(
 879        &mut self,
 880        buffer: &Entity<Buffer>,
 881        position: T,
 882        cx: &mut Context<Self>,
 883    ) -> Task<Result<Vec<Completion>>>
 884    where
 885        T: ToPointUtf16,
 886    {
 887        self.request_completions::<request::GetCompletionsCycling, _>(buffer, position, cx)
 888    }
 889
 890    pub fn accept_completion(
 891        &mut self,
 892        completion: &Completion,
 893        cx: &mut Context<Self>,
 894    ) -> Task<Result<()>> {
 895        let server = match self.server.as_authenticated() {
 896            Ok(server) => server,
 897            Err(error) => return Task::ready(Err(error)),
 898        };
 899        let request =
 900            server
 901                .lsp
 902                .request::<request::NotifyAccepted>(request::NotifyAcceptedParams {
 903                    uuid: completion.uuid.clone(),
 904                });
 905        cx.background_spawn(async move {
 906            request
 907                .await
 908                .into_response()
 909                .context("copilot: notify accepted")?;
 910            Ok(())
 911        })
 912    }
 913
 914    pub fn discard_completions(
 915        &mut self,
 916        completions: &[Completion],
 917        cx: &mut Context<Self>,
 918    ) -> Task<Result<()>> {
 919        let server = match self.server.as_authenticated() {
 920            Ok(server) => server,
 921            Err(_) => return Task::ready(Ok(())),
 922        };
 923        let request =
 924            server
 925                .lsp
 926                .request::<request::NotifyRejected>(request::NotifyRejectedParams {
 927                    uuids: completions
 928                        .iter()
 929                        .map(|completion| completion.uuid.clone())
 930                        .collect(),
 931                });
 932        cx.background_spawn(async move {
 933            request
 934                .await
 935                .into_response()
 936                .context("copilot: notify rejected")?;
 937            Ok(())
 938        })
 939    }
 940
 941    fn request_completions<R, T>(
 942        &mut self,
 943        buffer: &Entity<Buffer>,
 944        position: T,
 945        cx: &mut Context<Self>,
 946    ) -> Task<Result<Vec<Completion>>>
 947    where
 948        R: 'static
 949            + lsp::request::Request<
 950                Params = request::GetCompletionsParams,
 951                Result = request::GetCompletionsResult,
 952            >,
 953        T: ToPointUtf16,
 954    {
 955        self.register_buffer(buffer, cx);
 956
 957        let server = match self.server.as_authenticated() {
 958            Ok(server) => server,
 959            Err(error) => return Task::ready(Err(error)),
 960        };
 961        let lsp = server.lsp.clone();
 962        let registered_buffer = server
 963            .registered_buffers
 964            .get_mut(&buffer.entity_id())
 965            .unwrap();
 966        let snapshot = registered_buffer.report_changes(buffer, cx);
 967        let buffer = buffer.read(cx);
 968        let uri = registered_buffer.uri.clone();
 969        let position = position.to_point_utf16(buffer);
 970        let settings = language_settings(
 971            buffer.language_at(position).map(|l| l.name()),
 972            buffer.file(),
 973            cx,
 974        );
 975        let tab_size = settings.tab_size;
 976        let hard_tabs = settings.hard_tabs;
 977        let relative_path = buffer
 978            .file()
 979            .map_or(RelPath::empty().into(), |file| file.path().clone());
 980
 981        cx.background_spawn(async move {
 982            let (version, snapshot) = snapshot.await?;
 983            let result = lsp
 984                .request::<R>(request::GetCompletionsParams {
 985                    doc: request::GetCompletionsDocument {
 986                        uri,
 987                        tab_size: tab_size.into(),
 988                        indent_size: 1,
 989                        insert_spaces: !hard_tabs,
 990                        relative_path: relative_path.to_proto(),
 991                        position: point_to_lsp(position),
 992                        version: version.try_into().unwrap(),
 993                    },
 994                })
 995                .await
 996                .into_response()
 997                .context("copilot: get completions")?;
 998            let completions = result
 999                .completions
1000                .into_iter()
1001                .map(|completion| {
1002                    let start = snapshot
1003                        .clip_point_utf16(point_from_lsp(completion.range.start), Bias::Left);
1004                    let end =
1005                        snapshot.clip_point_utf16(point_from_lsp(completion.range.end), Bias::Left);
1006                    Completion {
1007                        uuid: completion.uuid,
1008                        range: snapshot.anchor_before(start)..snapshot.anchor_after(end),
1009                        text: completion.text,
1010                    }
1011                })
1012                .collect();
1013            anyhow::Ok(completions)
1014        })
1015    }
1016
1017    pub fn status(&self) -> Status {
1018        match &self.server {
1019            CopilotServer::Starting { task } => Status::Starting { task: task.clone() },
1020            CopilotServer::Disabled => Status::Disabled,
1021            CopilotServer::Error(error) => Status::Error(error.clone()),
1022            CopilotServer::Running(RunningCopilotServer { sign_in_status, .. }) => {
1023                match sign_in_status {
1024                    SignInStatus::Authorized => Status::Authorized,
1025                    SignInStatus::Unauthorized => Status::Unauthorized,
1026                    SignInStatus::SigningIn { prompt, .. } => Status::SigningIn {
1027                        prompt: prompt.clone(),
1028                    },
1029                    SignInStatus::SignedOut {
1030                        awaiting_signing_in,
1031                    } => Status::SignedOut {
1032                        awaiting_signing_in: *awaiting_signing_in,
1033                    },
1034                }
1035            }
1036        }
1037    }
1038
1039    fn update_sign_in_status(&mut self, lsp_status: request::SignInStatus, cx: &mut Context<Self>) {
1040        self.buffers.retain(|buffer| buffer.is_upgradable());
1041
1042        if let Ok(server) = self.server.as_running() {
1043            match lsp_status {
1044                request::SignInStatus::Ok { user: Some(_) }
1045                | request::SignInStatus::MaybeOk { .. }
1046                | request::SignInStatus::AlreadySignedIn { .. } => {
1047                    server.sign_in_status = SignInStatus::Authorized;
1048                    cx.emit(Event::CopilotAuthSignedIn);
1049                    for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1050                        if let Some(buffer) = buffer.upgrade() {
1051                            self.register_buffer(&buffer, cx);
1052                        }
1053                    }
1054                }
1055                request::SignInStatus::NotAuthorized { .. } => {
1056                    server.sign_in_status = SignInStatus::Unauthorized;
1057                    for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1058                        self.unregister_buffer(&buffer);
1059                    }
1060                }
1061                request::SignInStatus::Ok { user: None } | request::SignInStatus::NotSignedIn => {
1062                    if !matches!(server.sign_in_status, SignInStatus::SignedOut { .. }) {
1063                        server.sign_in_status = SignInStatus::SignedOut {
1064                            awaiting_signing_in: false,
1065                        };
1066                    }
1067                    cx.emit(Event::CopilotAuthSignedOut);
1068                    for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1069                        self.unregister_buffer(&buffer);
1070                    }
1071                }
1072            }
1073
1074            cx.notify();
1075        }
1076    }
1077
1078    fn update_action_visibilities(&self, cx: &mut App) {
1079        let signed_in_actions = [
1080            TypeId::of::<Suggest>(),
1081            TypeId::of::<NextSuggestion>(),
1082            TypeId::of::<PreviousSuggestion>(),
1083            TypeId::of::<Reinstall>(),
1084        ];
1085        let auth_actions = [TypeId::of::<SignOut>()];
1086        let no_auth_actions = [TypeId::of::<SignIn>()];
1087        let status = self.status();
1088
1089        let is_ai_disabled = DisableAiSettings::get_global(cx).disable_ai;
1090        let filter = CommandPaletteFilter::global_mut(cx);
1091
1092        if is_ai_disabled {
1093            filter.hide_action_types(&signed_in_actions);
1094            filter.hide_action_types(&auth_actions);
1095            filter.hide_action_types(&no_auth_actions);
1096        } else {
1097            match status {
1098                Status::Disabled => {
1099                    filter.hide_action_types(&signed_in_actions);
1100                    filter.hide_action_types(&auth_actions);
1101                    filter.hide_action_types(&no_auth_actions);
1102                }
1103                Status::Authorized => {
1104                    filter.hide_action_types(&no_auth_actions);
1105                    filter.show_action_types(signed_in_actions.iter().chain(&auth_actions));
1106                }
1107                _ => {
1108                    filter.hide_action_types(&signed_in_actions);
1109                    filter.hide_action_types(&auth_actions);
1110                    filter.show_action_types(&no_auth_actions);
1111                }
1112            }
1113        }
1114    }
1115}
1116
1117fn id_for_language(language: Option<&Arc<Language>>) -> String {
1118    language
1119        .map(|language| language.lsp_id())
1120        .unwrap_or_else(|| "plaintext".to_string())
1121}
1122
1123fn uri_for_buffer(buffer: &Entity<Buffer>, cx: &App) -> Result<lsp::Uri, ()> {
1124    if let Some(file) = buffer.read(cx).file().and_then(|file| file.as_local()) {
1125        lsp::Uri::from_file_path(file.abs_path(cx))
1126    } else {
1127        format!("buffer://{}", buffer.entity_id())
1128            .parse()
1129            .map_err(|_| ())
1130    }
1131}
1132
1133fn notify_did_change_config_to_server(
1134    server: &Arc<LanguageServer>,
1135    cx: &mut Context<Copilot>,
1136) -> std::result::Result<(), anyhow::Error> {
1137    let copilot_settings = all_language_settings(None, cx)
1138        .edit_predictions
1139        .copilot
1140        .clone();
1141
1142    if let Some(copilot_chat) = copilot_chat::CopilotChat::global(cx) {
1143        copilot_chat.update(cx, |chat, cx| {
1144            chat.set_configuration(
1145                copilot_chat::CopilotChatConfiguration {
1146                    enterprise_uri: copilot_settings.enterprise_uri.clone(),
1147                },
1148                cx,
1149            );
1150        });
1151    }
1152
1153    let settings = json!({
1154        "http": {
1155            "proxy": copilot_settings.proxy,
1156            "proxyStrictSSL": !copilot_settings.proxy_no_verify.unwrap_or(false)
1157        },
1158        "github-enterprise": {
1159            "uri": copilot_settings.enterprise_uri
1160        }
1161    });
1162
1163    server
1164        .notify::<lsp::notification::DidChangeConfiguration>(lsp::DidChangeConfigurationParams {
1165            settings,
1166        })
1167        .ok();
1168    Ok(())
1169}
1170
1171async fn clear_copilot_dir() {
1172    remove_matching(paths::copilot_dir(), |_| true).await
1173}
1174
1175async fn clear_copilot_config_dir() {
1176    remove_matching(copilot_chat::copilot_chat_config_dir(), |_| true).await
1177}
1178
1179async fn ensure_node_version_for_copilot(node_path: &Path) -> anyhow::Result<()> {
1180    const MIN_COPILOT_NODE_VERSION: Version = Version::new(20, 8, 0);
1181
1182    log::info!("Checking Node.js version for Copilot at: {:?}", node_path);
1183
1184    let output = util::command::new_smol_command(node_path)
1185        .arg("--version")
1186        .output()
1187        .await
1188        .with_context(|| format!("checking Node.js version at {:?}", node_path))?;
1189
1190    if !output.status.success() {
1191        anyhow::bail!(
1192            "failed to run node --version for Copilot. stdout: {}, stderr: {}",
1193            String::from_utf8_lossy(&output.stdout),
1194            String::from_utf8_lossy(&output.stderr),
1195        );
1196    }
1197
1198    let version_str = String::from_utf8_lossy(&output.stdout);
1199    let version = Version::parse(version_str.trim().trim_start_matches('v'))
1200        .with_context(|| format!("parsing Node.js version from '{}'", version_str.trim()))?;
1201
1202    if version < MIN_COPILOT_NODE_VERSION {
1203        anyhow::bail!(
1204            "GitHub Copilot language server requires Node.js {MIN_COPILOT_NODE_VERSION} or later, but found {version}. \
1205            Please update your Node.js version or configure a different Node.js path in settings."
1206        );
1207    }
1208
1209    log::info!(
1210        "Node.js version {} meets Copilot requirements (>= {})",
1211        version,
1212        MIN_COPILOT_NODE_VERSION
1213    );
1214    Ok(())
1215}
1216
1217async fn get_copilot_lsp(fs: Arc<dyn Fs>, node_runtime: NodeRuntime) -> anyhow::Result<PathBuf> {
1218    const PACKAGE_NAME: &str = "@github/copilot-language-server";
1219    const SERVER_PATH: &str =
1220        "node_modules/@github/copilot-language-server/dist/language-server.js";
1221
1222    let latest_version = node_runtime
1223        .npm_package_latest_version(PACKAGE_NAME)
1224        .await?;
1225    let server_path = paths::copilot_dir().join(SERVER_PATH);
1226
1227    fs.create_dir(paths::copilot_dir()).await?;
1228
1229    let should_install = node_runtime
1230        .should_install_npm_package(
1231            PACKAGE_NAME,
1232            &server_path,
1233            paths::copilot_dir(),
1234            VersionStrategy::Latest(&latest_version),
1235        )
1236        .await;
1237    if should_install {
1238        node_runtime
1239            .npm_install_packages(paths::copilot_dir(), &[(PACKAGE_NAME, &latest_version)])
1240            .await?;
1241    }
1242
1243    Ok(server_path)
1244}
1245
1246#[cfg(test)]
1247mod tests {
1248    use super::*;
1249    use gpui::TestAppContext;
1250    use util::{path, paths::PathStyle, rel_path::rel_path};
1251
1252    #[gpui::test(iterations = 10)]
1253    async fn test_buffer_management(cx: &mut TestAppContext) {
1254        let (copilot, mut lsp) = Copilot::fake(cx);
1255
1256        let buffer_1 = cx.new(|cx| Buffer::local("Hello", cx));
1257        let buffer_1_uri: lsp::Uri = format!("buffer://{}", buffer_1.entity_id().as_u64())
1258            .parse()
1259            .unwrap();
1260        copilot.update(cx, |copilot, cx| copilot.register_buffer(&buffer_1, cx));
1261        assert_eq!(
1262            lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1263                .await,
1264            lsp::DidOpenTextDocumentParams {
1265                text_document: lsp::TextDocumentItem::new(
1266                    buffer_1_uri.clone(),
1267                    "plaintext".into(),
1268                    0,
1269                    "Hello".into()
1270                ),
1271            }
1272        );
1273
1274        let buffer_2 = cx.new(|cx| Buffer::local("Goodbye", cx));
1275        let buffer_2_uri: lsp::Uri = format!("buffer://{}", buffer_2.entity_id().as_u64())
1276            .parse()
1277            .unwrap();
1278        copilot.update(cx, |copilot, cx| copilot.register_buffer(&buffer_2, cx));
1279        assert_eq!(
1280            lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1281                .await,
1282            lsp::DidOpenTextDocumentParams {
1283                text_document: lsp::TextDocumentItem::new(
1284                    buffer_2_uri.clone(),
1285                    "plaintext".into(),
1286                    0,
1287                    "Goodbye".into()
1288                ),
1289            }
1290        );
1291
1292        buffer_1.update(cx, |buffer, cx| buffer.edit([(5..5, " world")], None, cx));
1293        assert_eq!(
1294            lsp.receive_notification::<lsp::notification::DidChangeTextDocument>()
1295                .await,
1296            lsp::DidChangeTextDocumentParams {
1297                text_document: lsp::VersionedTextDocumentIdentifier::new(buffer_1_uri.clone(), 1),
1298                content_changes: vec![lsp::TextDocumentContentChangeEvent {
1299                    range: Some(lsp::Range::new(
1300                        lsp::Position::new(0, 5),
1301                        lsp::Position::new(0, 5)
1302                    )),
1303                    range_length: None,
1304                    text: " world".into(),
1305                }],
1306            }
1307        );
1308
1309        // Ensure updates to the file are reflected in the LSP.
1310        buffer_1.update(cx, |buffer, cx| {
1311            buffer.file_updated(
1312                Arc::new(File {
1313                    abs_path: path!("/root/child/buffer-1").into(),
1314                    path: rel_path("child/buffer-1").into(),
1315                }),
1316                cx,
1317            )
1318        });
1319        assert_eq!(
1320            lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1321                .await,
1322            lsp::DidCloseTextDocumentParams {
1323                text_document: lsp::TextDocumentIdentifier::new(buffer_1_uri),
1324            }
1325        );
1326        let buffer_1_uri = lsp::Uri::from_file_path(path!("/root/child/buffer-1")).unwrap();
1327        assert_eq!(
1328            lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1329                .await,
1330            lsp::DidOpenTextDocumentParams {
1331                text_document: lsp::TextDocumentItem::new(
1332                    buffer_1_uri.clone(),
1333                    "plaintext".into(),
1334                    1,
1335                    "Hello world".into()
1336                ),
1337            }
1338        );
1339
1340        // Ensure all previously-registered buffers are closed when signing out.
1341        lsp.set_request_handler::<request::SignOut, _, _>(|_, _| async {
1342            Ok(request::SignOutResult {})
1343        });
1344        copilot
1345            .update(cx, |copilot, cx| copilot.sign_out(cx))
1346            .await
1347            .unwrap();
1348        assert_eq!(
1349            lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1350                .await,
1351            lsp::DidCloseTextDocumentParams {
1352                text_document: lsp::TextDocumentIdentifier::new(buffer_1_uri.clone()),
1353            }
1354        );
1355        assert_eq!(
1356            lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1357                .await,
1358            lsp::DidCloseTextDocumentParams {
1359                text_document: lsp::TextDocumentIdentifier::new(buffer_2_uri.clone()),
1360            }
1361        );
1362
1363        // Ensure all previously-registered buffers are re-opened when signing in.
1364        lsp.set_request_handler::<request::SignInInitiate, _, _>(|_, _| async {
1365            Ok(request::SignInInitiateResult::AlreadySignedIn {
1366                user: "user-1".into(),
1367            })
1368        });
1369        copilot
1370            .update(cx, |copilot, cx| copilot.sign_in(cx))
1371            .await
1372            .unwrap();
1373
1374        assert_eq!(
1375            lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1376                .await,
1377            lsp::DidOpenTextDocumentParams {
1378                text_document: lsp::TextDocumentItem::new(
1379                    buffer_1_uri.clone(),
1380                    "plaintext".into(),
1381                    0,
1382                    "Hello world".into()
1383                ),
1384            }
1385        );
1386        assert_eq!(
1387            lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1388                .await,
1389            lsp::DidOpenTextDocumentParams {
1390                text_document: lsp::TextDocumentItem::new(
1391                    buffer_2_uri.clone(),
1392                    "plaintext".into(),
1393                    0,
1394                    "Goodbye".into()
1395                ),
1396            }
1397        );
1398        // Dropping a buffer causes it to be closed on the LSP side as well.
1399        cx.update(|_| drop(buffer_2));
1400        assert_eq!(
1401            lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1402                .await,
1403            lsp::DidCloseTextDocumentParams {
1404                text_document: lsp::TextDocumentIdentifier::new(buffer_2_uri),
1405            }
1406        );
1407    }
1408
1409    struct File {
1410        abs_path: PathBuf,
1411        path: Arc<RelPath>,
1412    }
1413
1414    impl language::File for File {
1415        fn as_local(&self) -> Option<&dyn language::LocalFile> {
1416            Some(self)
1417        }
1418
1419        fn disk_state(&self) -> language::DiskState {
1420            language::DiskState::Present {
1421                mtime: ::fs::MTime::from_seconds_and_nanos(100, 42),
1422            }
1423        }
1424
1425        fn path(&self) -> &Arc<RelPath> {
1426            &self.path
1427        }
1428
1429        fn path_style(&self, _: &App) -> PathStyle {
1430            PathStyle::local()
1431        }
1432
1433        fn full_path(&self, _: &App) -> PathBuf {
1434            unimplemented!()
1435        }
1436
1437        fn file_name<'a>(&'a self, _: &'a App) -> &'a str {
1438            unimplemented!()
1439        }
1440
1441        fn to_proto(&self, _: &App) -> rpc::proto::File {
1442            unimplemented!()
1443        }
1444
1445        fn worktree_id(&self, _: &App) -> settings::WorktreeId {
1446            settings::WorktreeId::from_usize(0)
1447        }
1448
1449        fn is_private(&self) -> bool {
1450            false
1451        }
1452    }
1453
1454    impl language::LocalFile for File {
1455        fn abs_path(&self, _: &App) -> PathBuf {
1456            self.abs_path.clone()
1457        }
1458
1459        fn load(&self, _: &App) -> Task<Result<String>> {
1460            unimplemented!()
1461        }
1462
1463        fn load_bytes(&self, _cx: &App) -> Task<Result<Vec<u8>>> {
1464            unimplemented!()
1465        }
1466    }
1467}
1468
1469#[cfg(test)]
1470#[ctor::ctor]
1471fn init_logger() {
1472    zlog::init_test();
1473}