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