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