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 semver::Version;
29use serde_json::json;
30use settings::Settings;
31use settings::SettingsStore;
32use sign_in::{reinstall_and_sign_in_within_workspace, sign_out_within_workspace};
33use std::collections::hash_map::Entry;
34use std::{
35 any::TypeId,
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_completion_provider::CopilotCompletionProvider;
48pub use crate::sign_in::{CopilotCodeVerification, initiate_sign_in, reinstall_and_sign_in};
49
50actions!(
51 copilot,
52 [
53 /// Requests a code completion suggestion from Copilot.
54 Suggest,
55 /// Cycles to the next Copilot suggestion.
56 NextSuggestion,
57 /// Cycles to the previous Copilot suggestion.
58 PreviousSuggestion,
59 /// Reinstalls the Copilot language server.
60 Reinstall,
61 /// Signs in to GitHub Copilot.
62 SignIn,
63 /// Signs out of GitHub Copilot.
64 SignOut
65 ]
66);
67
68pub fn init(
69 new_server_id: LanguageServerId,
70 fs: Arc<dyn Fs>,
71 http: Arc<dyn HttpClient>,
72 node_runtime: NodeRuntime,
73 cx: &mut App,
74) {
75 let language_settings = all_language_settings(None, cx);
76 let configuration = copilot_chat::CopilotChatConfiguration {
77 enterprise_uri: language_settings
78 .edit_predictions
79 .copilot
80 .enterprise_uri
81 .clone(),
82 };
83 copilot_chat::init(fs.clone(), http.clone(), configuration, cx);
84
85 let copilot = cx.new(move |cx| Copilot::start(new_server_id, fs, node_runtime, cx));
86 Copilot::set_global(copilot.clone(), cx);
87 cx.observe(&copilot, |copilot, cx| {
88 copilot.update(cx, |copilot, cx| copilot.update_action_visibilities(cx));
89 })
90 .detach();
91 cx.observe_global::<SettingsStore>(|cx| {
92 if let Some(copilot) = Copilot::global(cx) {
93 copilot.update(cx, |copilot, cx| copilot.update_action_visibilities(cx));
94 }
95 })
96 .detach();
97
98 cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
99 workspace.register_action(|workspace, _: &SignIn, window, cx| {
100 if let Some(copilot) = Copilot::global(cx) {
101 let is_reinstall = false;
102 initiate_sign_in_within_workspace(workspace, copilot, is_reinstall, window, cx);
103 }
104 });
105 workspace.register_action(|workspace, _: &Reinstall, window, cx| {
106 if let Some(copilot) = Copilot::global(cx) {
107 reinstall_and_sign_in_within_workspace(workspace, copilot, window, cx);
108 }
109 });
110 workspace.register_action(|workspace, _: &SignOut, _window, cx| {
111 if let Some(copilot) = Copilot::global(cx) {
112 sign_out_within_workspace(workspace, copilot, cx);
113 }
114 });
115 })
116 .detach();
117}
118
119enum CopilotServer {
120 Disabled,
121 Starting { task: Shared<Task<()>> },
122 Error(Arc<str>),
123 Running(RunningCopilotServer),
124}
125
126impl CopilotServer {
127 fn as_authenticated(&mut self) -> Result<&mut RunningCopilotServer> {
128 let server = self.as_running()?;
129 anyhow::ensure!(
130 matches!(server.sign_in_status, SignInStatus::Authorized),
131 "must sign in before using copilot"
132 );
133 Ok(server)
134 }
135
136 fn as_running(&mut self) -> Result<&mut RunningCopilotServer> {
137 match self {
138 CopilotServer::Starting { .. } => anyhow::bail!("copilot is still starting"),
139 CopilotServer::Disabled => anyhow::bail!("copilot is disabled"),
140 CopilotServer::Error(error) => {
141 anyhow::bail!("copilot was not started because of an error: {error}")
142 }
143 CopilotServer::Running(server) => Ok(server),
144 }
145 }
146}
147
148struct RunningCopilotServer {
149 lsp: Arc<LanguageServer>,
150 sign_in_status: SignInStatus,
151 registered_buffers: HashMap<EntityId, RegisteredBuffer>,
152}
153
154#[derive(Clone, Debug)]
155enum SignInStatus {
156 Authorized,
157 Unauthorized,
158 SigningIn {
159 prompt: Option<request::PromptUserDeviceFlow>,
160 task: Shared<Task<Result<(), Arc<anyhow::Error>>>>,
161 },
162 SignedOut {
163 awaiting_signing_in: bool,
164 },
165}
166
167#[derive(Debug, Clone)]
168pub enum Status {
169 Starting {
170 task: Shared<Task<()>>,
171 },
172 Error(Arc<str>),
173 Disabled,
174 SignedOut {
175 awaiting_signing_in: bool,
176 },
177 SigningIn {
178 prompt: Option<request::PromptUserDeviceFlow>,
179 },
180 Unauthorized,
181 Authorized,
182}
183
184impl Status {
185 pub fn is_authorized(&self) -> bool {
186 matches!(self, Status::Authorized)
187 }
188
189 pub fn is_configured(&self) -> bool {
190 matches!(
191 self,
192 Status::Starting { .. }
193 | Status::Error(_)
194 | Status::SigningIn { .. }
195 | Status::Authorized
196 )
197 }
198}
199
200struct RegisteredBuffer {
201 uri: lsp::Uri,
202 language_id: String,
203 snapshot: BufferSnapshot,
204 snapshot_version: i32,
205 _subscriptions: [gpui::Subscription; 2],
206 pending_buffer_change: Task<Option<()>>,
207}
208
209impl RegisteredBuffer {
210 fn report_changes(
211 &mut self,
212 buffer: &Entity<Buffer>,
213 cx: &mut Context<Copilot>,
214 ) -> oneshot::Receiver<(i32, BufferSnapshot)> {
215 let (done_tx, done_rx) = oneshot::channel();
216
217 if buffer.read(cx).version() == self.snapshot.version {
218 let _ = done_tx.send((self.snapshot_version, self.snapshot.clone()));
219 } else {
220 let buffer = buffer.downgrade();
221 let id = buffer.entity_id();
222 let prev_pending_change =
223 mem::replace(&mut self.pending_buffer_change, Task::ready(None));
224 self.pending_buffer_change = cx.spawn(async move |copilot, cx| {
225 prev_pending_change.await;
226
227 let old_version = copilot
228 .update(cx, |copilot, _| {
229 let server = copilot.server.as_authenticated().log_err()?;
230 let buffer = server.registered_buffers.get_mut(&id)?;
231 Some(buffer.snapshot.version.clone())
232 })
233 .ok()??;
234 let new_snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot()).ok()?;
235
236 let content_changes = cx
237 .background_spawn({
238 let new_snapshot = new_snapshot.clone();
239 async move {
240 new_snapshot
241 .edits_since::<Dimensions<PointUtf16, usize>>(&old_version)
242 .map(|edit| {
243 let edit_start = edit.new.start.0;
244 let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
245 let new_text = new_snapshot
246 .text_for_range(edit.new.start.1..edit.new.end.1)
247 .collect();
248 lsp::TextDocumentContentChangeEvent {
249 range: Some(lsp::Range::new(
250 point_to_lsp(edit_start),
251 point_to_lsp(edit_end),
252 )),
253 range_length: None,
254 text: new_text,
255 }
256 })
257 .collect::<Vec<_>>()
258 }
259 })
260 .await;
261
262 copilot
263 .update(cx, |copilot, _| {
264 let server = copilot.server.as_authenticated().log_err()?;
265 let buffer = server.registered_buffers.get_mut(&id)?;
266 if !content_changes.is_empty() {
267 buffer.snapshot_version += 1;
268 buffer.snapshot = new_snapshot;
269 server
270 .lsp
271 .notify::<lsp::notification::DidChangeTextDocument>(
272 &lsp::DidChangeTextDocumentParams {
273 text_document: lsp::VersionedTextDocumentIdentifier::new(
274 buffer.uri.clone(),
275 buffer.snapshot_version,
276 ),
277 content_changes,
278 },
279 )
280 .ok();
281 }
282 let _ = done_tx.send((buffer.snapshot_version, buffer.snapshot.clone()));
283 Some(())
284 })
285 .ok()?;
286
287 Some(())
288 });
289 }
290
291 done_rx
292 }
293}
294
295#[derive(Debug)]
296pub struct Completion {
297 pub uuid: String,
298 pub range: Range<Anchor>,
299 pub text: String,
300}
301
302pub struct Copilot {
303 fs: Arc<dyn Fs>,
304 node_runtime: NodeRuntime,
305 server: CopilotServer,
306 buffers: HashSet<WeakEntity<Buffer>>,
307 server_id: LanguageServerId,
308 _subscription: gpui::Subscription,
309}
310
311pub enum Event {
312 CopilotLanguageServerStarted,
313 CopilotAuthSignedIn,
314 CopilotAuthSignedOut,
315}
316
317impl EventEmitter<Event> for Copilot {}
318
319struct GlobalCopilot(Entity<Copilot>);
320
321impl Global for GlobalCopilot {}
322
323impl Copilot {
324 pub fn global(cx: &App) -> Option<Entity<Self>> {
325 cx.try_global::<GlobalCopilot>()
326 .map(|model| model.0.clone())
327 }
328
329 pub fn set_global(copilot: Entity<Self>, cx: &mut App) {
330 cx.set_global(GlobalCopilot(copilot));
331 }
332
333 fn start(
334 new_server_id: LanguageServerId,
335 fs: Arc<dyn Fs>,
336 node_runtime: NodeRuntime,
337 cx: &mut Context<Self>,
338 ) -> Self {
339 let mut this = Self {
340 server_id: new_server_id,
341 fs,
342 node_runtime,
343 server: CopilotServer::Disabled,
344 buffers: Default::default(),
345 _subscription: cx.on_app_quit(Self::shutdown_language_server),
346 };
347 this.start_copilot(true, false, cx);
348 cx.observe_global::<SettingsStore>(move |this, cx| {
349 this.start_copilot(true, false, cx);
350 if let Ok(server) = this.server.as_running() {
351 notify_did_change_config_to_server(&server.lsp, cx)
352 .context("copilot setting change: did change configuration")
353 .log_err();
354 }
355 })
356 .detach();
357 this
358 }
359
360 fn shutdown_language_server(
361 &mut self,
362 _cx: &mut Context<Self>,
363 ) -> impl Future<Output = ()> + use<> {
364 let shutdown = match mem::replace(&mut self.server, CopilotServer::Disabled) {
365 CopilotServer::Running(server) => Some(Box::pin(async move { server.lsp.shutdown() })),
366 _ => None,
367 };
368
369 async move {
370 if let Some(shutdown) = shutdown {
371 shutdown.await;
372 }
373 }
374 }
375
376 fn start_copilot(
377 &mut self,
378 check_edit_prediction_provider: bool,
379 awaiting_sign_in_after_start: bool,
380 cx: &mut Context<Self>,
381 ) {
382 if !matches!(self.server, CopilotServer::Disabled) {
383 return;
384 }
385 let language_settings = all_language_settings(None, cx);
386 if check_edit_prediction_provider
387 && language_settings.edit_predictions.provider != EditPredictionProvider::Copilot
388 {
389 return;
390 }
391 let server_id = self.server_id;
392 let fs = self.fs.clone();
393 let node_runtime = self.node_runtime.clone();
394 let env = self.build_env(&language_settings.edit_predictions.copilot);
395 let start_task = cx
396 .spawn(async move |this, cx| {
397 Self::start_language_server(
398 server_id,
399 fs,
400 node_runtime,
401 env,
402 this,
403 awaiting_sign_in_after_start,
404 cx,
405 )
406 .await
407 })
408 .shared();
409 self.server = CopilotServer::Starting { task: start_task };
410 cx.notify();
411 }
412
413 fn build_env(&self, copilot_settings: &CopilotSettings) -> Option<HashMap<String, String>> {
414 let proxy_url = copilot_settings.proxy.clone()?;
415 let no_verify = copilot_settings.proxy_no_verify;
416 let http_or_https_proxy = if proxy_url.starts_with("http:") {
417 Some("HTTP_PROXY")
418 } else if proxy_url.starts_with("https:") {
419 Some("HTTPS_PROXY")
420 } else {
421 log::error!(
422 "Unsupported protocol scheme for language server proxy (must be http or https)"
423 );
424 None
425 };
426
427 let mut env = HashMap::default();
428
429 if let Some(proxy_type) = http_or_https_proxy {
430 env.insert(proxy_type.to_string(), proxy_url);
431 if let Some(true) = no_verify {
432 env.insert("NODE_TLS_REJECT_UNAUTHORIZED".to_string(), "0".to_string());
433 };
434 }
435
436 if let Ok(oauth_token) = env::var(copilot_chat::COPILOT_OAUTH_ENV_VAR) {
437 env.insert(copilot_chat::COPILOT_OAUTH_ENV_VAR.to_string(), oauth_token);
438 }
439
440 if env.is_empty() { None } else { Some(env) }
441 }
442
443 #[cfg(any(test, feature = "test-support"))]
444 pub fn fake(cx: &mut gpui::TestAppContext) -> (Entity<Self>, lsp::FakeLanguageServer) {
445 use fs::FakeFs;
446 use lsp::FakeLanguageServer;
447 use node_runtime::NodeRuntime;
448
449 let (server, fake_server) = FakeLanguageServer::new(
450 LanguageServerId(0),
451 LanguageServerBinary {
452 path: "path/to/copilot".into(),
453 arguments: vec![],
454 env: None,
455 },
456 "copilot".into(),
457 Default::default(),
458 &mut cx.to_async(),
459 );
460 let node_runtime = NodeRuntime::unavailable();
461 let this = cx.new(|cx| Self {
462 server_id: LanguageServerId(0),
463 fs: FakeFs::new(cx.background_executor().clone()),
464 node_runtime,
465 server: CopilotServer::Running(RunningCopilotServer {
466 lsp: Arc::new(server),
467 sign_in_status: SignInStatus::Authorized,
468 registered_buffers: Default::default(),
469 }),
470 _subscription: cx.on_app_quit(Self::shutdown_language_server),
471 buffers: Default::default(),
472 });
473 (this, fake_server)
474 }
475
476 async fn start_language_server(
477 new_server_id: LanguageServerId,
478 fs: Arc<dyn Fs>,
479 node_runtime: NodeRuntime,
480 env: Option<HashMap<String, String>>,
481 this: WeakEntity<Self>,
482 awaiting_sign_in_after_start: bool,
483 cx: &mut AsyncApp,
484 ) {
485 let start_language_server = async {
486 let server_path = get_copilot_lsp(fs, node_runtime.clone()).await?;
487 let node_path = node_runtime.binary_path().await?;
488 ensure_node_version_for_copilot(&node_path).await?;
489
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 {
845 server
846 .lsp
847 .notify::<lsp::notification::DidCloseTextDocument>(
848 &lsp::DidCloseTextDocumentParams {
849 text_document: lsp::TextDocumentIdentifier::new(buffer.uri),
850 },
851 )
852 .ok();
853 }
854 }
855
856 pub fn completions<T>(
857 &mut self,
858 buffer: &Entity<Buffer>,
859 position: T,
860 cx: &mut Context<Self>,
861 ) -> Task<Result<Vec<Completion>>>
862 where
863 T: ToPointUtf16,
864 {
865 self.request_completions::<request::GetCompletions, _>(buffer, position, cx)
866 }
867
868 pub fn completions_cycling<T>(
869 &mut self,
870 buffer: &Entity<Buffer>,
871 position: T,
872 cx: &mut Context<Self>,
873 ) -> Task<Result<Vec<Completion>>>
874 where
875 T: ToPointUtf16,
876 {
877 self.request_completions::<request::GetCompletionsCycling, _>(buffer, position, cx)
878 }
879
880 pub fn accept_completion(
881 &mut self,
882 completion: &Completion,
883 cx: &mut Context<Self>,
884 ) -> Task<Result<()>> {
885 let server = match self.server.as_authenticated() {
886 Ok(server) => server,
887 Err(error) => return Task::ready(Err(error)),
888 };
889 let request =
890 server
891 .lsp
892 .request::<request::NotifyAccepted>(request::NotifyAcceptedParams {
893 uuid: completion.uuid.clone(),
894 });
895 cx.background_spawn(async move {
896 request
897 .await
898 .into_response()
899 .context("copilot: notify accepted")?;
900 Ok(())
901 })
902 }
903
904 pub fn discard_completions(
905 &mut self,
906 completions: &[Completion],
907 cx: &mut Context<Self>,
908 ) -> Task<Result<()>> {
909 let server = match self.server.as_authenticated() {
910 Ok(server) => server,
911 Err(_) => return Task::ready(Ok(())),
912 };
913 let request =
914 server
915 .lsp
916 .request::<request::NotifyRejected>(request::NotifyRejectedParams {
917 uuids: completions
918 .iter()
919 .map(|completion| completion.uuid.clone())
920 .collect(),
921 });
922 cx.background_spawn(async move {
923 request
924 .await
925 .into_response()
926 .context("copilot: notify rejected")?;
927 Ok(())
928 })
929 }
930
931 fn request_completions<R, T>(
932 &mut self,
933 buffer: &Entity<Buffer>,
934 position: T,
935 cx: &mut Context<Self>,
936 ) -> Task<Result<Vec<Completion>>>
937 where
938 R: 'static
939 + lsp::request::Request<
940 Params = request::GetCompletionsParams,
941 Result = request::GetCompletionsResult,
942 >,
943 T: ToPointUtf16,
944 {
945 self.register_buffer(buffer, cx);
946
947 let server = match self.server.as_authenticated() {
948 Ok(server) => server,
949 Err(error) => return Task::ready(Err(error)),
950 };
951 let lsp = server.lsp.clone();
952 let registered_buffer = server
953 .registered_buffers
954 .get_mut(&buffer.entity_id())
955 .unwrap();
956 let snapshot = registered_buffer.report_changes(buffer, cx);
957 let buffer = buffer.read(cx);
958 let uri = registered_buffer.uri.clone();
959 let position = position.to_point_utf16(buffer);
960 let settings = language_settings(
961 buffer.language_at(position).map(|l| l.name()),
962 buffer.file(),
963 cx,
964 );
965 let tab_size = settings.tab_size;
966 let hard_tabs = settings.hard_tabs;
967 let relative_path = buffer
968 .file()
969 .map(|file| file.path().to_path_buf())
970 .unwrap_or_default();
971
972 cx.background_spawn(async move {
973 let (version, snapshot) = snapshot.await?;
974 let result = lsp
975 .request::<R>(request::GetCompletionsParams {
976 doc: request::GetCompletionsDocument {
977 uri,
978 tab_size: tab_size.into(),
979 indent_size: 1,
980 insert_spaces: !hard_tabs,
981 relative_path: relative_path.to_string_lossy().into(),
982 position: point_to_lsp(position),
983 version: version.try_into().unwrap(),
984 },
985 })
986 .await
987 .into_response()
988 .context("copilot: get completions")?;
989 let completions = result
990 .completions
991 .into_iter()
992 .map(|completion| {
993 let start = snapshot
994 .clip_point_utf16(point_from_lsp(completion.range.start), Bias::Left);
995 let end =
996 snapshot.clip_point_utf16(point_from_lsp(completion.range.end), Bias::Left);
997 Completion {
998 uuid: completion.uuid,
999 range: snapshot.anchor_before(start)..snapshot.anchor_after(end),
1000 text: completion.text,
1001 }
1002 })
1003 .collect();
1004 anyhow::Ok(completions)
1005 })
1006 }
1007
1008 pub fn status(&self) -> Status {
1009 match &self.server {
1010 CopilotServer::Starting { task } => Status::Starting { task: task.clone() },
1011 CopilotServer::Disabled => Status::Disabled,
1012 CopilotServer::Error(error) => Status::Error(error.clone()),
1013 CopilotServer::Running(RunningCopilotServer { sign_in_status, .. }) => {
1014 match sign_in_status {
1015 SignInStatus::Authorized => Status::Authorized,
1016 SignInStatus::Unauthorized => Status::Unauthorized,
1017 SignInStatus::SigningIn { prompt, .. } => Status::SigningIn {
1018 prompt: prompt.clone(),
1019 },
1020 SignInStatus::SignedOut {
1021 awaiting_signing_in,
1022 } => Status::SignedOut {
1023 awaiting_signing_in: *awaiting_signing_in,
1024 },
1025 }
1026 }
1027 }
1028 }
1029
1030 fn update_sign_in_status(&mut self, lsp_status: request::SignInStatus, cx: &mut Context<Self>) {
1031 self.buffers.retain(|buffer| buffer.is_upgradable());
1032
1033 if let Ok(server) = self.server.as_running() {
1034 match lsp_status {
1035 request::SignInStatus::Ok { user: Some(_) }
1036 | request::SignInStatus::MaybeOk { .. }
1037 | request::SignInStatus::AlreadySignedIn { .. } => {
1038 server.sign_in_status = SignInStatus::Authorized;
1039 cx.emit(Event::CopilotAuthSignedIn);
1040 for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1041 if let Some(buffer) = buffer.upgrade() {
1042 self.register_buffer(&buffer, cx);
1043 }
1044 }
1045 }
1046 request::SignInStatus::NotAuthorized { .. } => {
1047 server.sign_in_status = SignInStatus::Unauthorized;
1048 for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1049 self.unregister_buffer(&buffer);
1050 }
1051 }
1052 request::SignInStatus::Ok { user: None } | request::SignInStatus::NotSignedIn => {
1053 if !matches!(server.sign_in_status, SignInStatus::SignedOut { .. }) {
1054 server.sign_in_status = SignInStatus::SignedOut {
1055 awaiting_signing_in: false,
1056 };
1057 }
1058 cx.emit(Event::CopilotAuthSignedOut);
1059 for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1060 self.unregister_buffer(&buffer);
1061 }
1062 }
1063 }
1064
1065 cx.notify();
1066 }
1067 }
1068
1069 fn update_action_visibilities(&self, cx: &mut App) {
1070 let signed_in_actions = [
1071 TypeId::of::<Suggest>(),
1072 TypeId::of::<NextSuggestion>(),
1073 TypeId::of::<PreviousSuggestion>(),
1074 TypeId::of::<Reinstall>(),
1075 ];
1076 let auth_actions = [TypeId::of::<SignOut>()];
1077 let no_auth_actions = [TypeId::of::<SignIn>()];
1078 let status = self.status();
1079
1080 let is_ai_disabled = DisableAiSettings::get_global(cx).disable_ai;
1081 let filter = CommandPaletteFilter::global_mut(cx);
1082
1083 if is_ai_disabled {
1084 filter.hide_action_types(&signed_in_actions);
1085 filter.hide_action_types(&auth_actions);
1086 filter.hide_action_types(&no_auth_actions);
1087 } else {
1088 match status {
1089 Status::Disabled => {
1090 filter.hide_action_types(&signed_in_actions);
1091 filter.hide_action_types(&auth_actions);
1092 filter.hide_action_types(&no_auth_actions);
1093 }
1094 Status::Authorized => {
1095 filter.hide_action_types(&no_auth_actions);
1096 filter.show_action_types(signed_in_actions.iter().chain(&auth_actions));
1097 }
1098 _ => {
1099 filter.hide_action_types(&signed_in_actions);
1100 filter.hide_action_types(&auth_actions);
1101 filter.show_action_types(&no_auth_actions);
1102 }
1103 }
1104 }
1105 }
1106}
1107
1108fn id_for_language(language: Option<&Arc<Language>>) -> String {
1109 language
1110 .map(|language| language.lsp_id())
1111 .unwrap_or_else(|| "plaintext".to_string())
1112}
1113
1114fn uri_for_buffer(buffer: &Entity<Buffer>, cx: &App) -> Result<lsp::Uri, ()> {
1115 if let Some(file) = buffer.read(cx).file().and_then(|file| file.as_local()) {
1116 lsp::Uri::from_file_path(file.abs_path(cx))
1117 } else {
1118 format!("buffer://{}", buffer.entity_id())
1119 .parse()
1120 .map_err(|_| ())
1121 }
1122}
1123
1124fn notify_did_change_config_to_server(
1125 server: &Arc<LanguageServer>,
1126 cx: &mut Context<Copilot>,
1127) -> std::result::Result<(), anyhow::Error> {
1128 let copilot_settings = all_language_settings(None, cx)
1129 .edit_predictions
1130 .copilot
1131 .clone();
1132
1133 if let Some(copilot_chat) = copilot_chat::CopilotChat::global(cx) {
1134 copilot_chat.update(cx, |chat, cx| {
1135 chat.set_configuration(
1136 copilot_chat::CopilotChatConfiguration {
1137 enterprise_uri: copilot_settings.enterprise_uri.clone(),
1138 },
1139 cx,
1140 );
1141 });
1142 }
1143
1144 let settings = json!({
1145 "http": {
1146 "proxy": copilot_settings.proxy,
1147 "proxyStrictSSL": !copilot_settings.proxy_no_verify.unwrap_or(false)
1148 },
1149 "github-enterprise": {
1150 "uri": copilot_settings.enterprise_uri
1151 }
1152 });
1153
1154 server.notify::<lsp::notification::DidChangeConfiguration>(&lsp::DidChangeConfigurationParams {
1155 settings,
1156 })
1157}
1158
1159async fn clear_copilot_dir() {
1160 remove_matching(paths::copilot_dir(), |_| true).await
1161}
1162
1163async fn clear_copilot_config_dir() {
1164 remove_matching(copilot_chat::copilot_chat_config_dir(), |_| true).await
1165}
1166
1167async fn ensure_node_version_for_copilot(node_path: &Path) -> anyhow::Result<()> {
1168 const MIN_COPILOT_NODE_VERSION: Version = Version::new(20, 8, 0);
1169
1170 log::info!("Checking Node.js version for Copilot at: {:?}", node_path);
1171
1172 let output = util::command::new_smol_command(node_path)
1173 .arg("--version")
1174 .output()
1175 .await
1176 .with_context(|| format!("checking Node.js version at {:?}", node_path))?;
1177
1178 if !output.status.success() {
1179 anyhow::bail!(
1180 "failed to run node --version for Copilot. stdout: {}, stderr: {}",
1181 String::from_utf8_lossy(&output.stdout),
1182 String::from_utf8_lossy(&output.stderr),
1183 );
1184 }
1185
1186 let version_str = String::from_utf8_lossy(&output.stdout);
1187 let version = Version::parse(version_str.trim().trim_start_matches('v'))
1188 .with_context(|| format!("parsing Node.js version from '{}'", version_str.trim()))?;
1189
1190 if version < MIN_COPILOT_NODE_VERSION {
1191 anyhow::bail!(
1192 "GitHub Copilot language server requires Node.js {MIN_COPILOT_NODE_VERSION} or later, but found {version}. \
1193 Please update your Node.js version or configure a different Node.js path in settings."
1194 );
1195 }
1196
1197 log::info!(
1198 "Node.js version {} meets Copilot requirements (>= {})",
1199 version,
1200 MIN_COPILOT_NODE_VERSION
1201 );
1202 Ok(())
1203}
1204
1205async fn get_copilot_lsp(fs: Arc<dyn Fs>, node_runtime: NodeRuntime) -> anyhow::Result<PathBuf> {
1206 const PACKAGE_NAME: &str = "@github/copilot-language-server";
1207 const SERVER_PATH: &str =
1208 "node_modules/@github/copilot-language-server/dist/language-server.js";
1209
1210 let latest_version = node_runtime
1211 .npm_package_latest_version(PACKAGE_NAME)
1212 .await?;
1213 let server_path = paths::copilot_dir().join(SERVER_PATH);
1214
1215 fs.create_dir(paths::copilot_dir()).await?;
1216
1217 let should_install = node_runtime
1218 .should_install_npm_package(
1219 PACKAGE_NAME,
1220 &server_path,
1221 paths::copilot_dir(),
1222 VersionStrategy::Latest(&latest_version),
1223 )
1224 .await;
1225 if should_install {
1226 node_runtime
1227 .npm_install_packages(paths::copilot_dir(), &[(PACKAGE_NAME, &latest_version)])
1228 .await?;
1229 }
1230
1231 Ok(server_path)
1232}
1233
1234#[cfg(test)]
1235mod tests {
1236 use super::*;
1237 use gpui::TestAppContext;
1238 use util::path;
1239
1240 #[gpui::test(iterations = 10)]
1241 async fn test_buffer_management(cx: &mut TestAppContext) {
1242 let (copilot, mut lsp) = Copilot::fake(cx);
1243
1244 let buffer_1 = cx.new(|cx| Buffer::local("Hello", cx));
1245 let buffer_1_uri: lsp::Uri = format!("buffer://{}", buffer_1.entity_id().as_u64())
1246 .parse()
1247 .unwrap();
1248 copilot.update(cx, |copilot, cx| copilot.register_buffer(&buffer_1, cx));
1249 assert_eq!(
1250 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1251 .await,
1252 lsp::DidOpenTextDocumentParams {
1253 text_document: lsp::TextDocumentItem::new(
1254 buffer_1_uri.clone(),
1255 "plaintext".into(),
1256 0,
1257 "Hello".into()
1258 ),
1259 }
1260 );
1261
1262 let buffer_2 = cx.new(|cx| Buffer::local("Goodbye", cx));
1263 let buffer_2_uri: lsp::Uri = format!("buffer://{}", buffer_2.entity_id().as_u64())
1264 .parse()
1265 .unwrap();
1266 copilot.update(cx, |copilot, cx| copilot.register_buffer(&buffer_2, cx));
1267 assert_eq!(
1268 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1269 .await,
1270 lsp::DidOpenTextDocumentParams {
1271 text_document: lsp::TextDocumentItem::new(
1272 buffer_2_uri.clone(),
1273 "plaintext".into(),
1274 0,
1275 "Goodbye".into()
1276 ),
1277 }
1278 );
1279
1280 buffer_1.update(cx, |buffer, cx| buffer.edit([(5..5, " world")], None, cx));
1281 assert_eq!(
1282 lsp.receive_notification::<lsp::notification::DidChangeTextDocument>()
1283 .await,
1284 lsp::DidChangeTextDocumentParams {
1285 text_document: lsp::VersionedTextDocumentIdentifier::new(buffer_1_uri.clone(), 1),
1286 content_changes: vec![lsp::TextDocumentContentChangeEvent {
1287 range: Some(lsp::Range::new(
1288 lsp::Position::new(0, 5),
1289 lsp::Position::new(0, 5)
1290 )),
1291 range_length: None,
1292 text: " world".into(),
1293 }],
1294 }
1295 );
1296
1297 // Ensure updates to the file are reflected in the LSP.
1298 buffer_1.update(cx, |buffer, cx| {
1299 buffer.file_updated(
1300 Arc::new(File {
1301 abs_path: path!("/root/child/buffer-1").into(),
1302 path: Path::new("child/buffer-1").into(),
1303 }),
1304 cx,
1305 )
1306 });
1307 assert_eq!(
1308 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1309 .await,
1310 lsp::DidCloseTextDocumentParams {
1311 text_document: lsp::TextDocumentIdentifier::new(buffer_1_uri),
1312 }
1313 );
1314 let buffer_1_uri = lsp::Uri::from_file_path(path!("/root/child/buffer-1")).unwrap();
1315 assert_eq!(
1316 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1317 .await,
1318 lsp::DidOpenTextDocumentParams {
1319 text_document: lsp::TextDocumentItem::new(
1320 buffer_1_uri.clone(),
1321 "plaintext".into(),
1322 1,
1323 "Hello world".into()
1324 ),
1325 }
1326 );
1327
1328 // Ensure all previously-registered buffers are closed when signing out.
1329 lsp.set_request_handler::<request::SignOut, _, _>(|_, _| async {
1330 Ok(request::SignOutResult {})
1331 });
1332 copilot
1333 .update(cx, |copilot, cx| copilot.sign_out(cx))
1334 .await
1335 .unwrap();
1336 assert_eq!(
1337 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1338 .await,
1339 lsp::DidCloseTextDocumentParams {
1340 text_document: lsp::TextDocumentIdentifier::new(buffer_1_uri.clone()),
1341 }
1342 );
1343 assert_eq!(
1344 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1345 .await,
1346 lsp::DidCloseTextDocumentParams {
1347 text_document: lsp::TextDocumentIdentifier::new(buffer_2_uri.clone()),
1348 }
1349 );
1350
1351 // Ensure all previously-registered buffers are re-opened when signing in.
1352 lsp.set_request_handler::<request::SignInInitiate, _, _>(|_, _| async {
1353 Ok(request::SignInInitiateResult::AlreadySignedIn {
1354 user: "user-1".into(),
1355 })
1356 });
1357 copilot
1358 .update(cx, |copilot, cx| copilot.sign_in(cx))
1359 .await
1360 .unwrap();
1361
1362 assert_eq!(
1363 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1364 .await,
1365 lsp::DidOpenTextDocumentParams {
1366 text_document: lsp::TextDocumentItem::new(
1367 buffer_1_uri.clone(),
1368 "plaintext".into(),
1369 0,
1370 "Hello world".into()
1371 ),
1372 }
1373 );
1374 assert_eq!(
1375 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1376 .await,
1377 lsp::DidOpenTextDocumentParams {
1378 text_document: lsp::TextDocumentItem::new(
1379 buffer_2_uri.clone(),
1380 "plaintext".into(),
1381 0,
1382 "Goodbye".into()
1383 ),
1384 }
1385 );
1386 // Dropping a buffer causes it to be closed on the LSP side as well.
1387 cx.update(|_| drop(buffer_2));
1388 assert_eq!(
1389 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1390 .await,
1391 lsp::DidCloseTextDocumentParams {
1392 text_document: lsp::TextDocumentIdentifier::new(buffer_2_uri),
1393 }
1394 );
1395 }
1396
1397 struct File {
1398 abs_path: PathBuf,
1399 path: Arc<Path>,
1400 }
1401
1402 impl language::File for File {
1403 fn as_local(&self) -> Option<&dyn language::LocalFile> {
1404 Some(self)
1405 }
1406
1407 fn disk_state(&self) -> language::DiskState {
1408 language::DiskState::Present {
1409 mtime: ::fs::MTime::from_seconds_and_nanos(100, 42),
1410 }
1411 }
1412
1413 fn path(&self) -> &Arc<Path> {
1414 &self.path
1415 }
1416
1417 fn full_path(&self, _: &App) -> PathBuf {
1418 unimplemented!()
1419 }
1420
1421 fn file_name<'a>(&'a self, _: &'a App) -> &'a std::ffi::OsStr {
1422 unimplemented!()
1423 }
1424
1425 fn to_proto(&self, _: &App) -> rpc::proto::File {
1426 unimplemented!()
1427 }
1428
1429 fn worktree_id(&self, _: &App) -> settings::WorktreeId {
1430 settings::WorktreeId::from_usize(0)
1431 }
1432
1433 fn is_private(&self) -> bool {
1434 false
1435 }
1436 }
1437
1438 impl language::LocalFile for File {
1439 fn abs_path(&self, _: &App) -> PathBuf {
1440 self.abs_path.clone()
1441 }
1442
1443 fn load(&self, _: &App) -> Task<Result<String>> {
1444 unimplemented!()
1445 }
1446
1447 fn load_bytes(&self, _cx: &App) -> Task<Result<Vec<u8>>> {
1448 unimplemented!()
1449 }
1450 }
1451}
1452
1453#[cfg(test)]
1454#[ctor::ctor]
1455fn init_logger() {
1456 zlog::init_test();
1457}