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_executor()
 238                    .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        if all_language_settings(None, cx).edit_predictions.provider
 372            == EditPredictionProvider::Copilot
 373        {
 374            if matches!(self.server, CopilotServer::Disabled) {
 375                let start_task = cx
 376                    .spawn(move |this, cx| {
 377                        Self::start_language_server(server_id, http, node_runtime, 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    #[cfg(any(test, feature = "test-support"))]
 390    pub fn fake(cx: &mut gpui::TestAppContext) -> (Entity<Self>, lsp::FakeLanguageServer) {
 391        use lsp::FakeLanguageServer;
 392        use node_runtime::NodeRuntime;
 393
 394        let (server, fake_server) = FakeLanguageServer::new(
 395            LanguageServerId(0),
 396            LanguageServerBinary {
 397                path: "path/to/copilot".into(),
 398                arguments: vec![],
 399                env: None,
 400            },
 401            "copilot".into(),
 402            Default::default(),
 403            cx.to_async(),
 404        );
 405        let http = http_client::FakeHttpClient::create(|_| async { unreachable!() });
 406        let node_runtime = NodeRuntime::unavailable();
 407        let this = cx.new(|cx| Self {
 408            server_id: LanguageServerId(0),
 409            http: http.clone(),
 410            node_runtime,
 411            server: CopilotServer::Running(RunningCopilotServer {
 412                lsp: Arc::new(server),
 413                sign_in_status: SignInStatus::Authorized,
 414                registered_buffers: Default::default(),
 415            }),
 416            _subscription: cx.on_app_quit(Self::shutdown_language_server),
 417            buffers: Default::default(),
 418        });
 419        (this, fake_server)
 420    }
 421
 422    async fn start_language_server(
 423        new_server_id: LanguageServerId,
 424        http: Arc<dyn HttpClient>,
 425        node_runtime: NodeRuntime,
 426        this: WeakEntity<Self>,
 427        mut cx: AsyncApp,
 428    ) {
 429        let start_language_server = async {
 430            let server_path = get_copilot_lsp(http).await?;
 431            let node_path = node_runtime.binary_path().await?;
 432            let arguments: Vec<OsString> = vec![server_path.into(), "--stdio".into()];
 433            let binary = LanguageServerBinary {
 434                path: node_path,
 435                arguments,
 436                // TODO: We could set HTTP_PROXY etc here and fix the copilot issue.
 437                env: None,
 438            };
 439
 440            let root_path = if cfg!(target_os = "windows") {
 441                Path::new("C:/")
 442            } else {
 443                Path::new("/")
 444            };
 445
 446            let server_name = LanguageServerName("copilot".into());
 447            let server = LanguageServer::new(
 448                Arc::new(Mutex::new(None)),
 449                new_server_id,
 450                server_name,
 451                binary,
 452                root_path,
 453                None,
 454                cx.clone(),
 455            )?;
 456
 457            server
 458                .on_notification::<StatusNotification, _>(|_, _| { /* Silence the notification */ })
 459                .detach();
 460
 461            let configuration = lsp::DidChangeConfigurationParams {
 462                settings: Default::default(),
 463            };
 464            let server = cx
 465                .update(|cx| {
 466                    let params = server.default_initialize_params(cx);
 467                    server.initialize(params, configuration.into(), cx)
 468                })?
 469                .await?;
 470
 471            let status = server
 472                .request::<request::CheckStatus>(request::CheckStatusParams {
 473                    local_checks_only: false,
 474                })
 475                .await?;
 476
 477            server
 478                .request::<request::SetEditorInfo>(request::SetEditorInfoParams {
 479                    editor_info: request::EditorInfo {
 480                        name: "zed".into(),
 481                        version: env!("CARGO_PKG_VERSION").into(),
 482                    },
 483                    editor_plugin_info: request::EditorPluginInfo {
 484                        name: "zed-copilot".into(),
 485                        version: "0.0.1".into(),
 486                    },
 487                })
 488                .await?;
 489
 490            anyhow::Ok((server, status))
 491        };
 492
 493        let server = start_language_server.await;
 494        this.update(&mut cx, |this, cx| {
 495            cx.notify();
 496            match server {
 497                Ok((server, status)) => {
 498                    this.server = CopilotServer::Running(RunningCopilotServer {
 499                        lsp: server,
 500                        sign_in_status: SignInStatus::SignedOut,
 501                        registered_buffers: Default::default(),
 502                    });
 503                    cx.emit(Event::CopilotLanguageServerStarted);
 504                    this.update_sign_in_status(status, cx);
 505                }
 506                Err(error) => {
 507                    this.server = CopilotServer::Error(error.to_string().into());
 508                    cx.notify()
 509                }
 510            }
 511        })
 512        .ok();
 513    }
 514
 515    pub fn sign_in(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
 516        if let CopilotServer::Running(server) = &mut self.server {
 517            let task = match &server.sign_in_status {
 518                SignInStatus::Authorized { .. } => Task::ready(Ok(())).shared(),
 519                SignInStatus::SigningIn { task, .. } => {
 520                    cx.notify();
 521                    task.clone()
 522                }
 523                SignInStatus::SignedOut | SignInStatus::Unauthorized { .. } => {
 524                    let lsp = server.lsp.clone();
 525                    let task = cx
 526                        .spawn(|this, mut cx| async move {
 527                            let sign_in = async {
 528                                let sign_in = lsp
 529                                    .request::<request::SignInInitiate>(
 530                                        request::SignInInitiateParams {},
 531                                    )
 532                                    .await?;
 533                                match sign_in {
 534                                    request::SignInInitiateResult::AlreadySignedIn { user } => {
 535                                        Ok(request::SignInStatus::Ok { user: Some(user) })
 536                                    }
 537                                    request::SignInInitiateResult::PromptUserDeviceFlow(flow) => {
 538                                        this.update(&mut cx, |this, cx| {
 539                                            if let CopilotServer::Running(RunningCopilotServer {
 540                                                sign_in_status: status,
 541                                                ..
 542                                            }) = &mut this.server
 543                                            {
 544                                                if let SignInStatus::SigningIn {
 545                                                    prompt: prompt_flow,
 546                                                    ..
 547                                                } = status
 548                                                {
 549                                                    *prompt_flow = Some(flow.clone());
 550                                                    cx.notify();
 551                                                }
 552                                            }
 553                                        })?;
 554                                        let response = lsp
 555                                            .request::<request::SignInConfirm>(
 556                                                request::SignInConfirmParams {
 557                                                    user_code: flow.user_code,
 558                                                },
 559                                            )
 560                                            .await?;
 561                                        Ok(response)
 562                                    }
 563                                }
 564                            };
 565
 566                            let sign_in = sign_in.await;
 567                            this.update(&mut cx, |this, cx| match sign_in {
 568                                Ok(status) => {
 569                                    this.update_sign_in_status(status, cx);
 570                                    Ok(())
 571                                }
 572                                Err(error) => {
 573                                    this.update_sign_in_status(
 574                                        request::SignInStatus::NotSignedIn,
 575                                        cx,
 576                                    );
 577                                    Err(Arc::new(error))
 578                                }
 579                            })?
 580                        })
 581                        .shared();
 582                    server.sign_in_status = SignInStatus::SigningIn {
 583                        prompt: None,
 584                        task: task.clone(),
 585                    };
 586                    cx.notify();
 587                    task
 588                }
 589            };
 590
 591            cx.background_executor()
 592                .spawn(task.map_err(|err| anyhow!("{:?}", err)))
 593        } else {
 594            // If we're downloading, wait until download is finished
 595            // If we're in a stuck state, display to the user
 596            Task::ready(Err(anyhow!("copilot hasn't started yet")))
 597        }
 598    }
 599
 600    pub fn sign_out(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
 601        self.update_sign_in_status(request::SignInStatus::NotSignedIn, cx);
 602        if let CopilotServer::Running(RunningCopilotServer { lsp: server, .. }) = &self.server {
 603            let server = server.clone();
 604            cx.background_executor().spawn(async move {
 605                server
 606                    .request::<request::SignOut>(request::SignOutParams {})
 607                    .await?;
 608                anyhow::Ok(())
 609            })
 610        } else {
 611            Task::ready(Err(anyhow!("copilot hasn't started yet")))
 612        }
 613    }
 614
 615    pub fn reinstall(&mut self, cx: &mut Context<Self>) -> Task<()> {
 616        let start_task = cx
 617            .spawn({
 618                let http = self.http.clone();
 619                let node_runtime = self.node_runtime.clone();
 620                let server_id = self.server_id;
 621                move |this, cx| async move {
 622                    clear_copilot_dir().await;
 623                    Self::start_language_server(server_id, http, node_runtime, this, cx).await
 624                }
 625            })
 626            .shared();
 627
 628        self.server = CopilotServer::Starting {
 629            task: start_task.clone(),
 630        };
 631
 632        cx.notify();
 633
 634        cx.background_executor().spawn(start_task)
 635    }
 636
 637    pub fn language_server(&self) -> Option<&Arc<LanguageServer>> {
 638        if let CopilotServer::Running(server) = &self.server {
 639            Some(&server.lsp)
 640        } else {
 641            None
 642        }
 643    }
 644
 645    pub fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) {
 646        let weak_buffer = buffer.downgrade();
 647        self.buffers.insert(weak_buffer.clone());
 648
 649        if let CopilotServer::Running(RunningCopilotServer {
 650            lsp: server,
 651            sign_in_status: status,
 652            registered_buffers,
 653            ..
 654        }) = &mut self.server
 655        {
 656            if !matches!(status, SignInStatus::Authorized { .. }) {
 657                return;
 658            }
 659
 660            registered_buffers
 661                .entry(buffer.entity_id())
 662                .or_insert_with(|| {
 663                    let uri: lsp::Url = uri_for_buffer(buffer, cx);
 664                    let language_id = id_for_language(buffer.read(cx).language());
 665                    let snapshot = buffer.read(cx).snapshot();
 666                    server
 667                        .notify::<lsp::notification::DidOpenTextDocument>(
 668                            &lsp::DidOpenTextDocumentParams {
 669                                text_document: lsp::TextDocumentItem {
 670                                    uri: uri.clone(),
 671                                    language_id: language_id.clone(),
 672                                    version: 0,
 673                                    text: snapshot.text(),
 674                                },
 675                            },
 676                        )
 677                        .log_err();
 678
 679                    RegisteredBuffer {
 680                        uri,
 681                        language_id,
 682                        snapshot,
 683                        snapshot_version: 0,
 684                        pending_buffer_change: Task::ready(Some(())),
 685                        _subscriptions: [
 686                            cx.subscribe(buffer, |this, buffer, event, cx| {
 687                                this.handle_buffer_event(buffer, event, cx).log_err();
 688                            }),
 689                            cx.observe_release(buffer, move |this, _buffer, _cx| {
 690                                this.buffers.remove(&weak_buffer);
 691                                this.unregister_buffer(&weak_buffer);
 692                            }),
 693                        ],
 694                    }
 695                });
 696        }
 697    }
 698
 699    fn handle_buffer_event(
 700        &mut self,
 701        buffer: Entity<Buffer>,
 702        event: &language::BufferEvent,
 703        cx: &mut Context<Self>,
 704    ) -> Result<()> {
 705        if let Ok(server) = self.server.as_running() {
 706            if let Some(registered_buffer) = server.registered_buffers.get_mut(&buffer.entity_id())
 707            {
 708                match event {
 709                    language::BufferEvent::Edited => {
 710                        drop(registered_buffer.report_changes(&buffer, cx));
 711                    }
 712                    language::BufferEvent::Saved => {
 713                        server
 714                            .lsp
 715                            .notify::<lsp::notification::DidSaveTextDocument>(
 716                                &lsp::DidSaveTextDocumentParams {
 717                                    text_document: lsp::TextDocumentIdentifier::new(
 718                                        registered_buffer.uri.clone(),
 719                                    ),
 720                                    text: None,
 721                                },
 722                            )?;
 723                    }
 724                    language::BufferEvent::FileHandleChanged
 725                    | language::BufferEvent::LanguageChanged => {
 726                        let new_language_id = id_for_language(buffer.read(cx).language());
 727                        let new_uri = uri_for_buffer(&buffer, cx);
 728                        if new_uri != registered_buffer.uri
 729                            || new_language_id != registered_buffer.language_id
 730                        {
 731                            let old_uri = mem::replace(&mut registered_buffer.uri, new_uri);
 732                            registered_buffer.language_id = new_language_id;
 733                            server
 734                                .lsp
 735                                .notify::<lsp::notification::DidCloseTextDocument>(
 736                                    &lsp::DidCloseTextDocumentParams {
 737                                        text_document: lsp::TextDocumentIdentifier::new(old_uri),
 738                                    },
 739                                )?;
 740                            server
 741                                .lsp
 742                                .notify::<lsp::notification::DidOpenTextDocument>(
 743                                    &lsp::DidOpenTextDocumentParams {
 744                                        text_document: lsp::TextDocumentItem::new(
 745                                            registered_buffer.uri.clone(),
 746                                            registered_buffer.language_id.clone(),
 747                                            registered_buffer.snapshot_version,
 748                                            registered_buffer.snapshot.text(),
 749                                        ),
 750                                    },
 751                                )?;
 752                        }
 753                    }
 754                    _ => {}
 755                }
 756            }
 757        }
 758
 759        Ok(())
 760    }
 761
 762    fn unregister_buffer(&mut self, buffer: &WeakEntity<Buffer>) {
 763        if let Ok(server) = self.server.as_running() {
 764            if let Some(buffer) = server.registered_buffers.remove(&buffer.entity_id()) {
 765                server
 766                    .lsp
 767                    .notify::<lsp::notification::DidCloseTextDocument>(
 768                        &lsp::DidCloseTextDocumentParams {
 769                            text_document: lsp::TextDocumentIdentifier::new(buffer.uri),
 770                        },
 771                    )
 772                    .log_err();
 773            }
 774        }
 775    }
 776
 777    pub fn completions<T>(
 778        &mut self,
 779        buffer: &Entity<Buffer>,
 780        position: T,
 781        cx: &mut Context<Self>,
 782    ) -> Task<Result<Vec<Completion>>>
 783    where
 784        T: ToPointUtf16,
 785    {
 786        self.request_completions::<request::GetCompletions, _>(buffer, position, cx)
 787    }
 788
 789    pub fn completions_cycling<T>(
 790        &mut self,
 791        buffer: &Entity<Buffer>,
 792        position: T,
 793        cx: &mut Context<Self>,
 794    ) -> Task<Result<Vec<Completion>>>
 795    where
 796        T: ToPointUtf16,
 797    {
 798        self.request_completions::<request::GetCompletionsCycling, _>(buffer, position, cx)
 799    }
 800
 801    pub fn accept_completion(
 802        &mut self,
 803        completion: &Completion,
 804        cx: &mut Context<Self>,
 805    ) -> Task<Result<()>> {
 806        let server = match self.server.as_authenticated() {
 807            Ok(server) => server,
 808            Err(error) => return Task::ready(Err(error)),
 809        };
 810        let request =
 811            server
 812                .lsp
 813                .request::<request::NotifyAccepted>(request::NotifyAcceptedParams {
 814                    uuid: completion.uuid.clone(),
 815                });
 816        cx.background_executor().spawn(async move {
 817            request.await?;
 818            Ok(())
 819        })
 820    }
 821
 822    pub fn discard_completions(
 823        &mut self,
 824        completions: &[Completion],
 825        cx: &mut Context<Self>,
 826    ) -> Task<Result<()>> {
 827        let server = match self.server.as_authenticated() {
 828            Ok(server) => server,
 829            Err(_) => return Task::ready(Ok(())),
 830        };
 831        let request =
 832            server
 833                .lsp
 834                .request::<request::NotifyRejected>(request::NotifyRejectedParams {
 835                    uuids: completions
 836                        .iter()
 837                        .map(|completion| completion.uuid.clone())
 838                        .collect(),
 839                });
 840        cx.background_executor().spawn(async move {
 841            request.await?;
 842            Ok(())
 843        })
 844    }
 845
 846    fn request_completions<R, T>(
 847        &mut self,
 848        buffer: &Entity<Buffer>,
 849        position: T,
 850        cx: &mut Context<Self>,
 851    ) -> Task<Result<Vec<Completion>>>
 852    where
 853        R: 'static
 854            + lsp::request::Request<
 855                Params = request::GetCompletionsParams,
 856                Result = request::GetCompletionsResult,
 857            >,
 858        T: ToPointUtf16,
 859    {
 860        self.register_buffer(buffer, cx);
 861
 862        let server = match self.server.as_authenticated() {
 863            Ok(server) => server,
 864            Err(error) => return Task::ready(Err(error)),
 865        };
 866        let lsp = server.lsp.clone();
 867        let registered_buffer = server
 868            .registered_buffers
 869            .get_mut(&buffer.entity_id())
 870            .unwrap();
 871        let snapshot = registered_buffer.report_changes(buffer, cx);
 872        let buffer = buffer.read(cx);
 873        let uri = registered_buffer.uri.clone();
 874        let position = position.to_point_utf16(buffer);
 875        let settings = language_settings(
 876            buffer.language_at(position).map(|l| l.name()),
 877            buffer.file(),
 878            cx,
 879        );
 880        let tab_size = settings.tab_size;
 881        let hard_tabs = settings.hard_tabs;
 882        let relative_path = buffer
 883            .file()
 884            .map(|file| file.path().to_path_buf())
 885            .unwrap_or_default();
 886
 887        cx.background_executor().spawn(async move {
 888            let (version, snapshot) = snapshot.await?;
 889            let result = lsp
 890                .request::<R>(request::GetCompletionsParams {
 891                    doc: request::GetCompletionsDocument {
 892                        uri,
 893                        tab_size: tab_size.into(),
 894                        indent_size: 1,
 895                        insert_spaces: !hard_tabs,
 896                        relative_path: relative_path.to_string_lossy().into(),
 897                        position: point_to_lsp(position),
 898                        version: version.try_into().unwrap(),
 899                    },
 900                })
 901                .await?;
 902            let completions = result
 903                .completions
 904                .into_iter()
 905                .map(|completion| {
 906                    let start = snapshot
 907                        .clip_point_utf16(point_from_lsp(completion.range.start), Bias::Left);
 908                    let end =
 909                        snapshot.clip_point_utf16(point_from_lsp(completion.range.end), Bias::Left);
 910                    Completion {
 911                        uuid: completion.uuid,
 912                        range: snapshot.anchor_before(start)..snapshot.anchor_after(end),
 913                        text: completion.text,
 914                    }
 915                })
 916                .collect();
 917            anyhow::Ok(completions)
 918        })
 919    }
 920
 921    pub fn status(&self) -> Status {
 922        match &self.server {
 923            CopilotServer::Starting { task } => Status::Starting { task: task.clone() },
 924            CopilotServer::Disabled => Status::Disabled,
 925            CopilotServer::Error(error) => Status::Error(error.clone()),
 926            CopilotServer::Running(RunningCopilotServer { sign_in_status, .. }) => {
 927                match sign_in_status {
 928                    SignInStatus::Authorized { .. } => Status::Authorized,
 929                    SignInStatus::Unauthorized { .. } => Status::Unauthorized,
 930                    SignInStatus::SigningIn { prompt, .. } => Status::SigningIn {
 931                        prompt: prompt.clone(),
 932                    },
 933                    SignInStatus::SignedOut => Status::SignedOut,
 934                }
 935            }
 936        }
 937    }
 938
 939    fn update_sign_in_status(&mut self, lsp_status: request::SignInStatus, cx: &mut Context<Self>) {
 940        self.buffers.retain(|buffer| buffer.is_upgradable());
 941
 942        if let Ok(server) = self.server.as_running() {
 943            match lsp_status {
 944                request::SignInStatus::Ok { user: Some(_) }
 945                | request::SignInStatus::MaybeOk { .. }
 946                | request::SignInStatus::AlreadySignedIn { .. } => {
 947                    server.sign_in_status = SignInStatus::Authorized;
 948                    cx.emit(Event::CopilotAuthSignedIn);
 949                    for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
 950                        if let Some(buffer) = buffer.upgrade() {
 951                            self.register_buffer(&buffer, cx);
 952                        }
 953                    }
 954                }
 955                request::SignInStatus::NotAuthorized { .. } => {
 956                    server.sign_in_status = SignInStatus::Unauthorized;
 957                    for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
 958                        self.unregister_buffer(&buffer);
 959                    }
 960                }
 961                request::SignInStatus::Ok { user: None } | request::SignInStatus::NotSignedIn => {
 962                    server.sign_in_status = SignInStatus::SignedOut;
 963                    cx.emit(Event::CopilotAuthSignedOut);
 964                    for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
 965                        self.unregister_buffer(&buffer);
 966                    }
 967                }
 968            }
 969
 970            cx.notify();
 971        }
 972    }
 973}
 974
 975fn id_for_language(language: Option<&Arc<Language>>) -> String {
 976    language
 977        .map(|language| language.lsp_id())
 978        .unwrap_or_else(|| "plaintext".to_string())
 979}
 980
 981fn uri_for_buffer(buffer: &Entity<Buffer>, cx: &App) -> lsp::Url {
 982    if let Some(file) = buffer.read(cx).file().and_then(|file| file.as_local()) {
 983        lsp::Url::from_file_path(file.abs_path(cx)).unwrap()
 984    } else {
 985        format!("buffer://{}", buffer.entity_id()).parse().unwrap()
 986    }
 987}
 988
 989async fn clear_copilot_dir() {
 990    remove_matching(paths::copilot_dir(), |_| true).await
 991}
 992
 993async fn get_copilot_lsp(http: Arc<dyn HttpClient>) -> anyhow::Result<PathBuf> {
 994    const SERVER_PATH: &str = "dist/language-server.js";
 995
 996    ///Check for the latest copilot language server and download it if we haven't already
 997    async fn fetch_latest(http: Arc<dyn HttpClient>) -> anyhow::Result<PathBuf> {
 998        let release =
 999            get_release_by_tag_name("zed-industries/copilot", "v0.7.0", http.clone()).await?;
1000
1001        let version_dir = &paths::copilot_dir().join(format!("copilot-{}", release.tag_name));
1002
1003        fs::create_dir_all(version_dir).await?;
1004        let server_path = version_dir.join(SERVER_PATH);
1005
1006        if fs::metadata(&server_path).await.is_err() {
1007            // Copilot LSP looks for this dist dir specifically, so lets add it in.
1008            let dist_dir = version_dir.join("dist");
1009            fs::create_dir_all(dist_dir.as_path()).await?;
1010
1011            let url = &release
1012                .assets
1013                .first()
1014                .context("Github release for copilot contained no assets")?
1015                .browser_download_url;
1016
1017            let mut response = http
1018                .get(url, Default::default(), true)
1019                .await
1020                .context("error downloading copilot release")?;
1021            let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
1022            let archive = Archive::new(decompressed_bytes);
1023            archive.unpack(dist_dir).await?;
1024
1025            remove_matching(paths::copilot_dir(), |entry| entry != version_dir).await;
1026        }
1027
1028        Ok(server_path)
1029    }
1030
1031    match fetch_latest(http).await {
1032        ok @ Result::Ok(..) => ok,
1033        e @ Err(..) => {
1034            e.log_err();
1035            // Fetch a cached binary, if it exists
1036            maybe!(async {
1037                let mut last_version_dir = None;
1038                let mut entries = fs::read_dir(paths::copilot_dir()).await?;
1039                while let Some(entry) = entries.next().await {
1040                    let entry = entry?;
1041                    if entry.file_type().await?.is_dir() {
1042                        last_version_dir = Some(entry.path());
1043                    }
1044                }
1045                let last_version_dir =
1046                    last_version_dir.ok_or_else(|| anyhow!("no cached binary"))?;
1047                let server_path = last_version_dir.join(SERVER_PATH);
1048                if server_path.exists() {
1049                    Ok(server_path)
1050                } else {
1051                    Err(anyhow!(
1052                        "missing executable in directory {:?}",
1053                        last_version_dir
1054                    ))
1055                }
1056            })
1057            .await
1058        }
1059    }
1060}
1061
1062#[cfg(test)]
1063mod tests {
1064    use super::*;
1065    use gpui::TestAppContext;
1066    use util::path;
1067
1068    #[gpui::test(iterations = 10)]
1069    async fn test_buffer_management(cx: &mut TestAppContext) {
1070        let (copilot, mut lsp) = Copilot::fake(cx);
1071
1072        let buffer_1 = cx.new(|cx| Buffer::local("Hello", cx));
1073        let buffer_1_uri: lsp::Url = format!("buffer://{}", buffer_1.entity_id().as_u64())
1074            .parse()
1075            .unwrap();
1076        copilot.update(cx, |copilot, cx| copilot.register_buffer(&buffer_1, cx));
1077        assert_eq!(
1078            lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1079                .await,
1080            lsp::DidOpenTextDocumentParams {
1081                text_document: lsp::TextDocumentItem::new(
1082                    buffer_1_uri.clone(),
1083                    "plaintext".into(),
1084                    0,
1085                    "Hello".into()
1086                ),
1087            }
1088        );
1089
1090        let buffer_2 = cx.new(|cx| Buffer::local("Goodbye", cx));
1091        let buffer_2_uri: lsp::Url = format!("buffer://{}", buffer_2.entity_id().as_u64())
1092            .parse()
1093            .unwrap();
1094        copilot.update(cx, |copilot, cx| copilot.register_buffer(&buffer_2, cx));
1095        assert_eq!(
1096            lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1097                .await,
1098            lsp::DidOpenTextDocumentParams {
1099                text_document: lsp::TextDocumentItem::new(
1100                    buffer_2_uri.clone(),
1101                    "plaintext".into(),
1102                    0,
1103                    "Goodbye".into()
1104                ),
1105            }
1106        );
1107
1108        buffer_1.update(cx, |buffer, cx| buffer.edit([(5..5, " world")], None, cx));
1109        assert_eq!(
1110            lsp.receive_notification::<lsp::notification::DidChangeTextDocument>()
1111                .await,
1112            lsp::DidChangeTextDocumentParams {
1113                text_document: lsp::VersionedTextDocumentIdentifier::new(buffer_1_uri.clone(), 1),
1114                content_changes: vec![lsp::TextDocumentContentChangeEvent {
1115                    range: Some(lsp::Range::new(
1116                        lsp::Position::new(0, 5),
1117                        lsp::Position::new(0, 5)
1118                    )),
1119                    range_length: None,
1120                    text: " world".into(),
1121                }],
1122            }
1123        );
1124
1125        // Ensure updates to the file are reflected in the LSP.
1126        buffer_1.update(cx, |buffer, cx| {
1127            buffer.file_updated(
1128                Arc::new(File {
1129                    abs_path: path!("/root/child/buffer-1").into(),
1130                    path: Path::new("child/buffer-1").into(),
1131                }),
1132                cx,
1133            )
1134        });
1135        assert_eq!(
1136            lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1137                .await,
1138            lsp::DidCloseTextDocumentParams {
1139                text_document: lsp::TextDocumentIdentifier::new(buffer_1_uri),
1140            }
1141        );
1142        let buffer_1_uri = lsp::Url::from_file_path(path!("/root/child/buffer-1")).unwrap();
1143        assert_eq!(
1144            lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1145                .await,
1146            lsp::DidOpenTextDocumentParams {
1147                text_document: lsp::TextDocumentItem::new(
1148                    buffer_1_uri.clone(),
1149                    "plaintext".into(),
1150                    1,
1151                    "Hello world".into()
1152                ),
1153            }
1154        );
1155
1156        // Ensure all previously-registered buffers are closed when signing out.
1157        lsp.handle_request::<request::SignOut, _, _>(|_, _| async {
1158            Ok(request::SignOutResult {})
1159        });
1160        copilot
1161            .update(cx, |copilot, cx| copilot.sign_out(cx))
1162            .await
1163            .unwrap();
1164        assert_eq!(
1165            lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1166                .await,
1167            lsp::DidCloseTextDocumentParams {
1168                text_document: lsp::TextDocumentIdentifier::new(buffer_1_uri.clone()),
1169            }
1170        );
1171        assert_eq!(
1172            lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1173                .await,
1174            lsp::DidCloseTextDocumentParams {
1175                text_document: lsp::TextDocumentIdentifier::new(buffer_2_uri.clone()),
1176            }
1177        );
1178
1179        // Ensure all previously-registered buffers are re-opened when signing in.
1180        lsp.handle_request::<request::SignInInitiate, _, _>(|_, _| async {
1181            Ok(request::SignInInitiateResult::AlreadySignedIn {
1182                user: "user-1".into(),
1183            })
1184        });
1185        copilot
1186            .update(cx, |copilot, cx| copilot.sign_in(cx))
1187            .await
1188            .unwrap();
1189
1190        assert_eq!(
1191            lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1192                .await,
1193            lsp::DidOpenTextDocumentParams {
1194                text_document: lsp::TextDocumentItem::new(
1195                    buffer_1_uri.clone(),
1196                    "plaintext".into(),
1197                    0,
1198                    "Hello world".into()
1199                ),
1200            }
1201        );
1202        assert_eq!(
1203            lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1204                .await,
1205            lsp::DidOpenTextDocumentParams {
1206                text_document: lsp::TextDocumentItem::new(
1207                    buffer_2_uri.clone(),
1208                    "plaintext".into(),
1209                    0,
1210                    "Goodbye".into()
1211                ),
1212            }
1213        );
1214        // Dropping a buffer causes it to be closed on the LSP side as well.
1215        cx.update(|_| drop(buffer_2));
1216        assert_eq!(
1217            lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1218                .await,
1219            lsp::DidCloseTextDocumentParams {
1220                text_document: lsp::TextDocumentIdentifier::new(buffer_2_uri),
1221            }
1222        );
1223    }
1224
1225    struct File {
1226        abs_path: PathBuf,
1227        path: Arc<Path>,
1228    }
1229
1230    impl language::File for File {
1231        fn as_local(&self) -> Option<&dyn language::LocalFile> {
1232            Some(self)
1233        }
1234
1235        fn disk_state(&self) -> language::DiskState {
1236            language::DiskState::Present {
1237                mtime: ::fs::MTime::from_seconds_and_nanos(100, 42),
1238            }
1239        }
1240
1241        fn path(&self) -> &Arc<Path> {
1242            &self.path
1243        }
1244
1245        fn full_path(&self, _: &App) -> PathBuf {
1246            unimplemented!()
1247        }
1248
1249        fn file_name<'a>(&'a self, _: &'a App) -> &'a std::ffi::OsStr {
1250            unimplemented!()
1251        }
1252
1253        fn as_any(&self) -> &dyn std::any::Any {
1254            unimplemented!()
1255        }
1256
1257        fn to_proto(&self, _: &App) -> rpc::proto::File {
1258            unimplemented!()
1259        }
1260
1261        fn worktree_id(&self, _: &App) -> settings::WorktreeId {
1262            settings::WorktreeId::from_usize(0)
1263        }
1264
1265        fn is_private(&self) -> bool {
1266            false
1267        }
1268    }
1269
1270    impl language::LocalFile for File {
1271        fn abs_path(&self, _: &App) -> PathBuf {
1272            self.abs_path.clone()
1273        }
1274
1275        fn load(&self, _: &App) -> Task<Result<String>> {
1276            unimplemented!()
1277        }
1278
1279        fn load_bytes(&self, _cx: &App) -> Task<Result<Vec<u8>>> {
1280            unimplemented!()
1281        }
1282    }
1283}