copilot.rs

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