copilot.rs

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