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