copilot.rs

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