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