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