copilot.rs

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