copilot.rs

   1pub mod copilot_chat;
   2mod copilot_completion_provider;
   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_completion_provider::CopilotCompletionProvider;
  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
 521            server
 522                .on_notification::<StatusNotification, _>(|_, _| { /* Silence the notification */ })
 523                .detach();
 524
 525            let configuration = lsp::DidChangeConfigurationParams {
 526                settings: Default::default(),
 527            };
 528
 529            let editor_info = request::SetEditorInfoParams {
 530                editor_info: request::EditorInfo {
 531                    name: "zed".into(),
 532                    version: env!("CARGO_PKG_VERSION").into(),
 533                },
 534                editor_plugin_info: request::EditorPluginInfo {
 535                    name: "zed-copilot".into(),
 536                    version: "0.0.1".into(),
 537                },
 538            };
 539            let editor_info_json = serde_json::to_value(&editor_info)?;
 540
 541            let server = cx
 542                .update(|cx| {
 543                    let mut params = server.default_initialize_params(false, cx);
 544                    params.initialization_options = Some(editor_info_json);
 545                    server.initialize(params, configuration.into(), cx)
 546                })?
 547                .await?;
 548
 549            this.update(cx, |_, cx| notify_did_change_config_to_server(&server, cx))?
 550                .context("copilot: did change configuration")?;
 551
 552            let status = server
 553                .request::<request::CheckStatus>(request::CheckStatusParams {
 554                    local_checks_only: false,
 555                })
 556                .await
 557                .into_response()
 558                .context("copilot: check status")?;
 559
 560            anyhow::Ok((server, status))
 561        };
 562
 563        let server = start_language_server.await;
 564        this.update(cx, |this, cx| {
 565            cx.notify();
 566            match server {
 567                Ok((server, status)) => {
 568                    this.server = CopilotServer::Running(RunningCopilotServer {
 569                        lsp: server,
 570                        sign_in_status: SignInStatus::SignedOut {
 571                            awaiting_signing_in: awaiting_sign_in_after_start,
 572                        },
 573                        registered_buffers: Default::default(),
 574                    });
 575                    cx.emit(Event::CopilotLanguageServerStarted);
 576                    this.update_sign_in_status(status, cx);
 577                }
 578                Err(error) => {
 579                    this.server = CopilotServer::Error(error.to_string().into());
 580                    cx.notify()
 581                }
 582            }
 583        })
 584        .ok();
 585    }
 586
 587    pub(crate) fn sign_in(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
 588        if let CopilotServer::Running(server) = &mut self.server {
 589            let task = match &server.sign_in_status {
 590                SignInStatus::Authorized => Task::ready(Ok(())).shared(),
 591                SignInStatus::SigningIn { task, .. } => {
 592                    cx.notify();
 593                    task.clone()
 594                }
 595                SignInStatus::SignedOut { .. } | SignInStatus::Unauthorized => {
 596                    let lsp = server.lsp.clone();
 597                    let task = cx
 598                        .spawn(async move |this, cx| {
 599                            let sign_in = async {
 600                                let sign_in = lsp
 601                                    .request::<request::SignInInitiate>(
 602                                        request::SignInInitiateParams {},
 603                                    )
 604                                    .await
 605                                    .into_response()
 606                                    .context("copilot sign-in")?;
 607                                match sign_in {
 608                                    request::SignInInitiateResult::AlreadySignedIn { user } => {
 609                                        Ok(request::SignInStatus::Ok { user: Some(user) })
 610                                    }
 611                                    request::SignInInitiateResult::PromptUserDeviceFlow(flow) => {
 612                                        this.update(cx, |this, cx| {
 613                                            if let CopilotServer::Running(RunningCopilotServer {
 614                                                sign_in_status: status,
 615                                                ..
 616                                            }) = &mut this.server
 617                                                && let SignInStatus::SigningIn {
 618                                                    prompt: prompt_flow,
 619                                                    ..
 620                                                } = status
 621                                            {
 622                                                *prompt_flow = Some(flow.clone());
 623                                                cx.notify();
 624                                            }
 625                                        })?;
 626                                        let response = lsp
 627                                            .request::<request::SignInConfirm>(
 628                                                request::SignInConfirmParams {
 629                                                    user_code: flow.user_code,
 630                                                },
 631                                            )
 632                                            .await
 633                                            .into_response()
 634                                            .context("copilot: sign in confirm")?;
 635                                        Ok(response)
 636                                    }
 637                                }
 638                            };
 639
 640                            let sign_in = sign_in.await;
 641                            this.update(cx, |this, cx| match sign_in {
 642                                Ok(status) => {
 643                                    this.update_sign_in_status(status, cx);
 644                                    Ok(())
 645                                }
 646                                Err(error) => {
 647                                    this.update_sign_in_status(
 648                                        request::SignInStatus::NotSignedIn,
 649                                        cx,
 650                                    );
 651                                    Err(Arc::new(error))
 652                                }
 653                            })?
 654                        })
 655                        .shared();
 656                    server.sign_in_status = SignInStatus::SigningIn {
 657                        prompt: None,
 658                        task: task.clone(),
 659                    };
 660                    cx.notify();
 661                    task
 662                }
 663            };
 664
 665            cx.background_spawn(task.map_err(|err| anyhow!("{err:?}")))
 666        } else {
 667            // If we're downloading, wait until download is finished
 668            // If we're in a stuck state, display to the user
 669            Task::ready(Err(anyhow!("copilot hasn't started yet")))
 670        }
 671    }
 672
 673    pub(crate) fn sign_out(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
 674        self.update_sign_in_status(request::SignInStatus::NotSignedIn, cx);
 675        match &self.server {
 676            CopilotServer::Running(RunningCopilotServer { lsp: server, .. }) => {
 677                let server = server.clone();
 678                cx.background_spawn(async move {
 679                    server
 680                        .request::<request::SignOut>(request::SignOutParams {})
 681                        .await
 682                        .into_response()
 683                        .context("copilot: sign in confirm")?;
 684                    anyhow::Ok(())
 685                })
 686            }
 687            CopilotServer::Disabled => cx.background_spawn(async {
 688                clear_copilot_config_dir().await;
 689                anyhow::Ok(())
 690            }),
 691            _ => Task::ready(Err(anyhow!("copilot hasn't started yet"))),
 692        }
 693    }
 694
 695    pub(crate) fn reinstall(&mut self, cx: &mut Context<Self>) -> Shared<Task<()>> {
 696        let language_settings = all_language_settings(None, cx);
 697        let env = self.build_env(&language_settings.edit_predictions.copilot);
 698        let start_task = cx
 699            .spawn({
 700                let fs = self.fs.clone();
 701                let node_runtime = self.node_runtime.clone();
 702                let server_id = self.server_id;
 703                async move |this, cx| {
 704                    clear_copilot_dir().await;
 705                    Self::start_language_server(server_id, fs, node_runtime, env, this, false, cx)
 706                        .await
 707                }
 708            })
 709            .shared();
 710
 711        self.server = CopilotServer::Starting {
 712            task: start_task.clone(),
 713        };
 714
 715        cx.notify();
 716
 717        start_task
 718    }
 719
 720    pub fn language_server(&self) -> Option<&Arc<LanguageServer>> {
 721        if let CopilotServer::Running(server) = &self.server {
 722            Some(&server.lsp)
 723        } else {
 724            None
 725        }
 726    }
 727
 728    pub fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) {
 729        let weak_buffer = buffer.downgrade();
 730        self.buffers.insert(weak_buffer.clone());
 731
 732        if let CopilotServer::Running(RunningCopilotServer {
 733            lsp: server,
 734            sign_in_status: status,
 735            registered_buffers,
 736            ..
 737        }) = &mut self.server
 738        {
 739            if !matches!(status, SignInStatus::Authorized) {
 740                return;
 741            }
 742
 743            let entry = registered_buffers.entry(buffer.entity_id());
 744            if let Entry::Vacant(e) = entry {
 745                let Ok(uri) = uri_for_buffer(buffer, cx) else {
 746                    return;
 747                };
 748                let language_id = id_for_language(buffer.read(cx).language());
 749                let snapshot = buffer.read(cx).snapshot();
 750                server
 751                    .notify::<lsp::notification::DidOpenTextDocument>(
 752                        lsp::DidOpenTextDocumentParams {
 753                            text_document: lsp::TextDocumentItem {
 754                                uri: uri.clone(),
 755                                language_id: language_id.clone(),
 756                                version: 0,
 757                                text: snapshot.text(),
 758                            },
 759                        },
 760                    )
 761                    .ok();
 762
 763                e.insert(RegisteredBuffer {
 764                    uri,
 765                    language_id,
 766                    snapshot,
 767                    snapshot_version: 0,
 768                    pending_buffer_change: Task::ready(Some(())),
 769                    _subscriptions: [
 770                        cx.subscribe(buffer, |this, buffer, event, cx| {
 771                            this.handle_buffer_event(buffer, event, cx).log_err();
 772                        }),
 773                        cx.observe_release(buffer, move |this, _buffer, _cx| {
 774                            this.buffers.remove(&weak_buffer);
 775                            this.unregister_buffer(&weak_buffer);
 776                        }),
 777                    ],
 778                });
 779            }
 780        }
 781    }
 782
 783    fn handle_buffer_event(
 784        &mut self,
 785        buffer: Entity<Buffer>,
 786        event: &language::BufferEvent,
 787        cx: &mut Context<Self>,
 788    ) -> Result<()> {
 789        if let Ok(server) = self.server.as_running()
 790            && let Some(registered_buffer) = server.registered_buffers.get_mut(&buffer.entity_id())
 791        {
 792            match event {
 793                language::BufferEvent::Edited => {
 794                    drop(registered_buffer.report_changes(&buffer, cx));
 795                }
 796                language::BufferEvent::Saved => {
 797                    server
 798                        .lsp
 799                        .notify::<lsp::notification::DidSaveTextDocument>(
 800                            lsp::DidSaveTextDocumentParams {
 801                                text_document: lsp::TextDocumentIdentifier::new(
 802                                    registered_buffer.uri.clone(),
 803                                ),
 804                                text: None,
 805                            },
 806                        )
 807                        .ok();
 808                }
 809                language::BufferEvent::FileHandleChanged
 810                | language::BufferEvent::LanguageChanged => {
 811                    let new_language_id = id_for_language(buffer.read(cx).language());
 812                    let Ok(new_uri) = uri_for_buffer(&buffer, cx) else {
 813                        return Ok(());
 814                    };
 815                    if new_uri != registered_buffer.uri
 816                        || new_language_id != registered_buffer.language_id
 817                    {
 818                        let old_uri = mem::replace(&mut registered_buffer.uri, new_uri);
 819                        registered_buffer.language_id = new_language_id;
 820                        server
 821                            .lsp
 822                            .notify::<lsp::notification::DidCloseTextDocument>(
 823                                lsp::DidCloseTextDocumentParams {
 824                                    text_document: lsp::TextDocumentIdentifier::new(old_uri),
 825                                },
 826                            )
 827                            .ok();
 828                        server
 829                            .lsp
 830                            .notify::<lsp::notification::DidOpenTextDocument>(
 831                                lsp::DidOpenTextDocumentParams {
 832                                    text_document: lsp::TextDocumentItem::new(
 833                                        registered_buffer.uri.clone(),
 834                                        registered_buffer.language_id.clone(),
 835                                        registered_buffer.snapshot_version,
 836                                        registered_buffer.snapshot.text(),
 837                                    ),
 838                                },
 839                            )
 840                            .ok();
 841                    }
 842                }
 843                _ => {}
 844            }
 845        }
 846
 847        Ok(())
 848    }
 849
 850    fn unregister_buffer(&mut self, buffer: &WeakEntity<Buffer>) {
 851        if let Ok(server) = self.server.as_running()
 852            && let Some(buffer) = server.registered_buffers.remove(&buffer.entity_id())
 853        {
 854            server
 855                .lsp
 856                .notify::<lsp::notification::DidCloseTextDocument>(
 857                    lsp::DidCloseTextDocumentParams {
 858                        text_document: lsp::TextDocumentIdentifier::new(buffer.uri),
 859                    },
 860                )
 861                .ok();
 862        }
 863    }
 864
 865    pub fn completions<T>(
 866        &mut self,
 867        buffer: &Entity<Buffer>,
 868        position: T,
 869        cx: &mut Context<Self>,
 870    ) -> Task<Result<Vec<Completion>>>
 871    where
 872        T: ToPointUtf16,
 873    {
 874        self.request_completions::<request::GetCompletions, _>(buffer, position, cx)
 875    }
 876
 877    pub fn completions_cycling<T>(
 878        &mut self,
 879        buffer: &Entity<Buffer>,
 880        position: T,
 881        cx: &mut Context<Self>,
 882    ) -> Task<Result<Vec<Completion>>>
 883    where
 884        T: ToPointUtf16,
 885    {
 886        self.request_completions::<request::GetCompletionsCycling, _>(buffer, position, cx)
 887    }
 888
 889    pub fn accept_completion(
 890        &mut self,
 891        completion: &Completion,
 892        cx: &mut Context<Self>,
 893    ) -> Task<Result<()>> {
 894        let server = match self.server.as_authenticated() {
 895            Ok(server) => server,
 896            Err(error) => return Task::ready(Err(error)),
 897        };
 898        let request =
 899            server
 900                .lsp
 901                .request::<request::NotifyAccepted>(request::NotifyAcceptedParams {
 902                    uuid: completion.uuid.clone(),
 903                });
 904        cx.background_spawn(async move {
 905            request
 906                .await
 907                .into_response()
 908                .context("copilot: notify accepted")?;
 909            Ok(())
 910        })
 911    }
 912
 913    pub fn discard_completions(
 914        &mut self,
 915        completions: &[Completion],
 916        cx: &mut Context<Self>,
 917    ) -> Task<Result<()>> {
 918        let server = match self.server.as_authenticated() {
 919            Ok(server) => server,
 920            Err(_) => return Task::ready(Ok(())),
 921        };
 922        let request =
 923            server
 924                .lsp
 925                .request::<request::NotifyRejected>(request::NotifyRejectedParams {
 926                    uuids: completions
 927                        .iter()
 928                        .map(|completion| completion.uuid.clone())
 929                        .collect(),
 930                });
 931        cx.background_spawn(async move {
 932            request
 933                .await
 934                .into_response()
 935                .context("copilot: notify rejected")?;
 936            Ok(())
 937        })
 938    }
 939
 940    fn request_completions<R, T>(
 941        &mut self,
 942        buffer: &Entity<Buffer>,
 943        position: T,
 944        cx: &mut Context<Self>,
 945    ) -> Task<Result<Vec<Completion>>>
 946    where
 947        R: 'static
 948            + lsp::request::Request<
 949                Params = request::GetCompletionsParams,
 950                Result = request::GetCompletionsResult,
 951            >,
 952        T: ToPointUtf16,
 953    {
 954        self.register_buffer(buffer, cx);
 955
 956        let server = match self.server.as_authenticated() {
 957            Ok(server) => server,
 958            Err(error) => return Task::ready(Err(error)),
 959        };
 960        let lsp = server.lsp.clone();
 961        let registered_buffer = server
 962            .registered_buffers
 963            .get_mut(&buffer.entity_id())
 964            .unwrap();
 965        let snapshot = registered_buffer.report_changes(buffer, cx);
 966        let buffer = buffer.read(cx);
 967        let uri = registered_buffer.uri.clone();
 968        let position = position.to_point_utf16(buffer);
 969        let settings = language_settings(
 970            buffer.language_at(position).map(|l| l.name()),
 971            buffer.file(),
 972            cx,
 973        );
 974        let tab_size = settings.tab_size;
 975        let hard_tabs = settings.hard_tabs;
 976        let relative_path = buffer
 977            .file()
 978            .map_or(RelPath::empty().into(), |file| file.path().clone());
 979
 980        cx.background_spawn(async move {
 981            let (version, snapshot) = snapshot.await?;
 982            let result = lsp
 983                .request::<R>(request::GetCompletionsParams {
 984                    doc: request::GetCompletionsDocument {
 985                        uri,
 986                        tab_size: tab_size.into(),
 987                        indent_size: 1,
 988                        insert_spaces: !hard_tabs,
 989                        relative_path: relative_path.to_proto(),
 990                        position: point_to_lsp(position),
 991                        version: version.try_into().unwrap(),
 992                    },
 993                })
 994                .await
 995                .into_response()
 996                .context("copilot: get completions")?;
 997            let completions = result
 998                .completions
 999                .into_iter()
1000                .map(|completion| {
1001                    let start = snapshot
1002                        .clip_point_utf16(point_from_lsp(completion.range.start), Bias::Left);
1003                    let end =
1004                        snapshot.clip_point_utf16(point_from_lsp(completion.range.end), Bias::Left);
1005                    Completion {
1006                        uuid: completion.uuid,
1007                        range: snapshot.anchor_before(start)..snapshot.anchor_after(end),
1008                        text: completion.text,
1009                    }
1010                })
1011                .collect();
1012            anyhow::Ok(completions)
1013        })
1014    }
1015
1016    pub fn status(&self) -> Status {
1017        match &self.server {
1018            CopilotServer::Starting { task } => Status::Starting { task: task.clone() },
1019            CopilotServer::Disabled => Status::Disabled,
1020            CopilotServer::Error(error) => Status::Error(error.clone()),
1021            CopilotServer::Running(RunningCopilotServer { sign_in_status, .. }) => {
1022                match sign_in_status {
1023                    SignInStatus::Authorized => Status::Authorized,
1024                    SignInStatus::Unauthorized => Status::Unauthorized,
1025                    SignInStatus::SigningIn { prompt, .. } => Status::SigningIn {
1026                        prompt: prompt.clone(),
1027                    },
1028                    SignInStatus::SignedOut {
1029                        awaiting_signing_in,
1030                    } => Status::SignedOut {
1031                        awaiting_signing_in: *awaiting_signing_in,
1032                    },
1033                }
1034            }
1035        }
1036    }
1037
1038    fn update_sign_in_status(&mut self, lsp_status: request::SignInStatus, cx: &mut Context<Self>) {
1039        self.buffers.retain(|buffer| buffer.is_upgradable());
1040
1041        if let Ok(server) = self.server.as_running() {
1042            match lsp_status {
1043                request::SignInStatus::Ok { user: Some(_) }
1044                | request::SignInStatus::MaybeOk { .. }
1045                | request::SignInStatus::AlreadySignedIn { .. } => {
1046                    server.sign_in_status = SignInStatus::Authorized;
1047                    cx.emit(Event::CopilotAuthSignedIn);
1048                    for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1049                        if let Some(buffer) = buffer.upgrade() {
1050                            self.register_buffer(&buffer, cx);
1051                        }
1052                    }
1053                }
1054                request::SignInStatus::NotAuthorized { .. } => {
1055                    server.sign_in_status = SignInStatus::Unauthorized;
1056                    for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1057                        self.unregister_buffer(&buffer);
1058                    }
1059                }
1060                request::SignInStatus::Ok { user: None } | request::SignInStatus::NotSignedIn => {
1061                    if !matches!(server.sign_in_status, SignInStatus::SignedOut { .. }) {
1062                        server.sign_in_status = SignInStatus::SignedOut {
1063                            awaiting_signing_in: false,
1064                        };
1065                    }
1066                    cx.emit(Event::CopilotAuthSignedOut);
1067                    for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1068                        self.unregister_buffer(&buffer);
1069                    }
1070                }
1071            }
1072
1073            cx.notify();
1074        }
1075    }
1076
1077    fn update_action_visibilities(&self, cx: &mut App) {
1078        let signed_in_actions = [
1079            TypeId::of::<Suggest>(),
1080            TypeId::of::<NextSuggestion>(),
1081            TypeId::of::<PreviousSuggestion>(),
1082            TypeId::of::<Reinstall>(),
1083        ];
1084        let auth_actions = [TypeId::of::<SignOut>()];
1085        let no_auth_actions = [TypeId::of::<SignIn>()];
1086        let status = self.status();
1087
1088        let is_ai_disabled = DisableAiSettings::get_global(cx).disable_ai;
1089        let filter = CommandPaletteFilter::global_mut(cx);
1090
1091        if is_ai_disabled {
1092            filter.hide_action_types(&signed_in_actions);
1093            filter.hide_action_types(&auth_actions);
1094            filter.hide_action_types(&no_auth_actions);
1095        } else {
1096            match status {
1097                Status::Disabled => {
1098                    filter.hide_action_types(&signed_in_actions);
1099                    filter.hide_action_types(&auth_actions);
1100                    filter.hide_action_types(&no_auth_actions);
1101                }
1102                Status::Authorized => {
1103                    filter.hide_action_types(&no_auth_actions);
1104                    filter.show_action_types(signed_in_actions.iter().chain(&auth_actions));
1105                }
1106                _ => {
1107                    filter.hide_action_types(&signed_in_actions);
1108                    filter.hide_action_types(&auth_actions);
1109                    filter.show_action_types(&no_auth_actions);
1110                }
1111            }
1112        }
1113    }
1114}
1115
1116fn id_for_language(language: Option<&Arc<Language>>) -> String {
1117    language
1118        .map(|language| language.lsp_id())
1119        .unwrap_or_else(|| "plaintext".to_string())
1120}
1121
1122fn uri_for_buffer(buffer: &Entity<Buffer>, cx: &App) -> Result<lsp::Uri, ()> {
1123    if let Some(file) = buffer.read(cx).file().and_then(|file| file.as_local()) {
1124        lsp::Uri::from_file_path(file.abs_path(cx))
1125    } else {
1126        format!("buffer://{}", buffer.entity_id())
1127            .parse()
1128            .map_err(|_| ())
1129    }
1130}
1131
1132fn notify_did_change_config_to_server(
1133    server: &Arc<LanguageServer>,
1134    cx: &mut Context<Copilot>,
1135) -> std::result::Result<(), anyhow::Error> {
1136    let copilot_settings = all_language_settings(None, cx)
1137        .edit_predictions
1138        .copilot
1139        .clone();
1140
1141    if let Some(copilot_chat) = copilot_chat::CopilotChat::global(cx) {
1142        copilot_chat.update(cx, |chat, cx| {
1143            chat.set_configuration(
1144                copilot_chat::CopilotChatConfiguration {
1145                    enterprise_uri: copilot_settings.enterprise_uri.clone(),
1146                },
1147                cx,
1148            );
1149        });
1150    }
1151
1152    let settings = json!({
1153        "http": {
1154            "proxy": copilot_settings.proxy,
1155            "proxyStrictSSL": !copilot_settings.proxy_no_verify.unwrap_or(false)
1156        },
1157        "github-enterprise": {
1158            "uri": copilot_settings.enterprise_uri
1159        }
1160    });
1161
1162    server
1163        .notify::<lsp::notification::DidChangeConfiguration>(lsp::DidChangeConfigurationParams {
1164            settings,
1165        })
1166        .ok();
1167    Ok(())
1168}
1169
1170async fn clear_copilot_dir() {
1171    remove_matching(paths::copilot_dir(), |_| true).await
1172}
1173
1174async fn clear_copilot_config_dir() {
1175    remove_matching(copilot_chat::copilot_chat_config_dir(), |_| true).await
1176}
1177
1178async fn ensure_node_version_for_copilot(node_path: &Path) -> anyhow::Result<()> {
1179    const MIN_COPILOT_NODE_VERSION: Version = Version::new(20, 8, 0);
1180
1181    log::info!("Checking Node.js version for Copilot at: {:?}", node_path);
1182
1183    let output = util::command::new_smol_command(node_path)
1184        .arg("--version")
1185        .output()
1186        .await
1187        .with_context(|| format!("checking Node.js version at {:?}", node_path))?;
1188
1189    if !output.status.success() {
1190        anyhow::bail!(
1191            "failed to run node --version for Copilot. stdout: {}, stderr: {}",
1192            String::from_utf8_lossy(&output.stdout),
1193            String::from_utf8_lossy(&output.stderr),
1194        );
1195    }
1196
1197    let version_str = String::from_utf8_lossy(&output.stdout);
1198    let version = Version::parse(version_str.trim().trim_start_matches('v'))
1199        .with_context(|| format!("parsing Node.js version from '{}'", version_str.trim()))?;
1200
1201    if version < MIN_COPILOT_NODE_VERSION {
1202        anyhow::bail!(
1203            "GitHub Copilot language server requires Node.js {MIN_COPILOT_NODE_VERSION} or later, but found {version}. \
1204            Please update your Node.js version or configure a different Node.js path in settings."
1205        );
1206    }
1207
1208    log::info!(
1209        "Node.js version {} meets Copilot requirements (>= {})",
1210        version,
1211        MIN_COPILOT_NODE_VERSION
1212    );
1213    Ok(())
1214}
1215
1216async fn get_copilot_lsp(fs: Arc<dyn Fs>, node_runtime: NodeRuntime) -> anyhow::Result<PathBuf> {
1217    const PACKAGE_NAME: &str = "@github/copilot-language-server";
1218    const SERVER_PATH: &str =
1219        "node_modules/@github/copilot-language-server/dist/language-server.js";
1220
1221    let latest_version = node_runtime
1222        .npm_package_latest_version(PACKAGE_NAME)
1223        .await?;
1224    let server_path = paths::copilot_dir().join(SERVER_PATH);
1225
1226    fs.create_dir(paths::copilot_dir()).await?;
1227
1228    let should_install = node_runtime
1229        .should_install_npm_package(
1230            PACKAGE_NAME,
1231            &server_path,
1232            paths::copilot_dir(),
1233            VersionStrategy::Latest(&latest_version),
1234        )
1235        .await;
1236    if should_install {
1237        node_runtime
1238            .npm_install_packages(paths::copilot_dir(), &[(PACKAGE_NAME, &latest_version)])
1239            .await?;
1240    }
1241
1242    Ok(server_path)
1243}
1244
1245#[cfg(test)]
1246mod tests {
1247    use super::*;
1248    use gpui::TestAppContext;
1249    use util::{path, paths::PathStyle, rel_path::rel_path};
1250
1251    #[gpui::test(iterations = 10)]
1252    async fn test_buffer_management(cx: &mut TestAppContext) {
1253        let (copilot, mut lsp) = Copilot::fake(cx);
1254
1255        let buffer_1 = cx.new(|cx| Buffer::local("Hello", cx));
1256        let buffer_1_uri: lsp::Uri = format!("buffer://{}", buffer_1.entity_id().as_u64())
1257            .parse()
1258            .unwrap();
1259        copilot.update(cx, |copilot, cx| copilot.register_buffer(&buffer_1, cx));
1260        assert_eq!(
1261            lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1262                .await,
1263            lsp::DidOpenTextDocumentParams {
1264                text_document: lsp::TextDocumentItem::new(
1265                    buffer_1_uri.clone(),
1266                    "plaintext".into(),
1267                    0,
1268                    "Hello".into()
1269                ),
1270            }
1271        );
1272
1273        let buffer_2 = cx.new(|cx| Buffer::local("Goodbye", cx));
1274        let buffer_2_uri: lsp::Uri = format!("buffer://{}", buffer_2.entity_id().as_u64())
1275            .parse()
1276            .unwrap();
1277        copilot.update(cx, |copilot, cx| copilot.register_buffer(&buffer_2, cx));
1278        assert_eq!(
1279            lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1280                .await,
1281            lsp::DidOpenTextDocumentParams {
1282                text_document: lsp::TextDocumentItem::new(
1283                    buffer_2_uri.clone(),
1284                    "plaintext".into(),
1285                    0,
1286                    "Goodbye".into()
1287                ),
1288            }
1289        );
1290
1291        buffer_1.update(cx, |buffer, cx| buffer.edit([(5..5, " world")], None, cx));
1292        assert_eq!(
1293            lsp.receive_notification::<lsp::notification::DidChangeTextDocument>()
1294                .await,
1295            lsp::DidChangeTextDocumentParams {
1296                text_document: lsp::VersionedTextDocumentIdentifier::new(buffer_1_uri.clone(), 1),
1297                content_changes: vec![lsp::TextDocumentContentChangeEvent {
1298                    range: Some(lsp::Range::new(
1299                        lsp::Position::new(0, 5),
1300                        lsp::Position::new(0, 5)
1301                    )),
1302                    range_length: None,
1303                    text: " world".into(),
1304                }],
1305            }
1306        );
1307
1308        // Ensure updates to the file are reflected in the LSP.
1309        buffer_1.update(cx, |buffer, cx| {
1310            buffer.file_updated(
1311                Arc::new(File {
1312                    abs_path: path!("/root/child/buffer-1").into(),
1313                    path: rel_path("child/buffer-1").into(),
1314                }),
1315                cx,
1316            )
1317        });
1318        assert_eq!(
1319            lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1320                .await,
1321            lsp::DidCloseTextDocumentParams {
1322                text_document: lsp::TextDocumentIdentifier::new(buffer_1_uri),
1323            }
1324        );
1325        let buffer_1_uri = lsp::Uri::from_file_path(path!("/root/child/buffer-1")).unwrap();
1326        assert_eq!(
1327            lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1328                .await,
1329            lsp::DidOpenTextDocumentParams {
1330                text_document: lsp::TextDocumentItem::new(
1331                    buffer_1_uri.clone(),
1332                    "plaintext".into(),
1333                    1,
1334                    "Hello world".into()
1335                ),
1336            }
1337        );
1338
1339        // Ensure all previously-registered buffers are closed when signing out.
1340        lsp.set_request_handler::<request::SignOut, _, _>(|_, _| async {
1341            Ok(request::SignOutResult {})
1342        });
1343        copilot
1344            .update(cx, |copilot, cx| copilot.sign_out(cx))
1345            .await
1346            .unwrap();
1347        assert_eq!(
1348            lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1349                .await,
1350            lsp::DidCloseTextDocumentParams {
1351                text_document: lsp::TextDocumentIdentifier::new(buffer_1_uri.clone()),
1352            }
1353        );
1354        assert_eq!(
1355            lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1356                .await,
1357            lsp::DidCloseTextDocumentParams {
1358                text_document: lsp::TextDocumentIdentifier::new(buffer_2_uri.clone()),
1359            }
1360        );
1361
1362        // Ensure all previously-registered buffers are re-opened when signing in.
1363        lsp.set_request_handler::<request::SignInInitiate, _, _>(|_, _| async {
1364            Ok(request::SignInInitiateResult::AlreadySignedIn {
1365                user: "user-1".into(),
1366            })
1367        });
1368        copilot
1369            .update(cx, |copilot, cx| copilot.sign_in(cx))
1370            .await
1371            .unwrap();
1372
1373        assert_eq!(
1374            lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1375                .await,
1376            lsp::DidOpenTextDocumentParams {
1377                text_document: lsp::TextDocumentItem::new(
1378                    buffer_1_uri.clone(),
1379                    "plaintext".into(),
1380                    0,
1381                    "Hello world".into()
1382                ),
1383            }
1384        );
1385        assert_eq!(
1386            lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1387                .await,
1388            lsp::DidOpenTextDocumentParams {
1389                text_document: lsp::TextDocumentItem::new(
1390                    buffer_2_uri.clone(),
1391                    "plaintext".into(),
1392                    0,
1393                    "Goodbye".into()
1394                ),
1395            }
1396        );
1397        // Dropping a buffer causes it to be closed on the LSP side as well.
1398        cx.update(|_| drop(buffer_2));
1399        assert_eq!(
1400            lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1401                .await,
1402            lsp::DidCloseTextDocumentParams {
1403                text_document: lsp::TextDocumentIdentifier::new(buffer_2_uri),
1404            }
1405        );
1406    }
1407
1408    struct File {
1409        abs_path: PathBuf,
1410        path: Arc<RelPath>,
1411    }
1412
1413    impl language::File for File {
1414        fn as_local(&self) -> Option<&dyn language::LocalFile> {
1415            Some(self)
1416        }
1417
1418        fn disk_state(&self) -> language::DiskState {
1419            language::DiskState::Present {
1420                mtime: ::fs::MTime::from_seconds_and_nanos(100, 42),
1421            }
1422        }
1423
1424        fn path(&self) -> &Arc<RelPath> {
1425            &self.path
1426        }
1427
1428        fn path_style(&self, _: &App) -> PathStyle {
1429            PathStyle::local()
1430        }
1431
1432        fn full_path(&self, _: &App) -> PathBuf {
1433            unimplemented!()
1434        }
1435
1436        fn file_name<'a>(&'a self, _: &'a App) -> &'a str {
1437            unimplemented!()
1438        }
1439
1440        fn to_proto(&self, _: &App) -> rpc::proto::File {
1441            unimplemented!()
1442        }
1443
1444        fn worktree_id(&self, _: &App) -> settings::WorktreeId {
1445            settings::WorktreeId::from_usize(0)
1446        }
1447
1448        fn is_private(&self) -> bool {
1449            false
1450        }
1451    }
1452
1453    impl language::LocalFile for File {
1454        fn abs_path(&self, _: &App) -> PathBuf {
1455            self.abs_path.clone()
1456        }
1457
1458        fn load(&self, _: &App) -> Task<Result<String>> {
1459            unimplemented!()
1460        }
1461
1462        fn load_bytes(&self, _cx: &App) -> Task<Result<Vec<u8>>> {
1463            unimplemented!()
1464        }
1465    }
1466}
1467
1468#[cfg(test)]
1469#[ctor::ctor]
1470fn init_logger() {
1471    zlog::init_test();
1472}