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