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 fn is_authorized(&self) -> bool {
 187        matches!(self, Status::Authorized)
 188    }
 189
 190    pub 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 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                }
 803                language::BufferEvent::FileHandleChanged
 804                | language::BufferEvent::LanguageChanged => {
 805                    let new_language_id = id_for_language(buffer.read(cx).language());
 806                    let Ok(new_uri) = uri_for_buffer(&buffer, cx) else {
 807                        return Ok(());
 808                    };
 809                    if new_uri != registered_buffer.uri
 810                        || new_language_id != registered_buffer.language_id
 811                    {
 812                        let old_uri = mem::replace(&mut registered_buffer.uri, new_uri);
 813                        registered_buffer.language_id = new_language_id;
 814                        server
 815                            .lsp
 816                            .notify::<lsp::notification::DidCloseTextDocument>(
 817                                &lsp::DidCloseTextDocumentParams {
 818                                    text_document: lsp::TextDocumentIdentifier::new(old_uri),
 819                                },
 820                            )?;
 821                        server
 822                            .lsp
 823                            .notify::<lsp::notification::DidOpenTextDocument>(
 824                                &lsp::DidOpenTextDocumentParams {
 825                                    text_document: lsp::TextDocumentItem::new(
 826                                        registered_buffer.uri.clone(),
 827                                        registered_buffer.language_id.clone(),
 828                                        registered_buffer.snapshot_version,
 829                                        registered_buffer.snapshot.text(),
 830                                    ),
 831                                },
 832                            )?;
 833                    }
 834                }
 835                _ => {}
 836            }
 837        }
 838
 839        Ok(())
 840    }
 841
 842    fn unregister_buffer(&mut self, buffer: &WeakEntity<Buffer>) {
 843        if let Ok(server) = self.server.as_running()
 844            && let Some(buffer) = server.registered_buffers.remove(&buffer.entity_id())
 845        {
 846            server
 847                .lsp
 848                .notify::<lsp::notification::DidCloseTextDocument>(
 849                    &lsp::DidCloseTextDocumentParams {
 850                        text_document: lsp::TextDocumentIdentifier::new(buffer.uri),
 851                    },
 852                )
 853                .ok();
 854        }
 855    }
 856
 857    pub fn completions<T>(
 858        &mut self,
 859        buffer: &Entity<Buffer>,
 860        position: T,
 861        cx: &mut Context<Self>,
 862    ) -> Task<Result<Vec<Completion>>>
 863    where
 864        T: ToPointUtf16,
 865    {
 866        self.request_completions::<request::GetCompletions, _>(buffer, position, cx)
 867    }
 868
 869    pub fn completions_cycling<T>(
 870        &mut self,
 871        buffer: &Entity<Buffer>,
 872        position: T,
 873        cx: &mut Context<Self>,
 874    ) -> Task<Result<Vec<Completion>>>
 875    where
 876        T: ToPointUtf16,
 877    {
 878        self.request_completions::<request::GetCompletionsCycling, _>(buffer, position, cx)
 879    }
 880
 881    pub fn accept_completion(
 882        &mut self,
 883        completion: &Completion,
 884        cx: &mut Context<Self>,
 885    ) -> Task<Result<()>> {
 886        let server = match self.server.as_authenticated() {
 887            Ok(server) => server,
 888            Err(error) => return Task::ready(Err(error)),
 889        };
 890        let request =
 891            server
 892                .lsp
 893                .request::<request::NotifyAccepted>(request::NotifyAcceptedParams {
 894                    uuid: completion.uuid.clone(),
 895                });
 896        cx.background_spawn(async move {
 897            request
 898                .await
 899                .into_response()
 900                .context("copilot: notify accepted")?;
 901            Ok(())
 902        })
 903    }
 904
 905    pub fn discard_completions(
 906        &mut self,
 907        completions: &[Completion],
 908        cx: &mut Context<Self>,
 909    ) -> Task<Result<()>> {
 910        let server = match self.server.as_authenticated() {
 911            Ok(server) => server,
 912            Err(_) => return Task::ready(Ok(())),
 913        };
 914        let request =
 915            server
 916                .lsp
 917                .request::<request::NotifyRejected>(request::NotifyRejectedParams {
 918                    uuids: completions
 919                        .iter()
 920                        .map(|completion| completion.uuid.clone())
 921                        .collect(),
 922                });
 923        cx.background_spawn(async move {
 924            request
 925                .await
 926                .into_response()
 927                .context("copilot: notify rejected")?;
 928            Ok(())
 929        })
 930    }
 931
 932    fn request_completions<R, T>(
 933        &mut self,
 934        buffer: &Entity<Buffer>,
 935        position: T,
 936        cx: &mut Context<Self>,
 937    ) -> Task<Result<Vec<Completion>>>
 938    where
 939        R: 'static
 940            + lsp::request::Request<
 941                Params = request::GetCompletionsParams,
 942                Result = request::GetCompletionsResult,
 943            >,
 944        T: ToPointUtf16,
 945    {
 946        self.register_buffer(buffer, cx);
 947
 948        let server = match self.server.as_authenticated() {
 949            Ok(server) => server,
 950            Err(error) => return Task::ready(Err(error)),
 951        };
 952        let lsp = server.lsp.clone();
 953        let registered_buffer = server
 954            .registered_buffers
 955            .get_mut(&buffer.entity_id())
 956            .unwrap();
 957        let snapshot = registered_buffer.report_changes(buffer, cx);
 958        let buffer = buffer.read(cx);
 959        let uri = registered_buffer.uri.clone();
 960        let position = position.to_point_utf16(buffer);
 961        let settings = language_settings(
 962            buffer.language_at(position).map(|l| l.name()),
 963            buffer.file(),
 964            cx,
 965        );
 966        let tab_size = settings.tab_size;
 967        let hard_tabs = settings.hard_tabs;
 968        let relative_path = buffer
 969            .file()
 970            .map_or(RelPath::empty().into(), |file| file.path().clone());
 971
 972        cx.background_spawn(async move {
 973            let (version, snapshot) = snapshot.await?;
 974            let result = lsp
 975                .request::<R>(request::GetCompletionsParams {
 976                    doc: request::GetCompletionsDocument {
 977                        uri,
 978                        tab_size: tab_size.into(),
 979                        indent_size: 1,
 980                        insert_spaces: !hard_tabs,
 981                        relative_path: relative_path.to_proto(),
 982                        position: point_to_lsp(position),
 983                        version: version.try_into().unwrap(),
 984                    },
 985                })
 986                .await
 987                .into_response()
 988                .context("copilot: get completions")?;
 989            let completions = result
 990                .completions
 991                .into_iter()
 992                .map(|completion| {
 993                    let start = snapshot
 994                        .clip_point_utf16(point_from_lsp(completion.range.start), Bias::Left);
 995                    let end =
 996                        snapshot.clip_point_utf16(point_from_lsp(completion.range.end), Bias::Left);
 997                    Completion {
 998                        uuid: completion.uuid,
 999                        range: snapshot.anchor_before(start)..snapshot.anchor_after(end),
1000                        text: completion.text,
1001                    }
1002                })
1003                .collect();
1004            anyhow::Ok(completions)
1005        })
1006    }
1007
1008    pub fn status(&self) -> Status {
1009        match &self.server {
1010            CopilotServer::Starting { task } => Status::Starting { task: task.clone() },
1011            CopilotServer::Disabled => Status::Disabled,
1012            CopilotServer::Error(error) => Status::Error(error.clone()),
1013            CopilotServer::Running(RunningCopilotServer { sign_in_status, .. }) => {
1014                match sign_in_status {
1015                    SignInStatus::Authorized => Status::Authorized,
1016                    SignInStatus::Unauthorized => Status::Unauthorized,
1017                    SignInStatus::SigningIn { prompt, .. } => Status::SigningIn {
1018                        prompt: prompt.clone(),
1019                    },
1020                    SignInStatus::SignedOut {
1021                        awaiting_signing_in,
1022                    } => Status::SignedOut {
1023                        awaiting_signing_in: *awaiting_signing_in,
1024                    },
1025                }
1026            }
1027        }
1028    }
1029
1030    fn update_sign_in_status(&mut self, lsp_status: request::SignInStatus, cx: &mut Context<Self>) {
1031        self.buffers.retain(|buffer| buffer.is_upgradable());
1032
1033        if let Ok(server) = self.server.as_running() {
1034            match lsp_status {
1035                request::SignInStatus::Ok { user: Some(_) }
1036                | request::SignInStatus::MaybeOk { .. }
1037                | request::SignInStatus::AlreadySignedIn { .. } => {
1038                    server.sign_in_status = SignInStatus::Authorized;
1039                    cx.emit(Event::CopilotAuthSignedIn);
1040                    for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1041                        if let Some(buffer) = buffer.upgrade() {
1042                            self.register_buffer(&buffer, cx);
1043                        }
1044                    }
1045                }
1046                request::SignInStatus::NotAuthorized { .. } => {
1047                    server.sign_in_status = SignInStatus::Unauthorized;
1048                    for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1049                        self.unregister_buffer(&buffer);
1050                    }
1051                }
1052                request::SignInStatus::Ok { user: None } | request::SignInStatus::NotSignedIn => {
1053                    if !matches!(server.sign_in_status, SignInStatus::SignedOut { .. }) {
1054                        server.sign_in_status = SignInStatus::SignedOut {
1055                            awaiting_signing_in: false,
1056                        };
1057                    }
1058                    cx.emit(Event::CopilotAuthSignedOut);
1059                    for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1060                        self.unregister_buffer(&buffer);
1061                    }
1062                }
1063            }
1064
1065            cx.notify();
1066        }
1067    }
1068
1069    fn update_action_visibilities(&self, cx: &mut App) {
1070        let signed_in_actions = [
1071            TypeId::of::<Suggest>(),
1072            TypeId::of::<NextSuggestion>(),
1073            TypeId::of::<PreviousSuggestion>(),
1074            TypeId::of::<Reinstall>(),
1075        ];
1076        let auth_actions = [TypeId::of::<SignOut>()];
1077        let no_auth_actions = [TypeId::of::<SignIn>()];
1078        let status = self.status();
1079
1080        let is_ai_disabled = DisableAiSettings::get_global(cx).disable_ai;
1081        let filter = CommandPaletteFilter::global_mut(cx);
1082
1083        if is_ai_disabled {
1084            filter.hide_action_types(&signed_in_actions);
1085            filter.hide_action_types(&auth_actions);
1086            filter.hide_action_types(&no_auth_actions);
1087        } else {
1088            match status {
1089                Status::Disabled => {
1090                    filter.hide_action_types(&signed_in_actions);
1091                    filter.hide_action_types(&auth_actions);
1092                    filter.hide_action_types(&no_auth_actions);
1093                }
1094                Status::Authorized => {
1095                    filter.hide_action_types(&no_auth_actions);
1096                    filter.show_action_types(signed_in_actions.iter().chain(&auth_actions));
1097                }
1098                _ => {
1099                    filter.hide_action_types(&signed_in_actions);
1100                    filter.hide_action_types(&auth_actions);
1101                    filter.show_action_types(&no_auth_actions);
1102                }
1103            }
1104        }
1105    }
1106}
1107
1108fn id_for_language(language: Option<&Arc<Language>>) -> String {
1109    language
1110        .map(|language| language.lsp_id())
1111        .unwrap_or_else(|| "plaintext".to_string())
1112}
1113
1114fn uri_for_buffer(buffer: &Entity<Buffer>, cx: &App) -> Result<lsp::Uri, ()> {
1115    if let Some(file) = buffer.read(cx).file().and_then(|file| file.as_local()) {
1116        lsp::Uri::from_file_path(file.abs_path(cx))
1117    } else {
1118        format!("buffer://{}", buffer.entity_id())
1119            .parse()
1120            .map_err(|_| ())
1121    }
1122}
1123
1124fn notify_did_change_config_to_server(
1125    server: &Arc<LanguageServer>,
1126    cx: &mut Context<Copilot>,
1127) -> std::result::Result<(), anyhow::Error> {
1128    let copilot_settings = all_language_settings(None, cx)
1129        .edit_predictions
1130        .copilot
1131        .clone();
1132
1133    if let Some(copilot_chat) = copilot_chat::CopilotChat::global(cx) {
1134        copilot_chat.update(cx, |chat, cx| {
1135            chat.set_configuration(
1136                copilot_chat::CopilotChatConfiguration {
1137                    enterprise_uri: copilot_settings.enterprise_uri.clone(),
1138                },
1139                cx,
1140            );
1141        });
1142    }
1143
1144    let settings = json!({
1145        "http": {
1146            "proxy": copilot_settings.proxy,
1147            "proxyStrictSSL": !copilot_settings.proxy_no_verify.unwrap_or(false)
1148        },
1149        "github-enterprise": {
1150            "uri": copilot_settings.enterprise_uri
1151        }
1152    });
1153
1154    server.notify::<lsp::notification::DidChangeConfiguration>(&lsp::DidChangeConfigurationParams {
1155        settings,
1156    })
1157}
1158
1159async fn clear_copilot_dir() {
1160    remove_matching(paths::copilot_dir(), |_| true).await
1161}
1162
1163async fn clear_copilot_config_dir() {
1164    remove_matching(copilot_chat::copilot_chat_config_dir(), |_| true).await
1165}
1166
1167async fn ensure_node_version_for_copilot(node_path: &Path) -> anyhow::Result<()> {
1168    const MIN_COPILOT_NODE_VERSION: Version = Version::new(20, 8, 0);
1169
1170    log::info!("Checking Node.js version for Copilot at: {:?}", node_path);
1171
1172    let output = util::command::new_smol_command(node_path)
1173        .arg("--version")
1174        .output()
1175        .await
1176        .with_context(|| format!("checking Node.js version at {:?}", node_path))?;
1177
1178    if !output.status.success() {
1179        anyhow::bail!(
1180            "failed to run node --version for Copilot. stdout: {}, stderr: {}",
1181            String::from_utf8_lossy(&output.stdout),
1182            String::from_utf8_lossy(&output.stderr),
1183        );
1184    }
1185
1186    let version_str = String::from_utf8_lossy(&output.stdout);
1187    let version = Version::parse(version_str.trim().trim_start_matches('v'))
1188        .with_context(|| format!("parsing Node.js version from '{}'", version_str.trim()))?;
1189
1190    if version < MIN_COPILOT_NODE_VERSION {
1191        anyhow::bail!(
1192            "GitHub Copilot language server requires Node.js {MIN_COPILOT_NODE_VERSION} or later, but found {version}. \
1193            Please update your Node.js version or configure a different Node.js path in settings."
1194        );
1195    }
1196
1197    log::info!(
1198        "Node.js version {} meets Copilot requirements (>= {})",
1199        version,
1200        MIN_COPILOT_NODE_VERSION
1201    );
1202    Ok(())
1203}
1204
1205async fn get_copilot_lsp(fs: Arc<dyn Fs>, node_runtime: NodeRuntime) -> anyhow::Result<PathBuf> {
1206    const PACKAGE_NAME: &str = "@github/copilot-language-server";
1207    const SERVER_PATH: &str =
1208        "node_modules/@github/copilot-language-server/dist/language-server.js";
1209
1210    let latest_version = node_runtime
1211        .npm_package_latest_version(PACKAGE_NAME)
1212        .await?;
1213    let server_path = paths::copilot_dir().join(SERVER_PATH);
1214
1215    fs.create_dir(paths::copilot_dir()).await?;
1216
1217    let should_install = node_runtime
1218        .should_install_npm_package(
1219            PACKAGE_NAME,
1220            &server_path,
1221            paths::copilot_dir(),
1222            VersionStrategy::Latest(&latest_version),
1223        )
1224        .await;
1225    if should_install {
1226        node_runtime
1227            .npm_install_packages(paths::copilot_dir(), &[(PACKAGE_NAME, &latest_version)])
1228            .await?;
1229    }
1230
1231    Ok(server_path)
1232}
1233
1234#[cfg(test)]
1235mod tests {
1236    use super::*;
1237    use gpui::TestAppContext;
1238    use util::{path, paths::PathStyle, rel_path::rel_path};
1239
1240    #[gpui::test(iterations = 10)]
1241    async fn test_buffer_management(cx: &mut TestAppContext) {
1242        let (copilot, mut lsp) = Copilot::fake(cx);
1243
1244        let buffer_1 = cx.new(|cx| Buffer::local("Hello", cx));
1245        let buffer_1_uri: lsp::Uri = format!("buffer://{}", buffer_1.entity_id().as_u64())
1246            .parse()
1247            .unwrap();
1248        copilot.update(cx, |copilot, cx| copilot.register_buffer(&buffer_1, cx));
1249        assert_eq!(
1250            lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1251                .await,
1252            lsp::DidOpenTextDocumentParams {
1253                text_document: lsp::TextDocumentItem::new(
1254                    buffer_1_uri.clone(),
1255                    "plaintext".into(),
1256                    0,
1257                    "Hello".into()
1258                ),
1259            }
1260        );
1261
1262        let buffer_2 = cx.new(|cx| Buffer::local("Goodbye", cx));
1263        let buffer_2_uri: lsp::Uri = format!("buffer://{}", buffer_2.entity_id().as_u64())
1264            .parse()
1265            .unwrap();
1266        copilot.update(cx, |copilot, cx| copilot.register_buffer(&buffer_2, cx));
1267        assert_eq!(
1268            lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1269                .await,
1270            lsp::DidOpenTextDocumentParams {
1271                text_document: lsp::TextDocumentItem::new(
1272                    buffer_2_uri.clone(),
1273                    "plaintext".into(),
1274                    0,
1275                    "Goodbye".into()
1276                ),
1277            }
1278        );
1279
1280        buffer_1.update(cx, |buffer, cx| buffer.edit([(5..5, " world")], None, cx));
1281        assert_eq!(
1282            lsp.receive_notification::<lsp::notification::DidChangeTextDocument>()
1283                .await,
1284            lsp::DidChangeTextDocumentParams {
1285                text_document: lsp::VersionedTextDocumentIdentifier::new(buffer_1_uri.clone(), 1),
1286                content_changes: vec![lsp::TextDocumentContentChangeEvent {
1287                    range: Some(lsp::Range::new(
1288                        lsp::Position::new(0, 5),
1289                        lsp::Position::new(0, 5)
1290                    )),
1291                    range_length: None,
1292                    text: " world".into(),
1293                }],
1294            }
1295        );
1296
1297        // Ensure updates to the file are reflected in the LSP.
1298        buffer_1.update(cx, |buffer, cx| {
1299            buffer.file_updated(
1300                Arc::new(File {
1301                    abs_path: path!("/root/child/buffer-1").into(),
1302                    path: rel_path("child/buffer-1").into(),
1303                }),
1304                cx,
1305            )
1306        });
1307        assert_eq!(
1308            lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1309                .await,
1310            lsp::DidCloseTextDocumentParams {
1311                text_document: lsp::TextDocumentIdentifier::new(buffer_1_uri),
1312            }
1313        );
1314        let buffer_1_uri = lsp::Uri::from_file_path(path!("/root/child/buffer-1")).unwrap();
1315        assert_eq!(
1316            lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1317                .await,
1318            lsp::DidOpenTextDocumentParams {
1319                text_document: lsp::TextDocumentItem::new(
1320                    buffer_1_uri.clone(),
1321                    "plaintext".into(),
1322                    1,
1323                    "Hello world".into()
1324                ),
1325            }
1326        );
1327
1328        // Ensure all previously-registered buffers are closed when signing out.
1329        lsp.set_request_handler::<request::SignOut, _, _>(|_, _| async {
1330            Ok(request::SignOutResult {})
1331        });
1332        copilot
1333            .update(cx, |copilot, cx| copilot.sign_out(cx))
1334            .await
1335            .unwrap();
1336        assert_eq!(
1337            lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1338                .await,
1339            lsp::DidCloseTextDocumentParams {
1340                text_document: lsp::TextDocumentIdentifier::new(buffer_1_uri.clone()),
1341            }
1342        );
1343        assert_eq!(
1344            lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1345                .await,
1346            lsp::DidCloseTextDocumentParams {
1347                text_document: lsp::TextDocumentIdentifier::new(buffer_2_uri.clone()),
1348            }
1349        );
1350
1351        // Ensure all previously-registered buffers are re-opened when signing in.
1352        lsp.set_request_handler::<request::SignInInitiate, _, _>(|_, _| async {
1353            Ok(request::SignInInitiateResult::AlreadySignedIn {
1354                user: "user-1".into(),
1355            })
1356        });
1357        copilot
1358            .update(cx, |copilot, cx| copilot.sign_in(cx))
1359            .await
1360            .unwrap();
1361
1362        assert_eq!(
1363            lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1364                .await,
1365            lsp::DidOpenTextDocumentParams {
1366                text_document: lsp::TextDocumentItem::new(
1367                    buffer_1_uri.clone(),
1368                    "plaintext".into(),
1369                    0,
1370                    "Hello world".into()
1371                ),
1372            }
1373        );
1374        assert_eq!(
1375            lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1376                .await,
1377            lsp::DidOpenTextDocumentParams {
1378                text_document: lsp::TextDocumentItem::new(
1379                    buffer_2_uri.clone(),
1380                    "plaintext".into(),
1381                    0,
1382                    "Goodbye".into()
1383                ),
1384            }
1385        );
1386        // Dropping a buffer causes it to be closed on the LSP side as well.
1387        cx.update(|_| drop(buffer_2));
1388        assert_eq!(
1389            lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1390                .await,
1391            lsp::DidCloseTextDocumentParams {
1392                text_document: lsp::TextDocumentIdentifier::new(buffer_2_uri),
1393            }
1394        );
1395    }
1396
1397    struct File {
1398        abs_path: PathBuf,
1399        path: Arc<RelPath>,
1400    }
1401
1402    impl language::File for File {
1403        fn as_local(&self) -> Option<&dyn language::LocalFile> {
1404            Some(self)
1405        }
1406
1407        fn disk_state(&self) -> language::DiskState {
1408            language::DiskState::Present {
1409                mtime: ::fs::MTime::from_seconds_and_nanos(100, 42),
1410            }
1411        }
1412
1413        fn path(&self) -> &Arc<RelPath> {
1414            &self.path
1415        }
1416
1417        fn path_style(&self, _: &App) -> PathStyle {
1418            PathStyle::local()
1419        }
1420
1421        fn full_path(&self, _: &App) -> PathBuf {
1422            unimplemented!()
1423        }
1424
1425        fn file_name<'a>(&'a self, _: &'a App) -> &'a str {
1426            unimplemented!()
1427        }
1428
1429        fn to_proto(&self, _: &App) -> rpc::proto::File {
1430            unimplemented!()
1431        }
1432
1433        fn worktree_id(&self, _: &App) -> settings::WorktreeId {
1434            settings::WorktreeId::from_usize(0)
1435        }
1436
1437        fn is_private(&self) -> bool {
1438            false
1439        }
1440    }
1441
1442    impl language::LocalFile for File {
1443        fn abs_path(&self, _: &App) -> PathBuf {
1444            self.abs_path.clone()
1445        }
1446
1447        fn load(&self, _: &App) -> Task<Result<String>> {
1448            unimplemented!()
1449        }
1450
1451        fn load_bytes(&self, _cx: &App) -> Task<Result<Vec<u8>>> {
1452            unimplemented!()
1453        }
1454    }
1455}
1456
1457#[cfg(test)]
1458#[ctor::ctor]
1459fn init_logger() {
1460    zlog::init_test();
1461}