copilot.rs

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