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