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