copilot.rs

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