copilot2.rs

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