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