1pub mod copilot_chat;
2mod copilot_completion_provider;
3pub mod request;
4mod sign_in;
5
6use crate::sign_in::initiate_sign_in_within_workspace;
7use ::fs::Fs;
8use anyhow::{Context as _, Result, anyhow};
9use collections::{HashMap, HashSet};
10use command_palette_hooks::CommandPaletteFilter;
11use futures::{Future, FutureExt, TryFutureExt, channel::oneshot, future::Shared};
12use gpui::{
13 App, AppContext as _, AsyncApp, Context, Entity, EntityId, EventEmitter, Global, Task,
14 WeakEntity, actions,
15};
16use http_client::HttpClient;
17use language::language_settings::CopilotSettings;
18use language::{
19 Anchor, Bias, Buffer, BufferSnapshot, Language, PointUtf16, ToPointUtf16,
20 language_settings::{EditPredictionProvider, all_language_settings, language_settings},
21 point_from_lsp, point_to_lsp,
22};
23use lsp::{LanguageServer, LanguageServerBinary, LanguageServerId, LanguageServerName};
24use node_runtime::{NodeRuntime, VersionStrategy};
25use parking_lot::Mutex;
26use project::DisableAiSettings;
27use request::StatusNotification;
28use serde_json::json;
29use settings::Settings;
30use settings::SettingsStore;
31use sign_in::{reinstall_and_sign_in_within_workspace, sign_out_within_workspace};
32use std::collections::hash_map::Entry;
33use std::{
34 any::TypeId,
35 env,
36 ffi::OsString,
37 mem,
38 ops::Range,
39 path::{Path, PathBuf},
40 sync::Arc,
41};
42use sum_tree::Dimensions;
43use util::{ResultExt, fs::remove_matching};
44use workspace::Workspace;
45
46pub use crate::copilot_completion_provider::CopilotCompletionProvider;
47pub use crate::sign_in::{CopilotCodeVerification, initiate_sign_in, reinstall_and_sign_in};
48
49actions!(
50 copilot,
51 [
52 /// Requests a code completion suggestion from Copilot.
53 Suggest,
54 /// Cycles to the next Copilot suggestion.
55 NextSuggestion,
56 /// Cycles to the previous Copilot suggestion.
57 PreviousSuggestion,
58 /// Reinstalls the Copilot language server.
59 Reinstall,
60 /// Signs in to GitHub Copilot.
61 SignIn,
62 /// Signs out of GitHub Copilot.
63 SignOut
64 ]
65);
66
67pub fn init(
68 new_server_id: LanguageServerId,
69 fs: Arc<dyn Fs>,
70 http: Arc<dyn HttpClient>,
71 node_runtime: NodeRuntime,
72 cx: &mut App,
73) {
74 let language_settings = all_language_settings(None, cx);
75 let configuration = copilot_chat::CopilotChatConfiguration {
76 enterprise_uri: language_settings
77 .edit_predictions
78 .copilot
79 .enterprise_uri
80 .clone(),
81 };
82 copilot_chat::init(fs.clone(), http.clone(), configuration, cx);
83
84 let copilot = cx.new({
85 let node_runtime = node_runtime.clone();
86 move |cx| Copilot::start(new_server_id, fs, node_runtime, cx)
87 });
88 Copilot::set_global(copilot.clone(), cx);
89 cx.observe(&copilot, |copilot, cx| {
90 copilot.update(cx, |copilot, cx| copilot.update_action_visibilities(cx));
91 })
92 .detach();
93 cx.observe_global::<SettingsStore>(|cx| {
94 if let Some(copilot) = Copilot::global(cx) {
95 copilot.update(cx, |copilot, cx| copilot.update_action_visibilities(cx));
96 }
97 })
98 .detach();
99
100 cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
101 workspace.register_action(|workspace, _: &SignIn, window, cx| {
102 if let Some(copilot) = Copilot::global(cx) {
103 let is_reinstall = false;
104 initiate_sign_in_within_workspace(workspace, copilot, is_reinstall, window, cx);
105 }
106 });
107 workspace.register_action(|workspace, _: &Reinstall, window, cx| {
108 if let Some(copilot) = Copilot::global(cx) {
109 reinstall_and_sign_in_within_workspace(workspace, copilot, window, cx);
110 }
111 });
112 workspace.register_action(|workspace, _: &SignOut, _window, cx| {
113 if let Some(copilot) = Copilot::global(cx) {
114 sign_out_within_workspace(workspace, copilot, cx);
115 }
116 });
117 })
118 .detach();
119}
120
121enum CopilotServer {
122 Disabled,
123 Starting { task: Shared<Task<()>> },
124 Error(Arc<str>),
125 Running(RunningCopilotServer),
126}
127
128impl CopilotServer {
129 fn as_authenticated(&mut self) -> Result<&mut RunningCopilotServer> {
130 let server = self.as_running()?;
131 anyhow::ensure!(
132 matches!(server.sign_in_status, SignInStatus::Authorized { .. }),
133 "must sign in before using copilot"
134 );
135 Ok(server)
136 }
137
138 fn as_running(&mut self) -> Result<&mut RunningCopilotServer> {
139 match self {
140 CopilotServer::Starting { .. } => anyhow::bail!("copilot is still starting"),
141 CopilotServer::Disabled => anyhow::bail!("copilot is disabled"),
142 CopilotServer::Error(error) => {
143 anyhow::bail!("copilot was not started because of an error: {error}")
144 }
145 CopilotServer::Running(server) => Ok(server),
146 }
147 }
148}
149
150struct RunningCopilotServer {
151 lsp: Arc<LanguageServer>,
152 sign_in_status: SignInStatus,
153 registered_buffers: HashMap<EntityId, RegisteredBuffer>,
154}
155
156#[derive(Clone, Debug)]
157enum SignInStatus {
158 Authorized,
159 Unauthorized,
160 SigningIn {
161 prompt: Option<request::PromptUserDeviceFlow>,
162 task: Shared<Task<Result<(), Arc<anyhow::Error>>>>,
163 },
164 SignedOut {
165 awaiting_signing_in: bool,
166 },
167}
168
169#[derive(Debug, Clone)]
170pub enum Status {
171 Starting {
172 task: Shared<Task<()>>,
173 },
174 Error(Arc<str>),
175 Disabled,
176 SignedOut {
177 awaiting_signing_in: bool,
178 },
179 SigningIn {
180 prompt: Option<request::PromptUserDeviceFlow>,
181 },
182 Unauthorized,
183 Authorized,
184}
185
186impl Status {
187 pub fn is_authorized(&self) -> bool {
188 matches!(self, Status::Authorized)
189 }
190
191 pub fn is_configured(&self) -> bool {
192 matches!(
193 self,
194 Status::Starting { .. }
195 | Status::Error(_)
196 | Status::SigningIn { .. }
197 | Status::Authorized
198 )
199 }
200}
201
202struct RegisteredBuffer {
203 uri: lsp::Url,
204 language_id: String,
205 snapshot: BufferSnapshot,
206 snapshot_version: i32,
207 _subscriptions: [gpui::Subscription; 2],
208 pending_buffer_change: Task<Option<()>>,
209}
210
211impl RegisteredBuffer {
212 fn report_changes(
213 &mut self,
214 buffer: &Entity<Buffer>,
215 cx: &mut Context<Copilot>,
216 ) -> oneshot::Receiver<(i32, BufferSnapshot)> {
217 let (done_tx, done_rx) = oneshot::channel();
218
219 if buffer.read(cx).version() == self.snapshot.version {
220 let _ = done_tx.send((self.snapshot_version, self.snapshot.clone()));
221 } else {
222 let buffer = buffer.downgrade();
223 let id = buffer.entity_id();
224 let prev_pending_change =
225 mem::replace(&mut self.pending_buffer_change, Task::ready(None));
226 self.pending_buffer_change = cx.spawn(async move |copilot, cx| {
227 prev_pending_change.await;
228
229 let old_version = copilot
230 .update(cx, |copilot, _| {
231 let server = copilot.server.as_authenticated().log_err()?;
232 let buffer = server.registered_buffers.get_mut(&id)?;
233 Some(buffer.snapshot.version.clone())
234 })
235 .ok()??;
236 let new_snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot()).ok()?;
237
238 let content_changes = cx
239 .background_spawn({
240 let new_snapshot = new_snapshot.clone();
241 async move {
242 new_snapshot
243 .edits_since::<Dimensions<PointUtf16, usize>>(&old_version)
244 .map(|edit| {
245 let edit_start = edit.new.start.0;
246 let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
247 let new_text = new_snapshot
248 .text_for_range(edit.new.start.1..edit.new.end.1)
249 .collect();
250 lsp::TextDocumentContentChangeEvent {
251 range: Some(lsp::Range::new(
252 point_to_lsp(edit_start),
253 point_to_lsp(edit_end),
254 )),
255 range_length: None,
256 text: new_text,
257 }
258 })
259 .collect::<Vec<_>>()
260 }
261 })
262 .await;
263
264 copilot
265 .update(cx, |copilot, _| {
266 let server = copilot.server.as_authenticated().log_err()?;
267 let buffer = server.registered_buffers.get_mut(&id)?;
268 if !content_changes.is_empty() {
269 buffer.snapshot_version += 1;
270 buffer.snapshot = new_snapshot;
271 server
272 .lsp
273 .notify::<lsp::notification::DidChangeTextDocument>(
274 &lsp::DidChangeTextDocumentParams {
275 text_document: lsp::VersionedTextDocumentIdentifier::new(
276 buffer.uri.clone(),
277 buffer.snapshot_version,
278 ),
279 content_changes,
280 },
281 )
282 .ok();
283 }
284 let _ = done_tx.send((buffer.snapshot_version, buffer.snapshot.clone()));
285 Some(())
286 })
287 .ok()?;
288
289 Some(())
290 });
291 }
292
293 done_rx
294 }
295}
296
297#[derive(Debug)]
298pub struct Completion {
299 pub uuid: String,
300 pub range: Range<Anchor>,
301 pub text: String,
302}
303
304pub struct Copilot {
305 fs: Arc<dyn Fs>,
306 node_runtime: NodeRuntime,
307 server: CopilotServer,
308 buffers: HashSet<WeakEntity<Buffer>>,
309 server_id: LanguageServerId,
310 _subscription: gpui::Subscription,
311}
312
313pub enum Event {
314 CopilotLanguageServerStarted,
315 CopilotAuthSignedIn,
316 CopilotAuthSignedOut,
317}
318
319impl EventEmitter<Event> for Copilot {}
320
321struct GlobalCopilot(Entity<Copilot>);
322
323impl Global for GlobalCopilot {}
324
325impl Copilot {
326 pub fn global(cx: &App) -> Option<Entity<Self>> {
327 cx.try_global::<GlobalCopilot>()
328 .map(|model| model.0.clone())
329 }
330
331 pub fn set_global(copilot: Entity<Self>, cx: &mut App) {
332 cx.set_global(GlobalCopilot(copilot));
333 }
334
335 fn start(
336 new_server_id: LanguageServerId,
337 fs: Arc<dyn Fs>,
338 node_runtime: NodeRuntime,
339 cx: &mut Context<Self>,
340 ) -> Self {
341 let mut this = Self {
342 server_id: new_server_id,
343 fs,
344 node_runtime,
345 server: CopilotServer::Disabled,
346 buffers: Default::default(),
347 _subscription: cx.on_app_quit(Self::shutdown_language_server),
348 };
349 this.start_copilot(true, false, cx);
350 cx.observe_global::<SettingsStore>(move |this, cx| {
351 this.start_copilot(true, false, cx);
352 if let Ok(server) = this.server.as_running() {
353 notify_did_change_config_to_server(&server.lsp, cx)
354 .context("copilot setting change: did change configuration")
355 .log_err();
356 }
357 })
358 .detach();
359 this
360 }
361
362 fn shutdown_language_server(
363 &mut self,
364 _cx: &mut Context<Self>,
365 ) -> impl Future<Output = ()> + use<> {
366 let shutdown = match mem::replace(&mut self.server, CopilotServer::Disabled) {
367 CopilotServer::Running(server) => Some(Box::pin(async move { server.lsp.shutdown() })),
368 _ => None,
369 };
370
371 async move {
372 if let Some(shutdown) = shutdown {
373 shutdown.await;
374 }
375 }
376 }
377
378 fn start_copilot(
379 &mut self,
380 check_edit_prediction_provider: bool,
381 awaiting_sign_in_after_start: bool,
382 cx: &mut Context<Self>,
383 ) {
384 if !matches!(self.server, CopilotServer::Disabled) {
385 return;
386 }
387 let language_settings = all_language_settings(None, cx);
388 if check_edit_prediction_provider
389 && language_settings.edit_predictions.provider != EditPredictionProvider::Copilot
390 {
391 return;
392 }
393 let server_id = self.server_id;
394 let fs = self.fs.clone();
395 let node_runtime = self.node_runtime.clone();
396 let env = self.build_env(&language_settings.edit_predictions.copilot);
397 let start_task = cx
398 .spawn(async move |this, cx| {
399 Self::start_language_server(
400 server_id,
401 fs,
402 node_runtime,
403 env,
404 this,
405 awaiting_sign_in_after_start,
406 cx,
407 )
408 .await
409 })
410 .shared();
411 self.server = CopilotServer::Starting { task: start_task };
412 cx.notify();
413 }
414
415 fn build_env(&self, copilot_settings: &CopilotSettings) -> Option<HashMap<String, String>> {
416 let proxy_url = copilot_settings.proxy.clone()?;
417 let no_verify = copilot_settings.proxy_no_verify;
418 let http_or_https_proxy = if proxy_url.starts_with("http:") {
419 Some("HTTP_PROXY")
420 } else if proxy_url.starts_with("https:") {
421 Some("HTTPS_PROXY")
422 } else {
423 log::error!(
424 "Unsupported protocol scheme for language server proxy (must be http or https)"
425 );
426 None
427 };
428
429 let mut env = HashMap::default();
430
431 if let Some(proxy_type) = http_or_https_proxy {
432 env.insert(proxy_type.to_string(), proxy_url);
433 if let Some(true) = no_verify {
434 env.insert("NODE_TLS_REJECT_UNAUTHORIZED".to_string(), "0".to_string());
435 };
436 }
437
438 if let Ok(oauth_token) = env::var(copilot_chat::COPILOT_OAUTH_ENV_VAR) {
439 env.insert(copilot_chat::COPILOT_OAUTH_ENV_VAR.to_string(), oauth_token);
440 }
441
442 if env.is_empty() { None } else { Some(env) }
443 }
444
445 #[cfg(any(test, feature = "test-support"))]
446 pub fn fake(cx: &mut gpui::TestAppContext) -> (Entity<Self>, lsp::FakeLanguageServer) {
447 use fs::FakeFs;
448 use lsp::FakeLanguageServer;
449 use node_runtime::NodeRuntime;
450
451 let (server, fake_server) = FakeLanguageServer::new(
452 LanguageServerId(0),
453 LanguageServerBinary {
454 path: "path/to/copilot".into(),
455 arguments: vec![],
456 env: None,
457 },
458 "copilot".into(),
459 Default::default(),
460 &mut cx.to_async(),
461 );
462 let node_runtime = NodeRuntime::unavailable();
463 let this = cx.new(|cx| Self {
464 server_id: LanguageServerId(0),
465 fs: FakeFs::new(cx.background_executor().clone()),
466 node_runtime,
467 server: CopilotServer::Running(RunningCopilotServer {
468 lsp: Arc::new(server),
469 sign_in_status: SignInStatus::Authorized,
470 registered_buffers: Default::default(),
471 }),
472 _subscription: cx.on_app_quit(Self::shutdown_language_server),
473 buffers: Default::default(),
474 });
475 (this, fake_server)
476 }
477
478 async fn start_language_server(
479 new_server_id: LanguageServerId,
480 fs: Arc<dyn Fs>,
481 node_runtime: NodeRuntime,
482 env: Option<HashMap<String, String>>,
483 this: WeakEntity<Self>,
484 awaiting_sign_in_after_start: bool,
485 cx: &mut AsyncApp,
486 ) {
487 let start_language_server = async {
488 let server_path = get_copilot_lsp(fs, node_runtime.clone()).await?;
489 let node_path = node_runtime.binary_path().await?;
490 let arguments: Vec<OsString> = vec![server_path.into(), "--stdio".into()];
491 let binary = LanguageServerBinary {
492 path: node_path,
493 arguments,
494 env,
495 };
496
497 let root_path = if cfg!(target_os = "windows") {
498 Path::new("C:/")
499 } else {
500 Path::new("/")
501 };
502
503 let server_name = LanguageServerName("copilot".into());
504 let server = LanguageServer::new(
505 Arc::new(Mutex::new(None)),
506 new_server_id,
507 server_name,
508 binary,
509 root_path,
510 None,
511 Default::default(),
512 cx,
513 )?;
514
515 server
516 .on_notification::<StatusNotification, _>(|_, _| { /* Silence the notification */ })
517 .detach();
518
519 let configuration = lsp::DidChangeConfigurationParams {
520 settings: Default::default(),
521 };
522
523 let editor_info = request::SetEditorInfoParams {
524 editor_info: request::EditorInfo {
525 name: "zed".into(),
526 version: env!("CARGO_PKG_VERSION").into(),
527 },
528 editor_plugin_info: request::EditorPluginInfo {
529 name: "zed-copilot".into(),
530 version: "0.0.1".into(),
531 },
532 };
533 let editor_info_json = serde_json::to_value(&editor_info)?;
534
535 let server = cx
536 .update(|cx| {
537 let mut params = server.default_initialize_params(false, cx);
538 params.initialization_options = Some(editor_info_json);
539 server.initialize(params, configuration.into(), cx)
540 })?
541 .await?;
542
543 this.update(cx, |_, cx| notify_did_change_config_to_server(&server, cx))?
544 .context("copilot: did change configuration")?;
545
546 let status = server
547 .request::<request::CheckStatus>(request::CheckStatusParams {
548 local_checks_only: false,
549 })
550 .await
551 .into_response()
552 .context("copilot: check status")?;
553
554 anyhow::Ok((server, status))
555 };
556
557 let server = start_language_server.await;
558 this.update(cx, |this, cx| {
559 cx.notify();
560 match server {
561 Ok((server, status)) => {
562 this.server = CopilotServer::Running(RunningCopilotServer {
563 lsp: server,
564 sign_in_status: SignInStatus::SignedOut {
565 awaiting_signing_in: awaiting_sign_in_after_start,
566 },
567 registered_buffers: Default::default(),
568 });
569 cx.emit(Event::CopilotLanguageServerStarted);
570 this.update_sign_in_status(status, cx);
571 }
572 Err(error) => {
573 this.server = CopilotServer::Error(error.to_string().into());
574 cx.notify()
575 }
576 }
577 })
578 .ok();
579 }
580
581 pub(crate) fn sign_in(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
582 if let CopilotServer::Running(server) = &mut self.server {
583 let task = match &server.sign_in_status {
584 SignInStatus::Authorized { .. } => Task::ready(Ok(())).shared(),
585 SignInStatus::SigningIn { task, .. } => {
586 cx.notify();
587 task.clone()
588 }
589 SignInStatus::SignedOut { .. } | SignInStatus::Unauthorized { .. } => {
590 let lsp = server.lsp.clone();
591 let task = cx
592 .spawn(async move |this, cx| {
593 let sign_in = async {
594 let sign_in = lsp
595 .request::<request::SignInInitiate>(
596 request::SignInInitiateParams {},
597 )
598 .await
599 .into_response()
600 .context("copilot sign-in")?;
601 match sign_in {
602 request::SignInInitiateResult::AlreadySignedIn { user } => {
603 Ok(request::SignInStatus::Ok { user: Some(user) })
604 }
605 request::SignInInitiateResult::PromptUserDeviceFlow(flow) => {
606 this.update(cx, |this, cx| {
607 if let CopilotServer::Running(RunningCopilotServer {
608 sign_in_status: status,
609 ..
610 }) = &mut this.server
611 && let SignInStatus::SigningIn {
612 prompt: prompt_flow,
613 ..
614 } = status
615 {
616 *prompt_flow = Some(flow.clone());
617 cx.notify();
618 }
619 })?;
620 let response = lsp
621 .request::<request::SignInConfirm>(
622 request::SignInConfirmParams {
623 user_code: flow.user_code,
624 },
625 )
626 .await
627 .into_response()
628 .context("copilot: sign in confirm")?;
629 Ok(response)
630 }
631 }
632 };
633
634 let sign_in = sign_in.await;
635 this.update(cx, |this, cx| match sign_in {
636 Ok(status) => {
637 this.update_sign_in_status(status, cx);
638 Ok(())
639 }
640 Err(error) => {
641 this.update_sign_in_status(
642 request::SignInStatus::NotSignedIn,
643 cx,
644 );
645 Err(Arc::new(error))
646 }
647 })?
648 })
649 .shared();
650 server.sign_in_status = SignInStatus::SigningIn {
651 prompt: None,
652 task: task.clone(),
653 };
654 cx.notify();
655 task
656 }
657 };
658
659 cx.background_spawn(task.map_err(|err| anyhow!("{err:?}")))
660 } else {
661 // If we're downloading, wait until download is finished
662 // If we're in a stuck state, display to the user
663 Task::ready(Err(anyhow!("copilot hasn't started yet")))
664 }
665 }
666
667 pub(crate) fn sign_out(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
668 self.update_sign_in_status(request::SignInStatus::NotSignedIn, cx);
669 match &self.server {
670 CopilotServer::Running(RunningCopilotServer { lsp: server, .. }) => {
671 let server = server.clone();
672 cx.background_spawn(async move {
673 server
674 .request::<request::SignOut>(request::SignOutParams {})
675 .await
676 .into_response()
677 .context("copilot: sign in confirm")?;
678 anyhow::Ok(())
679 })
680 }
681 CopilotServer::Disabled => cx.background_spawn(async {
682 clear_copilot_config_dir().await;
683 anyhow::Ok(())
684 }),
685 _ => Task::ready(Err(anyhow!("copilot hasn't started yet"))),
686 }
687 }
688
689 pub(crate) fn reinstall(&mut self, cx: &mut Context<Self>) -> Shared<Task<()>> {
690 let language_settings = all_language_settings(None, cx);
691 let env = self.build_env(&language_settings.edit_predictions.copilot);
692 let start_task = cx
693 .spawn({
694 let fs = self.fs.clone();
695 let node_runtime = self.node_runtime.clone();
696 let server_id = self.server_id;
697 async move |this, cx| {
698 clear_copilot_dir().await;
699 Self::start_language_server(server_id, fs, node_runtime, env, this, false, cx)
700 .await
701 }
702 })
703 .shared();
704
705 self.server = CopilotServer::Starting {
706 task: start_task.clone(),
707 };
708
709 cx.notify();
710
711 start_task
712 }
713
714 pub fn language_server(&self) -> Option<&Arc<LanguageServer>> {
715 if let CopilotServer::Running(server) = &self.server {
716 Some(&server.lsp)
717 } else {
718 None
719 }
720 }
721
722 pub fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) {
723 let weak_buffer = buffer.downgrade();
724 self.buffers.insert(weak_buffer.clone());
725
726 if let CopilotServer::Running(RunningCopilotServer {
727 lsp: server,
728 sign_in_status: status,
729 registered_buffers,
730 ..
731 }) = &mut self.server
732 {
733 if !matches!(status, SignInStatus::Authorized { .. }) {
734 return;
735 }
736
737 let entry = registered_buffers.entry(buffer.entity_id());
738 if let Entry::Vacant(e) = entry {
739 let Ok(uri) = uri_for_buffer(buffer, cx) else {
740 return;
741 };
742 let language_id = id_for_language(buffer.read(cx).language());
743 let snapshot = buffer.read(cx).snapshot();
744 server
745 .notify::<lsp::notification::DidOpenTextDocument>(
746 &lsp::DidOpenTextDocumentParams {
747 text_document: lsp::TextDocumentItem {
748 uri: uri.clone(),
749 language_id: language_id.clone(),
750 version: 0,
751 text: snapshot.text(),
752 },
753 },
754 )
755 .ok();
756
757 e.insert(RegisteredBuffer {
758 uri,
759 language_id,
760 snapshot,
761 snapshot_version: 0,
762 pending_buffer_change: Task::ready(Some(())),
763 _subscriptions: [
764 cx.subscribe(buffer, |this, buffer, event, cx| {
765 this.handle_buffer_event(buffer, event, cx).log_err();
766 }),
767 cx.observe_release(buffer, move |this, _buffer, _cx| {
768 this.buffers.remove(&weak_buffer);
769 this.unregister_buffer(&weak_buffer);
770 }),
771 ],
772 });
773 }
774 }
775 }
776
777 fn handle_buffer_event(
778 &mut self,
779 buffer: Entity<Buffer>,
780 event: &language::BufferEvent,
781 cx: &mut Context<Self>,
782 ) -> Result<()> {
783 if let Ok(server) = self.server.as_running()
784 && let Some(registered_buffer) = server.registered_buffers.get_mut(&buffer.entity_id())
785 {
786 match event {
787 language::BufferEvent::Edited => {
788 drop(registered_buffer.report_changes(&buffer, cx));
789 }
790 language::BufferEvent::Saved => {
791 server
792 .lsp
793 .notify::<lsp::notification::DidSaveTextDocument>(
794 &lsp::DidSaveTextDocumentParams {
795 text_document: lsp::TextDocumentIdentifier::new(
796 registered_buffer.uri.clone(),
797 ),
798 text: None,
799 },
800 )?;
801 }
802 language::BufferEvent::FileHandleChanged
803 | language::BufferEvent::LanguageChanged => {
804 let new_language_id = id_for_language(buffer.read(cx).language());
805 let Ok(new_uri) = uri_for_buffer(&buffer, cx) else {
806 return Ok(());
807 };
808 if new_uri != registered_buffer.uri
809 || new_language_id != registered_buffer.language_id
810 {
811 let old_uri = mem::replace(&mut registered_buffer.uri, new_uri);
812 registered_buffer.language_id = new_language_id;
813 server
814 .lsp
815 .notify::<lsp::notification::DidCloseTextDocument>(
816 &lsp::DidCloseTextDocumentParams {
817 text_document: lsp::TextDocumentIdentifier::new(old_uri),
818 },
819 )?;
820 server
821 .lsp
822 .notify::<lsp::notification::DidOpenTextDocument>(
823 &lsp::DidOpenTextDocumentParams {
824 text_document: lsp::TextDocumentItem::new(
825 registered_buffer.uri.clone(),
826 registered_buffer.language_id.clone(),
827 registered_buffer.snapshot_version,
828 registered_buffer.snapshot.text(),
829 ),
830 },
831 )?;
832 }
833 }
834 _ => {}
835 }
836 }
837
838 Ok(())
839 }
840
841 fn unregister_buffer(&mut self, buffer: &WeakEntity<Buffer>) {
842 if let Ok(server) = self.server.as_running()
843 && let Some(buffer) = server.registered_buffers.remove(&buffer.entity_id())
844 {
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.iter());
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::Url, ()> {
1115 if let Some(file) = buffer.read(cx).file().and_then(|file| file.as_local()) {
1116 lsp::Url::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 get_copilot_lsp(fs: Arc<dyn Fs>, node_runtime: NodeRuntime) -> anyhow::Result<PathBuf> {
1168 const PACKAGE_NAME: &str = "@github/copilot-language-server";
1169 const SERVER_PATH: &str =
1170 "node_modules/@github/copilot-language-server/dist/language-server.js";
1171
1172 let latest_version = node_runtime
1173 .npm_package_latest_version(PACKAGE_NAME)
1174 .await?;
1175 let server_path = paths::copilot_dir().join(SERVER_PATH);
1176
1177 fs.create_dir(paths::copilot_dir()).await?;
1178
1179 let should_install = node_runtime
1180 .should_install_npm_package(
1181 PACKAGE_NAME,
1182 &server_path,
1183 paths::copilot_dir(),
1184 VersionStrategy::Latest(&latest_version),
1185 )
1186 .await;
1187 if should_install {
1188 node_runtime
1189 .npm_install_packages(paths::copilot_dir(), &[(PACKAGE_NAME, &latest_version)])
1190 .await?;
1191 }
1192
1193 Ok(server_path)
1194}
1195
1196#[cfg(test)]
1197mod tests {
1198 use super::*;
1199 use gpui::TestAppContext;
1200 use util::path;
1201
1202 #[gpui::test(iterations = 10)]
1203 async fn test_buffer_management(cx: &mut TestAppContext) {
1204 let (copilot, mut lsp) = Copilot::fake(cx);
1205
1206 let buffer_1 = cx.new(|cx| Buffer::local("Hello", cx));
1207 let buffer_1_uri: lsp::Url = format!("buffer://{}", buffer_1.entity_id().as_u64())
1208 .parse()
1209 .unwrap();
1210 copilot.update(cx, |copilot, cx| copilot.register_buffer(&buffer_1, cx));
1211 assert_eq!(
1212 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1213 .await,
1214 lsp::DidOpenTextDocumentParams {
1215 text_document: lsp::TextDocumentItem::new(
1216 buffer_1_uri.clone(),
1217 "plaintext".into(),
1218 0,
1219 "Hello".into()
1220 ),
1221 }
1222 );
1223
1224 let buffer_2 = cx.new(|cx| Buffer::local("Goodbye", cx));
1225 let buffer_2_uri: lsp::Url = format!("buffer://{}", buffer_2.entity_id().as_u64())
1226 .parse()
1227 .unwrap();
1228 copilot.update(cx, |copilot, cx| copilot.register_buffer(&buffer_2, cx));
1229 assert_eq!(
1230 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1231 .await,
1232 lsp::DidOpenTextDocumentParams {
1233 text_document: lsp::TextDocumentItem::new(
1234 buffer_2_uri.clone(),
1235 "plaintext".into(),
1236 0,
1237 "Goodbye".into()
1238 ),
1239 }
1240 );
1241
1242 buffer_1.update(cx, |buffer, cx| buffer.edit([(5..5, " world")], None, cx));
1243 assert_eq!(
1244 lsp.receive_notification::<lsp::notification::DidChangeTextDocument>()
1245 .await,
1246 lsp::DidChangeTextDocumentParams {
1247 text_document: lsp::VersionedTextDocumentIdentifier::new(buffer_1_uri.clone(), 1),
1248 content_changes: vec![lsp::TextDocumentContentChangeEvent {
1249 range: Some(lsp::Range::new(
1250 lsp::Position::new(0, 5),
1251 lsp::Position::new(0, 5)
1252 )),
1253 range_length: None,
1254 text: " world".into(),
1255 }],
1256 }
1257 );
1258
1259 // Ensure updates to the file are reflected in the LSP.
1260 buffer_1.update(cx, |buffer, cx| {
1261 buffer.file_updated(
1262 Arc::new(File {
1263 abs_path: path!("/root/child/buffer-1").into(),
1264 path: Path::new("child/buffer-1").into(),
1265 }),
1266 cx,
1267 )
1268 });
1269 assert_eq!(
1270 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1271 .await,
1272 lsp::DidCloseTextDocumentParams {
1273 text_document: lsp::TextDocumentIdentifier::new(buffer_1_uri),
1274 }
1275 );
1276 let buffer_1_uri = lsp::Url::from_file_path(path!("/root/child/buffer-1")).unwrap();
1277 assert_eq!(
1278 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1279 .await,
1280 lsp::DidOpenTextDocumentParams {
1281 text_document: lsp::TextDocumentItem::new(
1282 buffer_1_uri.clone(),
1283 "plaintext".into(),
1284 1,
1285 "Hello world".into()
1286 ),
1287 }
1288 );
1289
1290 // Ensure all previously-registered buffers are closed when signing out.
1291 lsp.set_request_handler::<request::SignOut, _, _>(|_, _| async {
1292 Ok(request::SignOutResult {})
1293 });
1294 copilot
1295 .update(cx, |copilot, cx| copilot.sign_out(cx))
1296 .await
1297 .unwrap();
1298 assert_eq!(
1299 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1300 .await,
1301 lsp::DidCloseTextDocumentParams {
1302 text_document: lsp::TextDocumentIdentifier::new(buffer_1_uri.clone()),
1303 }
1304 );
1305 assert_eq!(
1306 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1307 .await,
1308 lsp::DidCloseTextDocumentParams {
1309 text_document: lsp::TextDocumentIdentifier::new(buffer_2_uri.clone()),
1310 }
1311 );
1312
1313 // Ensure all previously-registered buffers are re-opened when signing in.
1314 lsp.set_request_handler::<request::SignInInitiate, _, _>(|_, _| async {
1315 Ok(request::SignInInitiateResult::AlreadySignedIn {
1316 user: "user-1".into(),
1317 })
1318 });
1319 copilot
1320 .update(cx, |copilot, cx| copilot.sign_in(cx))
1321 .await
1322 .unwrap();
1323
1324 assert_eq!(
1325 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1326 .await,
1327 lsp::DidOpenTextDocumentParams {
1328 text_document: lsp::TextDocumentItem::new(
1329 buffer_1_uri.clone(),
1330 "plaintext".into(),
1331 0,
1332 "Hello world".into()
1333 ),
1334 }
1335 );
1336 assert_eq!(
1337 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1338 .await,
1339 lsp::DidOpenTextDocumentParams {
1340 text_document: lsp::TextDocumentItem::new(
1341 buffer_2_uri.clone(),
1342 "plaintext".into(),
1343 0,
1344 "Goodbye".into()
1345 ),
1346 }
1347 );
1348 // Dropping a buffer causes it to be closed on the LSP side as well.
1349 cx.update(|_| drop(buffer_2));
1350 assert_eq!(
1351 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1352 .await,
1353 lsp::DidCloseTextDocumentParams {
1354 text_document: lsp::TextDocumentIdentifier::new(buffer_2_uri),
1355 }
1356 );
1357 }
1358
1359 struct File {
1360 abs_path: PathBuf,
1361 path: Arc<Path>,
1362 }
1363
1364 impl language::File for File {
1365 fn as_local(&self) -> Option<&dyn language::LocalFile> {
1366 Some(self)
1367 }
1368
1369 fn disk_state(&self) -> language::DiskState {
1370 language::DiskState::Present {
1371 mtime: ::fs::MTime::from_seconds_and_nanos(100, 42),
1372 }
1373 }
1374
1375 fn path(&self) -> &Arc<Path> {
1376 &self.path
1377 }
1378
1379 fn full_path(&self, _: &App) -> PathBuf {
1380 unimplemented!()
1381 }
1382
1383 fn file_name<'a>(&'a self, _: &'a App) -> &'a std::ffi::OsStr {
1384 unimplemented!()
1385 }
1386
1387 fn to_proto(&self, _: &App) -> rpc::proto::File {
1388 unimplemented!()
1389 }
1390
1391 fn worktree_id(&self, _: &App) -> settings::WorktreeId {
1392 settings::WorktreeId::from_usize(0)
1393 }
1394
1395 fn is_private(&self) -> bool {
1396 false
1397 }
1398 }
1399
1400 impl language::LocalFile for File {
1401 fn abs_path(&self, _: &App) -> PathBuf {
1402 self.abs_path.clone()
1403 }
1404
1405 fn load(&self, _: &App) -> Task<Result<String>> {
1406 unimplemented!()
1407 }
1408
1409 fn load_bytes(&self, _cx: &App) -> Task<Result<Vec<u8>>> {
1410 unimplemented!()
1411 }
1412 }
1413}
1414
1415#[cfg(test)]
1416#[ctor::ctor]
1417fn init_logger() {
1418 zlog::init_test();
1419}