copilot.rs

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