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