1pub mod copilot_chat;
2mod copilot_completion_provider;
3pub mod copilot_responses;
4pub mod request;
5mod sign_in;
6
7use crate::sign_in::initiate_sign_in_within_workspace;
8use ::fs::Fs;
9use anyhow::{Context as _, Result, anyhow};
10use collections::{HashMap, HashSet};
11use command_palette_hooks::CommandPaletteFilter;
12use futures::{Future, FutureExt, TryFutureExt, channel::oneshot, future::Shared};
13use gpui::{
14 App, AppContext as _, AsyncApp, Context, Entity, EntityId, EventEmitter, Global, Task,
15 WeakEntity, actions,
16};
17use http_client::HttpClient;
18use language::language_settings::CopilotSettings;
19use language::{
20 Anchor, Bias, Buffer, BufferSnapshot, Language, PointUtf16, ToPointUtf16,
21 language_settings::{EditPredictionProvider, all_language_settings, language_settings},
22 point_from_lsp, point_to_lsp,
23};
24use lsp::{LanguageServer, LanguageServerBinary, LanguageServerId, LanguageServerName};
25use node_runtime::{NodeRuntime, VersionStrategy};
26use parking_lot::Mutex;
27use project::DisableAiSettings;
28use request::StatusNotification;
29use semver::Version;
30use serde_json::json;
31use settings::Settings;
32use settings::SettingsStore;
33use sign_in::{reinstall_and_sign_in_within_workspace, sign_out_within_workspace};
34use std::collections::hash_map::Entry;
35use std::{
36 any::TypeId,
37 env,
38 ffi::OsString,
39 mem,
40 ops::Range,
41 path::{Path, PathBuf},
42 sync::Arc,
43};
44use sum_tree::Dimensions;
45use util::rel_path::RelPath;
46use util::{ResultExt, fs::remove_matching};
47use workspace::Workspace;
48
49pub use crate::copilot_completion_provider::CopilotCompletionProvider;
50pub use crate::sign_in::{CopilotCodeVerification, initiate_sign_in, reinstall_and_sign_in};
51
52actions!(
53 copilot,
54 [
55 /// Requests a code completion suggestion from Copilot.
56 Suggest,
57 /// Cycles to the next Copilot suggestion.
58 NextSuggestion,
59 /// Cycles to the previous Copilot suggestion.
60 PreviousSuggestion,
61 /// Reinstalls the Copilot language server.
62 Reinstall,
63 /// Signs in to GitHub Copilot.
64 SignIn,
65 /// Signs out of GitHub Copilot.
66 SignOut
67 ]
68);
69
70pub fn init(
71 new_server_id: LanguageServerId,
72 fs: Arc<dyn Fs>,
73 http: Arc<dyn HttpClient>,
74 node_runtime: NodeRuntime,
75 cx: &mut App,
76) {
77 let language_settings = all_language_settings(None, cx);
78 let configuration = copilot_chat::CopilotChatConfiguration {
79 enterprise_uri: language_settings
80 .edit_predictions
81 .copilot
82 .enterprise_uri
83 .clone(),
84 };
85 copilot_chat::init(fs.clone(), http.clone(), configuration, cx);
86
87 let copilot = cx.new(move |cx| Copilot::start(new_server_id, fs, node_runtime, cx));
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::Uri,
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 ensure_node_version_for_copilot(&node_path).await?;
491
492 let arguments: Vec<OsString> = vec![server_path.into(), "--stdio".into()];
493 let binary = LanguageServerBinary {
494 path: node_path,
495 arguments,
496 env,
497 };
498
499 let root_path = if cfg!(target_os = "windows") {
500 Path::new("C:/")
501 } else {
502 Path::new("/")
503 };
504
505 let server_name = LanguageServerName("copilot".into());
506 let server = LanguageServer::new(
507 Arc::new(Mutex::new(None)),
508 new_server_id,
509 server_name,
510 binary,
511 root_path,
512 None,
513 Default::default(),
514 cx,
515 )?;
516
517 server
518 .on_notification::<StatusNotification, _>(|_, _| { /* Silence the notification */ })
519 .detach();
520
521 let configuration = lsp::DidChangeConfigurationParams {
522 settings: Default::default(),
523 };
524
525 let editor_info = request::SetEditorInfoParams {
526 editor_info: request::EditorInfo {
527 name: "zed".into(),
528 version: env!("CARGO_PKG_VERSION").into(),
529 },
530 editor_plugin_info: request::EditorPluginInfo {
531 name: "zed-copilot".into(),
532 version: "0.0.1".into(),
533 },
534 };
535 let editor_info_json = serde_json::to_value(&editor_info)?;
536
537 let server = cx
538 .update(|cx| {
539 let mut params = server.default_initialize_params(false, cx);
540 params.initialization_options = Some(editor_info_json);
541 server.initialize(params, configuration.into(), cx)
542 })?
543 .await?;
544
545 this.update(cx, |_, cx| notify_did_change_config_to_server(&server, cx))?
546 .context("copilot: did change configuration")?;
547
548 let status = server
549 .request::<request::CheckStatus>(request::CheckStatusParams {
550 local_checks_only: false,
551 })
552 .await
553 .into_response()
554 .context("copilot: check status")?;
555
556 anyhow::Ok((server, status))
557 };
558
559 let server = start_language_server.await;
560 this.update(cx, |this, cx| {
561 cx.notify();
562 match server {
563 Ok((server, status)) => {
564 this.server = CopilotServer::Running(RunningCopilotServer {
565 lsp: server,
566 sign_in_status: SignInStatus::SignedOut {
567 awaiting_signing_in: awaiting_sign_in_after_start,
568 },
569 registered_buffers: Default::default(),
570 });
571 cx.emit(Event::CopilotLanguageServerStarted);
572 this.update_sign_in_status(status, cx);
573 }
574 Err(error) => {
575 this.server = CopilotServer::Error(error.to_string().into());
576 cx.notify()
577 }
578 }
579 })
580 .ok();
581 }
582
583 pub(crate) fn sign_in(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
584 if let CopilotServer::Running(server) = &mut self.server {
585 let task = match &server.sign_in_status {
586 SignInStatus::Authorized => Task::ready(Ok(())).shared(),
587 SignInStatus::SigningIn { task, .. } => {
588 cx.notify();
589 task.clone()
590 }
591 SignInStatus::SignedOut { .. } | SignInStatus::Unauthorized => {
592 let lsp = server.lsp.clone();
593 let task = cx
594 .spawn(async move |this, cx| {
595 let sign_in = async {
596 let sign_in = lsp
597 .request::<request::SignInInitiate>(
598 request::SignInInitiateParams {},
599 )
600 .await
601 .into_response()
602 .context("copilot sign-in")?;
603 match sign_in {
604 request::SignInInitiateResult::AlreadySignedIn { user } => {
605 Ok(request::SignInStatus::Ok { user: Some(user) })
606 }
607 request::SignInInitiateResult::PromptUserDeviceFlow(flow) => {
608 this.update(cx, |this, cx| {
609 if let CopilotServer::Running(RunningCopilotServer {
610 sign_in_status: status,
611 ..
612 }) = &mut this.server
613 && let SignInStatus::SigningIn {
614 prompt: prompt_flow,
615 ..
616 } = status
617 {
618 *prompt_flow = Some(flow.clone());
619 cx.notify();
620 }
621 })?;
622 let response = lsp
623 .request::<request::SignInConfirm>(
624 request::SignInConfirmParams {
625 user_code: flow.user_code,
626 },
627 )
628 .await
629 .into_response()
630 .context("copilot: sign in confirm")?;
631 Ok(response)
632 }
633 }
634 };
635
636 let sign_in = sign_in.await;
637 this.update(cx, |this, cx| match sign_in {
638 Ok(status) => {
639 this.update_sign_in_status(status, cx);
640 Ok(())
641 }
642 Err(error) => {
643 this.update_sign_in_status(
644 request::SignInStatus::NotSignedIn,
645 cx,
646 );
647 Err(Arc::new(error))
648 }
649 })?
650 })
651 .shared();
652 server.sign_in_status = SignInStatus::SigningIn {
653 prompt: None,
654 task: task.clone(),
655 };
656 cx.notify();
657 task
658 }
659 };
660
661 cx.background_spawn(task.map_err(|err| anyhow!("{err:?}")))
662 } else {
663 // If we're downloading, wait until download is finished
664 // If we're in a stuck state, display to the user
665 Task::ready(Err(anyhow!("copilot hasn't started yet")))
666 }
667 }
668
669 pub(crate) fn sign_out(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
670 self.update_sign_in_status(request::SignInStatus::NotSignedIn, cx);
671 match &self.server {
672 CopilotServer::Running(RunningCopilotServer { lsp: server, .. }) => {
673 let server = server.clone();
674 cx.background_spawn(async move {
675 server
676 .request::<request::SignOut>(request::SignOutParams {})
677 .await
678 .into_response()
679 .context("copilot: sign in confirm")?;
680 anyhow::Ok(())
681 })
682 }
683 CopilotServer::Disabled => cx.background_spawn(async {
684 clear_copilot_config_dir().await;
685 anyhow::Ok(())
686 }),
687 _ => Task::ready(Err(anyhow!("copilot hasn't started yet"))),
688 }
689 }
690
691 pub(crate) fn reinstall(&mut self, cx: &mut Context<Self>) -> Shared<Task<()>> {
692 let language_settings = all_language_settings(None, cx);
693 let env = self.build_env(&language_settings.edit_predictions.copilot);
694 let start_task = cx
695 .spawn({
696 let fs = self.fs.clone();
697 let node_runtime = self.node_runtime.clone();
698 let server_id = self.server_id;
699 async move |this, cx| {
700 clear_copilot_dir().await;
701 Self::start_language_server(server_id, fs, node_runtime, env, this, false, cx)
702 .await
703 }
704 })
705 .shared();
706
707 self.server = CopilotServer::Starting {
708 task: start_task.clone(),
709 };
710
711 cx.notify();
712
713 start_task
714 }
715
716 pub fn language_server(&self) -> Option<&Arc<LanguageServer>> {
717 if let CopilotServer::Running(server) = &self.server {
718 Some(&server.lsp)
719 } else {
720 None
721 }
722 }
723
724 pub fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) {
725 let weak_buffer = buffer.downgrade();
726 self.buffers.insert(weak_buffer.clone());
727
728 if let CopilotServer::Running(RunningCopilotServer {
729 lsp: server,
730 sign_in_status: status,
731 registered_buffers,
732 ..
733 }) = &mut self.server
734 {
735 if !matches!(status, SignInStatus::Authorized) {
736 return;
737 }
738
739 let entry = registered_buffers.entry(buffer.entity_id());
740 if let Entry::Vacant(e) = entry {
741 let Ok(uri) = uri_for_buffer(buffer, cx) else {
742 return;
743 };
744 let language_id = id_for_language(buffer.read(cx).language());
745 let snapshot = buffer.read(cx).snapshot();
746 server
747 .notify::<lsp::notification::DidOpenTextDocument>(
748 lsp::DidOpenTextDocumentParams {
749 text_document: lsp::TextDocumentItem {
750 uri: uri.clone(),
751 language_id: language_id.clone(),
752 version: 0,
753 text: snapshot.text(),
754 },
755 },
756 )
757 .ok();
758
759 e.insert(RegisteredBuffer {
760 uri,
761 language_id,
762 snapshot,
763 snapshot_version: 0,
764 pending_buffer_change: Task::ready(Some(())),
765 _subscriptions: [
766 cx.subscribe(buffer, |this, buffer, event, cx| {
767 this.handle_buffer_event(buffer, event, cx).log_err();
768 }),
769 cx.observe_release(buffer, move |this, _buffer, _cx| {
770 this.buffers.remove(&weak_buffer);
771 this.unregister_buffer(&weak_buffer);
772 }),
773 ],
774 });
775 }
776 }
777 }
778
779 fn handle_buffer_event(
780 &mut self,
781 buffer: Entity<Buffer>,
782 event: &language::BufferEvent,
783 cx: &mut Context<Self>,
784 ) -> Result<()> {
785 if let Ok(server) = self.server.as_running()
786 && let Some(registered_buffer) = server.registered_buffers.get_mut(&buffer.entity_id())
787 {
788 match event {
789 language::BufferEvent::Edited => {
790 drop(registered_buffer.report_changes(&buffer, cx));
791 }
792 language::BufferEvent::Saved => {
793 server
794 .lsp
795 .notify::<lsp::notification::DidSaveTextDocument>(
796 lsp::DidSaveTextDocumentParams {
797 text_document: lsp::TextDocumentIdentifier::new(
798 registered_buffer.uri.clone(),
799 ),
800 text: None,
801 },
802 )
803 .ok();
804 }
805 language::BufferEvent::FileHandleChanged
806 | language::BufferEvent::LanguageChanged => {
807 let new_language_id = id_for_language(buffer.read(cx).language());
808 let Ok(new_uri) = uri_for_buffer(&buffer, cx) else {
809 return Ok(());
810 };
811 if new_uri != registered_buffer.uri
812 || new_language_id != registered_buffer.language_id
813 {
814 let old_uri = mem::replace(&mut registered_buffer.uri, new_uri);
815 registered_buffer.language_id = new_language_id;
816 server
817 .lsp
818 .notify::<lsp::notification::DidCloseTextDocument>(
819 lsp::DidCloseTextDocumentParams {
820 text_document: lsp::TextDocumentIdentifier::new(old_uri),
821 },
822 )
823 .ok();
824 server
825 .lsp
826 .notify::<lsp::notification::DidOpenTextDocument>(
827 lsp::DidOpenTextDocumentParams {
828 text_document: lsp::TextDocumentItem::new(
829 registered_buffer.uri.clone(),
830 registered_buffer.language_id.clone(),
831 registered_buffer.snapshot_version,
832 registered_buffer.snapshot.text(),
833 ),
834 },
835 )
836 .ok();
837 }
838 }
839 _ => {}
840 }
841 }
842
843 Ok(())
844 }
845
846 fn unregister_buffer(&mut self, buffer: &WeakEntity<Buffer>) {
847 if let Ok(server) = self.server.as_running()
848 && let Some(buffer) = server.registered_buffers.remove(&buffer.entity_id())
849 {
850 server
851 .lsp
852 .notify::<lsp::notification::DidCloseTextDocument>(
853 lsp::DidCloseTextDocumentParams {
854 text_document: lsp::TextDocumentIdentifier::new(buffer.uri),
855 },
856 )
857 .ok();
858 }
859 }
860
861 pub fn completions<T>(
862 &mut self,
863 buffer: &Entity<Buffer>,
864 position: T,
865 cx: &mut Context<Self>,
866 ) -> Task<Result<Vec<Completion>>>
867 where
868 T: ToPointUtf16,
869 {
870 self.request_completions::<request::GetCompletions, _>(buffer, position, cx)
871 }
872
873 pub fn completions_cycling<T>(
874 &mut self,
875 buffer: &Entity<Buffer>,
876 position: T,
877 cx: &mut Context<Self>,
878 ) -> Task<Result<Vec<Completion>>>
879 where
880 T: ToPointUtf16,
881 {
882 self.request_completions::<request::GetCompletionsCycling, _>(buffer, position, cx)
883 }
884
885 pub fn accept_completion(
886 &mut self,
887 completion: &Completion,
888 cx: &mut Context<Self>,
889 ) -> Task<Result<()>> {
890 let server = match self.server.as_authenticated() {
891 Ok(server) => server,
892 Err(error) => return Task::ready(Err(error)),
893 };
894 let request =
895 server
896 .lsp
897 .request::<request::NotifyAccepted>(request::NotifyAcceptedParams {
898 uuid: completion.uuid.clone(),
899 });
900 cx.background_spawn(async move {
901 request
902 .await
903 .into_response()
904 .context("copilot: notify accepted")?;
905 Ok(())
906 })
907 }
908
909 pub fn discard_completions(
910 &mut self,
911 completions: &[Completion],
912 cx: &mut Context<Self>,
913 ) -> Task<Result<()>> {
914 let server = match self.server.as_authenticated() {
915 Ok(server) => server,
916 Err(_) => return Task::ready(Ok(())),
917 };
918 let request =
919 server
920 .lsp
921 .request::<request::NotifyRejected>(request::NotifyRejectedParams {
922 uuids: completions
923 .iter()
924 .map(|completion| completion.uuid.clone())
925 .collect(),
926 });
927 cx.background_spawn(async move {
928 request
929 .await
930 .into_response()
931 .context("copilot: notify rejected")?;
932 Ok(())
933 })
934 }
935
936 fn request_completions<R, T>(
937 &mut self,
938 buffer: &Entity<Buffer>,
939 position: T,
940 cx: &mut Context<Self>,
941 ) -> Task<Result<Vec<Completion>>>
942 where
943 R: 'static
944 + lsp::request::Request<
945 Params = request::GetCompletionsParams,
946 Result = request::GetCompletionsResult,
947 >,
948 T: ToPointUtf16,
949 {
950 self.register_buffer(buffer, cx);
951
952 let server = match self.server.as_authenticated() {
953 Ok(server) => server,
954 Err(error) => return Task::ready(Err(error)),
955 };
956 let lsp = server.lsp.clone();
957 let registered_buffer = server
958 .registered_buffers
959 .get_mut(&buffer.entity_id())
960 .unwrap();
961 let snapshot = registered_buffer.report_changes(buffer, cx);
962 let buffer = buffer.read(cx);
963 let uri = registered_buffer.uri.clone();
964 let position = position.to_point_utf16(buffer);
965 let settings = language_settings(
966 buffer.language_at(position).map(|l| l.name()),
967 buffer.file(),
968 cx,
969 );
970 let tab_size = settings.tab_size;
971 let hard_tabs = settings.hard_tabs;
972 let relative_path = buffer
973 .file()
974 .map_or(RelPath::empty().into(), |file| file.path().clone());
975
976 cx.background_spawn(async move {
977 let (version, snapshot) = snapshot.await?;
978 let result = lsp
979 .request::<R>(request::GetCompletionsParams {
980 doc: request::GetCompletionsDocument {
981 uri,
982 tab_size: tab_size.into(),
983 indent_size: 1,
984 insert_spaces: !hard_tabs,
985 relative_path: relative_path.to_proto(),
986 position: point_to_lsp(position),
987 version: version.try_into().unwrap(),
988 },
989 })
990 .await
991 .into_response()
992 .context("copilot: get completions")?;
993 let completions = result
994 .completions
995 .into_iter()
996 .map(|completion| {
997 let start = snapshot
998 .clip_point_utf16(point_from_lsp(completion.range.start), Bias::Left);
999 let end =
1000 snapshot.clip_point_utf16(point_from_lsp(completion.range.end), Bias::Left);
1001 Completion {
1002 uuid: completion.uuid,
1003 range: snapshot.anchor_before(start)..snapshot.anchor_after(end),
1004 text: completion.text,
1005 }
1006 })
1007 .collect();
1008 anyhow::Ok(completions)
1009 })
1010 }
1011
1012 pub fn status(&self) -> Status {
1013 match &self.server {
1014 CopilotServer::Starting { task } => Status::Starting { task: task.clone() },
1015 CopilotServer::Disabled => Status::Disabled,
1016 CopilotServer::Error(error) => Status::Error(error.clone()),
1017 CopilotServer::Running(RunningCopilotServer { sign_in_status, .. }) => {
1018 match sign_in_status {
1019 SignInStatus::Authorized => Status::Authorized,
1020 SignInStatus::Unauthorized => Status::Unauthorized,
1021 SignInStatus::SigningIn { prompt, .. } => Status::SigningIn {
1022 prompt: prompt.clone(),
1023 },
1024 SignInStatus::SignedOut {
1025 awaiting_signing_in,
1026 } => Status::SignedOut {
1027 awaiting_signing_in: *awaiting_signing_in,
1028 },
1029 }
1030 }
1031 }
1032 }
1033
1034 fn update_sign_in_status(&mut self, lsp_status: request::SignInStatus, cx: &mut Context<Self>) {
1035 self.buffers.retain(|buffer| buffer.is_upgradable());
1036
1037 if let Ok(server) = self.server.as_running() {
1038 match lsp_status {
1039 request::SignInStatus::Ok { user: Some(_) }
1040 | request::SignInStatus::MaybeOk { .. }
1041 | request::SignInStatus::AlreadySignedIn { .. } => {
1042 server.sign_in_status = SignInStatus::Authorized;
1043 cx.emit(Event::CopilotAuthSignedIn);
1044 for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1045 if let Some(buffer) = buffer.upgrade() {
1046 self.register_buffer(&buffer, cx);
1047 }
1048 }
1049 }
1050 request::SignInStatus::NotAuthorized { .. } => {
1051 server.sign_in_status = SignInStatus::Unauthorized;
1052 for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1053 self.unregister_buffer(&buffer);
1054 }
1055 }
1056 request::SignInStatus::Ok { user: None } | request::SignInStatus::NotSignedIn => {
1057 if !matches!(server.sign_in_status, SignInStatus::SignedOut { .. }) {
1058 server.sign_in_status = SignInStatus::SignedOut {
1059 awaiting_signing_in: false,
1060 };
1061 }
1062 cx.emit(Event::CopilotAuthSignedOut);
1063 for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1064 self.unregister_buffer(&buffer);
1065 }
1066 }
1067 }
1068
1069 cx.notify();
1070 }
1071 }
1072
1073 fn update_action_visibilities(&self, cx: &mut App) {
1074 let signed_in_actions = [
1075 TypeId::of::<Suggest>(),
1076 TypeId::of::<NextSuggestion>(),
1077 TypeId::of::<PreviousSuggestion>(),
1078 TypeId::of::<Reinstall>(),
1079 ];
1080 let auth_actions = [TypeId::of::<SignOut>()];
1081 let no_auth_actions = [TypeId::of::<SignIn>()];
1082 let status = self.status();
1083
1084 let is_ai_disabled = DisableAiSettings::get_global(cx).disable_ai;
1085 let filter = CommandPaletteFilter::global_mut(cx);
1086
1087 if is_ai_disabled {
1088 filter.hide_action_types(&signed_in_actions);
1089 filter.hide_action_types(&auth_actions);
1090 filter.hide_action_types(&no_auth_actions);
1091 } else {
1092 match status {
1093 Status::Disabled => {
1094 filter.hide_action_types(&signed_in_actions);
1095 filter.hide_action_types(&auth_actions);
1096 filter.hide_action_types(&no_auth_actions);
1097 }
1098 Status::Authorized => {
1099 filter.hide_action_types(&no_auth_actions);
1100 filter.show_action_types(signed_in_actions.iter().chain(&auth_actions));
1101 }
1102 _ => {
1103 filter.hide_action_types(&signed_in_actions);
1104 filter.hide_action_types(&auth_actions);
1105 filter.show_action_types(&no_auth_actions);
1106 }
1107 }
1108 }
1109 }
1110}
1111
1112fn id_for_language(language: Option<&Arc<Language>>) -> String {
1113 language
1114 .map(|language| language.lsp_id())
1115 .unwrap_or_else(|| "plaintext".to_string())
1116}
1117
1118fn uri_for_buffer(buffer: &Entity<Buffer>, cx: &App) -> Result<lsp::Uri, ()> {
1119 if let Some(file) = buffer.read(cx).file().and_then(|file| file.as_local()) {
1120 lsp::Uri::from_file_path(file.abs_path(cx))
1121 } else {
1122 format!("buffer://{}", buffer.entity_id())
1123 .parse()
1124 .map_err(|_| ())
1125 }
1126}
1127
1128fn notify_did_change_config_to_server(
1129 server: &Arc<LanguageServer>,
1130 cx: &mut Context<Copilot>,
1131) -> std::result::Result<(), anyhow::Error> {
1132 let copilot_settings = all_language_settings(None, cx)
1133 .edit_predictions
1134 .copilot
1135 .clone();
1136
1137 if let Some(copilot_chat) = copilot_chat::CopilotChat::global(cx) {
1138 copilot_chat.update(cx, |chat, cx| {
1139 chat.set_configuration(
1140 copilot_chat::CopilotChatConfiguration {
1141 enterprise_uri: copilot_settings.enterprise_uri.clone(),
1142 },
1143 cx,
1144 );
1145 });
1146 }
1147
1148 let settings = json!({
1149 "http": {
1150 "proxy": copilot_settings.proxy,
1151 "proxyStrictSSL": !copilot_settings.proxy_no_verify.unwrap_or(false)
1152 },
1153 "github-enterprise": {
1154 "uri": copilot_settings.enterprise_uri
1155 }
1156 });
1157
1158 server
1159 .notify::<lsp::notification::DidChangeConfiguration>(lsp::DidChangeConfigurationParams {
1160 settings,
1161 })
1162 .ok();
1163 Ok(())
1164}
1165
1166async fn clear_copilot_dir() {
1167 remove_matching(paths::copilot_dir(), |_| true).await
1168}
1169
1170async fn clear_copilot_config_dir() {
1171 remove_matching(copilot_chat::copilot_chat_config_dir(), |_| true).await
1172}
1173
1174async fn ensure_node_version_for_copilot(node_path: &Path) -> anyhow::Result<()> {
1175 const MIN_COPILOT_NODE_VERSION: Version = Version::new(20, 8, 0);
1176
1177 log::info!("Checking Node.js version for Copilot at: {:?}", node_path);
1178
1179 let output = util::command::new_smol_command(node_path)
1180 .arg("--version")
1181 .output()
1182 .await
1183 .with_context(|| format!("checking Node.js version at {:?}", node_path))?;
1184
1185 if !output.status.success() {
1186 anyhow::bail!(
1187 "failed to run node --version for Copilot. stdout: {}, stderr: {}",
1188 String::from_utf8_lossy(&output.stdout),
1189 String::from_utf8_lossy(&output.stderr),
1190 );
1191 }
1192
1193 let version_str = String::from_utf8_lossy(&output.stdout);
1194 let version = Version::parse(version_str.trim().trim_start_matches('v'))
1195 .with_context(|| format!("parsing Node.js version from '{}'", version_str.trim()))?;
1196
1197 if version < MIN_COPILOT_NODE_VERSION {
1198 anyhow::bail!(
1199 "GitHub Copilot language server requires Node.js {MIN_COPILOT_NODE_VERSION} or later, but found {version}. \
1200 Please update your Node.js version or configure a different Node.js path in settings."
1201 );
1202 }
1203
1204 log::info!(
1205 "Node.js version {} meets Copilot requirements (>= {})",
1206 version,
1207 MIN_COPILOT_NODE_VERSION
1208 );
1209 Ok(())
1210}
1211
1212async fn get_copilot_lsp(fs: Arc<dyn Fs>, node_runtime: NodeRuntime) -> anyhow::Result<PathBuf> {
1213 const PACKAGE_NAME: &str = "@github/copilot-language-server";
1214 const SERVER_PATH: &str =
1215 "node_modules/@github/copilot-language-server/dist/language-server.js";
1216
1217 let latest_version = node_runtime
1218 .npm_package_latest_version(PACKAGE_NAME)
1219 .await?;
1220 let server_path = paths::copilot_dir().join(SERVER_PATH);
1221
1222 fs.create_dir(paths::copilot_dir()).await?;
1223
1224 let should_install = node_runtime
1225 .should_install_npm_package(
1226 PACKAGE_NAME,
1227 &server_path,
1228 paths::copilot_dir(),
1229 VersionStrategy::Latest(&latest_version),
1230 )
1231 .await;
1232 if should_install {
1233 node_runtime
1234 .npm_install_packages(paths::copilot_dir(), &[(PACKAGE_NAME, &latest_version)])
1235 .await?;
1236 }
1237
1238 Ok(server_path)
1239}
1240
1241#[cfg(test)]
1242mod tests {
1243 use super::*;
1244 use gpui::TestAppContext;
1245 use util::{path, paths::PathStyle, rel_path::rel_path};
1246
1247 #[gpui::test(iterations = 10)]
1248 async fn test_buffer_management(cx: &mut TestAppContext) {
1249 let (copilot, mut lsp) = Copilot::fake(cx);
1250
1251 let buffer_1 = cx.new(|cx| Buffer::local("Hello", cx));
1252 let buffer_1_uri: lsp::Uri = format!("buffer://{}", buffer_1.entity_id().as_u64())
1253 .parse()
1254 .unwrap();
1255 copilot.update(cx, |copilot, cx| copilot.register_buffer(&buffer_1, cx));
1256 assert_eq!(
1257 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1258 .await,
1259 lsp::DidOpenTextDocumentParams {
1260 text_document: lsp::TextDocumentItem::new(
1261 buffer_1_uri.clone(),
1262 "plaintext".into(),
1263 0,
1264 "Hello".into()
1265 ),
1266 }
1267 );
1268
1269 let buffer_2 = cx.new(|cx| Buffer::local("Goodbye", cx));
1270 let buffer_2_uri: lsp::Uri = format!("buffer://{}", buffer_2.entity_id().as_u64())
1271 .parse()
1272 .unwrap();
1273 copilot.update(cx, |copilot, cx| copilot.register_buffer(&buffer_2, cx));
1274 assert_eq!(
1275 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1276 .await,
1277 lsp::DidOpenTextDocumentParams {
1278 text_document: lsp::TextDocumentItem::new(
1279 buffer_2_uri.clone(),
1280 "plaintext".into(),
1281 0,
1282 "Goodbye".into()
1283 ),
1284 }
1285 );
1286
1287 buffer_1.update(cx, |buffer, cx| buffer.edit([(5..5, " world")], None, cx));
1288 assert_eq!(
1289 lsp.receive_notification::<lsp::notification::DidChangeTextDocument>()
1290 .await,
1291 lsp::DidChangeTextDocumentParams {
1292 text_document: lsp::VersionedTextDocumentIdentifier::new(buffer_1_uri.clone(), 1),
1293 content_changes: vec![lsp::TextDocumentContentChangeEvent {
1294 range: Some(lsp::Range::new(
1295 lsp::Position::new(0, 5),
1296 lsp::Position::new(0, 5)
1297 )),
1298 range_length: None,
1299 text: " world".into(),
1300 }],
1301 }
1302 );
1303
1304 // Ensure updates to the file are reflected in the LSP.
1305 buffer_1.update(cx, |buffer, cx| {
1306 buffer.file_updated(
1307 Arc::new(File {
1308 abs_path: path!("/root/child/buffer-1").into(),
1309 path: rel_path("child/buffer-1").into(),
1310 }),
1311 cx,
1312 )
1313 });
1314 assert_eq!(
1315 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1316 .await,
1317 lsp::DidCloseTextDocumentParams {
1318 text_document: lsp::TextDocumentIdentifier::new(buffer_1_uri),
1319 }
1320 );
1321 let buffer_1_uri = lsp::Uri::from_file_path(path!("/root/child/buffer-1")).unwrap();
1322 assert_eq!(
1323 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1324 .await,
1325 lsp::DidOpenTextDocumentParams {
1326 text_document: lsp::TextDocumentItem::new(
1327 buffer_1_uri.clone(),
1328 "plaintext".into(),
1329 1,
1330 "Hello world".into()
1331 ),
1332 }
1333 );
1334
1335 // Ensure all previously-registered buffers are closed when signing out.
1336 lsp.set_request_handler::<request::SignOut, _, _>(|_, _| async {
1337 Ok(request::SignOutResult {})
1338 });
1339 copilot
1340 .update(cx, |copilot, cx| copilot.sign_out(cx))
1341 .await
1342 .unwrap();
1343 assert_eq!(
1344 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1345 .await,
1346 lsp::DidCloseTextDocumentParams {
1347 text_document: lsp::TextDocumentIdentifier::new(buffer_1_uri.clone()),
1348 }
1349 );
1350 assert_eq!(
1351 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1352 .await,
1353 lsp::DidCloseTextDocumentParams {
1354 text_document: lsp::TextDocumentIdentifier::new(buffer_2_uri.clone()),
1355 }
1356 );
1357
1358 // Ensure all previously-registered buffers are re-opened when signing in.
1359 lsp.set_request_handler::<request::SignInInitiate, _, _>(|_, _| async {
1360 Ok(request::SignInInitiateResult::AlreadySignedIn {
1361 user: "user-1".into(),
1362 })
1363 });
1364 copilot
1365 .update(cx, |copilot, cx| copilot.sign_in(cx))
1366 .await
1367 .unwrap();
1368
1369 assert_eq!(
1370 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1371 .await,
1372 lsp::DidOpenTextDocumentParams {
1373 text_document: lsp::TextDocumentItem::new(
1374 buffer_1_uri.clone(),
1375 "plaintext".into(),
1376 0,
1377 "Hello world".into()
1378 ),
1379 }
1380 );
1381 assert_eq!(
1382 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1383 .await,
1384 lsp::DidOpenTextDocumentParams {
1385 text_document: lsp::TextDocumentItem::new(
1386 buffer_2_uri.clone(),
1387 "plaintext".into(),
1388 0,
1389 "Goodbye".into()
1390 ),
1391 }
1392 );
1393 // Dropping a buffer causes it to be closed on the LSP side as well.
1394 cx.update(|_| drop(buffer_2));
1395 assert_eq!(
1396 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1397 .await,
1398 lsp::DidCloseTextDocumentParams {
1399 text_document: lsp::TextDocumentIdentifier::new(buffer_2_uri),
1400 }
1401 );
1402 }
1403
1404 struct File {
1405 abs_path: PathBuf,
1406 path: Arc<RelPath>,
1407 }
1408
1409 impl language::File for File {
1410 fn as_local(&self) -> Option<&dyn language::LocalFile> {
1411 Some(self)
1412 }
1413
1414 fn disk_state(&self) -> language::DiskState {
1415 language::DiskState::Present {
1416 mtime: ::fs::MTime::from_seconds_and_nanos(100, 42),
1417 }
1418 }
1419
1420 fn path(&self) -> &Arc<RelPath> {
1421 &self.path
1422 }
1423
1424 fn path_style(&self, _: &App) -> PathStyle {
1425 PathStyle::local()
1426 }
1427
1428 fn full_path(&self, _: &App) -> PathBuf {
1429 unimplemented!()
1430 }
1431
1432 fn file_name<'a>(&'a self, _: &'a App) -> &'a str {
1433 unimplemented!()
1434 }
1435
1436 fn to_proto(&self, _: &App) -> rpc::proto::File {
1437 unimplemented!()
1438 }
1439
1440 fn worktree_id(&self, _: &App) -> settings::WorktreeId {
1441 settings::WorktreeId::from_usize(0)
1442 }
1443
1444 fn is_private(&self) -> bool {
1445 false
1446 }
1447 }
1448
1449 impl language::LocalFile for File {
1450 fn abs_path(&self, _: &App) -> PathBuf {
1451 self.abs_path.clone()
1452 }
1453
1454 fn load(&self, _: &App) -> Task<Result<String>> {
1455 unimplemented!()
1456 }
1457
1458 fn load_bytes(&self, _cx: &App) -> Task<Result<Vec<u8>>> {
1459 unimplemented!()
1460 }
1461 }
1462}
1463
1464#[cfg(test)]
1465#[ctor::ctor]
1466fn init_logger() {
1467 zlog::init_test();
1468}