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