copilot.rs

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