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