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 {
612 if let SignInStatus::SigningIn {
613 prompt: prompt_flow,
614 ..
615 } = status
616 {
617 *prompt_flow = Some(flow.clone());
618 cx.notify();
619 }
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 if 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 }
804 language::BufferEvent::FileHandleChanged
805 | language::BufferEvent::LanguageChanged => {
806 let new_language_id = id_for_language(buffer.read(cx).language());
807 let Ok(new_uri) = uri_for_buffer(&buffer, cx) else {
808 return Ok(());
809 };
810 if new_uri != registered_buffer.uri
811 || new_language_id != registered_buffer.language_id
812 {
813 let old_uri = mem::replace(&mut registered_buffer.uri, new_uri);
814 registered_buffer.language_id = new_language_id;
815 server
816 .lsp
817 .notify::<lsp::notification::DidCloseTextDocument>(
818 &lsp::DidCloseTextDocumentParams {
819 text_document: lsp::TextDocumentIdentifier::new(old_uri),
820 },
821 )?;
822 server
823 .lsp
824 .notify::<lsp::notification::DidOpenTextDocument>(
825 &lsp::DidOpenTextDocumentParams {
826 text_document: lsp::TextDocumentItem::new(
827 registered_buffer.uri.clone(),
828 registered_buffer.language_id.clone(),
829 registered_buffer.snapshot_version,
830 registered_buffer.snapshot.text(),
831 ),
832 },
833 )?;
834 }
835 }
836 _ => {}
837 }
838 }
839 }
840
841 Ok(())
842 }
843
844 fn unregister_buffer(&mut self, buffer: &WeakEntity<Buffer>) {
845 if let Ok(server) = self.server.as_running() {
846 if let Some(buffer) = server.registered_buffers.remove(&buffer.entity_id()) {
847 server
848 .lsp
849 .notify::<lsp::notification::DidCloseTextDocument>(
850 &lsp::DidCloseTextDocumentParams {
851 text_document: lsp::TextDocumentIdentifier::new(buffer.uri),
852 },
853 )
854 .ok();
855 }
856 }
857 }
858
859 pub fn completions<T>(
860 &mut self,
861 buffer: &Entity<Buffer>,
862 position: T,
863 cx: &mut Context<Self>,
864 ) -> Task<Result<Vec<Completion>>>
865 where
866 T: ToPointUtf16,
867 {
868 self.request_completions::<request::GetCompletions, _>(buffer, position, cx)
869 }
870
871 pub fn completions_cycling<T>(
872 &mut self,
873 buffer: &Entity<Buffer>,
874 position: T,
875 cx: &mut Context<Self>,
876 ) -> Task<Result<Vec<Completion>>>
877 where
878 T: ToPointUtf16,
879 {
880 self.request_completions::<request::GetCompletionsCycling, _>(buffer, position, cx)
881 }
882
883 pub fn accept_completion(
884 &mut self,
885 completion: &Completion,
886 cx: &mut Context<Self>,
887 ) -> Task<Result<()>> {
888 let server = match self.server.as_authenticated() {
889 Ok(server) => server,
890 Err(error) => return Task::ready(Err(error)),
891 };
892 let request =
893 server
894 .lsp
895 .request::<request::NotifyAccepted>(request::NotifyAcceptedParams {
896 uuid: completion.uuid.clone(),
897 });
898 cx.background_spawn(async move {
899 request
900 .await
901 .into_response()
902 .context("copilot: notify accepted")?;
903 Ok(())
904 })
905 }
906
907 pub fn discard_completions(
908 &mut self,
909 completions: &[Completion],
910 cx: &mut Context<Self>,
911 ) -> Task<Result<()>> {
912 let server = match self.server.as_authenticated() {
913 Ok(server) => server,
914 Err(_) => return Task::ready(Ok(())),
915 };
916 let request =
917 server
918 .lsp
919 .request::<request::NotifyRejected>(request::NotifyRejectedParams {
920 uuids: completions
921 .iter()
922 .map(|completion| completion.uuid.clone())
923 .collect(),
924 });
925 cx.background_spawn(async move {
926 request
927 .await
928 .into_response()
929 .context("copilot: notify rejected")?;
930 Ok(())
931 })
932 }
933
934 fn request_completions<R, T>(
935 &mut self,
936 buffer: &Entity<Buffer>,
937 position: T,
938 cx: &mut Context<Self>,
939 ) -> Task<Result<Vec<Completion>>>
940 where
941 R: 'static
942 + lsp::request::Request<
943 Params = request::GetCompletionsParams,
944 Result = request::GetCompletionsResult,
945 >,
946 T: ToPointUtf16,
947 {
948 self.register_buffer(buffer, cx);
949
950 let server = match self.server.as_authenticated() {
951 Ok(server) => server,
952 Err(error) => return Task::ready(Err(error)),
953 };
954 let lsp = server.lsp.clone();
955 let registered_buffer = server
956 .registered_buffers
957 .get_mut(&buffer.entity_id())
958 .unwrap();
959 let snapshot = registered_buffer.report_changes(buffer, cx);
960 let buffer = buffer.read(cx);
961 let uri = registered_buffer.uri.clone();
962 let position = position.to_point_utf16(buffer);
963 let settings = language_settings(
964 buffer.language_at(position).map(|l| l.name()),
965 buffer.file(),
966 cx,
967 );
968 let tab_size = settings.tab_size;
969 let hard_tabs = settings.hard_tabs;
970 let relative_path = buffer
971 .file()
972 .map(|file| file.path().to_path_buf())
973 .unwrap_or_default();
974
975 cx.background_spawn(async move {
976 let (version, snapshot) = snapshot.await?;
977 let result = lsp
978 .request::<R>(request::GetCompletionsParams {
979 doc: request::GetCompletionsDocument {
980 uri,
981 tab_size: tab_size.into(),
982 indent_size: 1,
983 insert_spaces: !hard_tabs,
984 relative_path: relative_path.to_string_lossy().into(),
985 position: point_to_lsp(position),
986 version: version.try_into().unwrap(),
987 },
988 })
989 .await
990 .into_response()
991 .context("copilot: get completions")?;
992 let completions = result
993 .completions
994 .into_iter()
995 .map(|completion| {
996 let start = snapshot
997 .clip_point_utf16(point_from_lsp(completion.range.start), Bias::Left);
998 let end =
999 snapshot.clip_point_utf16(point_from_lsp(completion.range.end), Bias::Left);
1000 Completion {
1001 uuid: completion.uuid,
1002 range: snapshot.anchor_before(start)..snapshot.anchor_after(end),
1003 text: completion.text,
1004 }
1005 })
1006 .collect();
1007 anyhow::Ok(completions)
1008 })
1009 }
1010
1011 pub fn status(&self) -> Status {
1012 match &self.server {
1013 CopilotServer::Starting { task } => Status::Starting { task: task.clone() },
1014 CopilotServer::Disabled => Status::Disabled,
1015 CopilotServer::Error(error) => Status::Error(error.clone()),
1016 CopilotServer::Running(RunningCopilotServer { sign_in_status, .. }) => {
1017 match sign_in_status {
1018 SignInStatus::Authorized { .. } => Status::Authorized,
1019 SignInStatus::Unauthorized { .. } => Status::Unauthorized,
1020 SignInStatus::SigningIn { prompt, .. } => Status::SigningIn {
1021 prompt: prompt.clone(),
1022 },
1023 SignInStatus::SignedOut {
1024 awaiting_signing_in,
1025 } => Status::SignedOut {
1026 awaiting_signing_in: *awaiting_signing_in,
1027 },
1028 }
1029 }
1030 }
1031 }
1032
1033 fn update_sign_in_status(&mut self, lsp_status: request::SignInStatus, cx: &mut Context<Self>) {
1034 self.buffers.retain(|buffer| buffer.is_upgradable());
1035
1036 if let Ok(server) = self.server.as_running() {
1037 match lsp_status {
1038 request::SignInStatus::Ok { user: Some(_) }
1039 | request::SignInStatus::MaybeOk { .. }
1040 | request::SignInStatus::AlreadySignedIn { .. } => {
1041 server.sign_in_status = SignInStatus::Authorized;
1042 cx.emit(Event::CopilotAuthSignedIn);
1043 for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1044 if let Some(buffer) = buffer.upgrade() {
1045 self.register_buffer(&buffer, cx);
1046 }
1047 }
1048 }
1049 request::SignInStatus::NotAuthorized { .. } => {
1050 server.sign_in_status = SignInStatus::Unauthorized;
1051 for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1052 self.unregister_buffer(&buffer);
1053 }
1054 }
1055 request::SignInStatus::Ok { user: None } | request::SignInStatus::NotSignedIn => {
1056 if !matches!(server.sign_in_status, SignInStatus::SignedOut { .. }) {
1057 server.sign_in_status = SignInStatus::SignedOut {
1058 awaiting_signing_in: false,
1059 };
1060 }
1061 cx.emit(Event::CopilotAuthSignedOut);
1062 for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1063 self.unregister_buffer(&buffer);
1064 }
1065 }
1066 }
1067
1068 cx.notify();
1069 }
1070 }
1071
1072 fn update_action_visibilities(&self, cx: &mut App) {
1073 let signed_in_actions = [
1074 TypeId::of::<Suggest>(),
1075 TypeId::of::<NextSuggestion>(),
1076 TypeId::of::<PreviousSuggestion>(),
1077 TypeId::of::<Reinstall>(),
1078 ];
1079 let auth_actions = [TypeId::of::<SignOut>()];
1080 let no_auth_actions = [TypeId::of::<SignIn>()];
1081 let status = self.status();
1082
1083 let is_ai_disabled = DisableAiSettings::get_global(cx).disable_ai;
1084 let filter = CommandPaletteFilter::global_mut(cx);
1085
1086 if is_ai_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 } else {
1091 match status {
1092 Status::Disabled => {
1093 filter.hide_action_types(&signed_in_actions);
1094 filter.hide_action_types(&auth_actions);
1095 filter.hide_action_types(&no_auth_actions);
1096 }
1097 Status::Authorized => {
1098 filter.hide_action_types(&no_auth_actions);
1099 filter.show_action_types(signed_in_actions.iter().chain(&auth_actions));
1100 }
1101 _ => {
1102 filter.hide_action_types(&signed_in_actions);
1103 filter.hide_action_types(&auth_actions);
1104 filter.show_action_types(no_auth_actions.iter());
1105 }
1106 }
1107 }
1108 }
1109}
1110
1111fn id_for_language(language: Option<&Arc<Language>>) -> String {
1112 language
1113 .map(|language| language.lsp_id())
1114 .unwrap_or_else(|| "plaintext".to_string())
1115}
1116
1117fn uri_for_buffer(buffer: &Entity<Buffer>, cx: &App) -> Result<lsp::Url, ()> {
1118 if let Some(file) = buffer.read(cx).file().and_then(|file| file.as_local()) {
1119 lsp::Url::from_file_path(file.abs_path(cx))
1120 } else {
1121 format!("buffer://{}", buffer.entity_id())
1122 .parse()
1123 .map_err(|_| ())
1124 }
1125}
1126
1127fn notify_did_change_config_to_server(
1128 server: &Arc<LanguageServer>,
1129 cx: &mut Context<Copilot>,
1130) -> std::result::Result<(), anyhow::Error> {
1131 let copilot_settings = all_language_settings(None, cx)
1132 .edit_predictions
1133 .copilot
1134 .clone();
1135
1136 if let Some(copilot_chat) = copilot_chat::CopilotChat::global(cx) {
1137 copilot_chat.update(cx, |chat, cx| {
1138 chat.set_configuration(
1139 copilot_chat::CopilotChatConfiguration {
1140 enterprise_uri: copilot_settings.enterprise_uri.clone(),
1141 },
1142 cx,
1143 );
1144 });
1145 }
1146
1147 let settings = json!({
1148 "http": {
1149 "proxy": copilot_settings.proxy,
1150 "proxyStrictSSL": !copilot_settings.proxy_no_verify.unwrap_or(false)
1151 },
1152 "github-enterprise": {
1153 "uri": copilot_settings.enterprise_uri
1154 }
1155 });
1156
1157 server.notify::<lsp::notification::DidChangeConfiguration>(&lsp::DidChangeConfigurationParams {
1158 settings,
1159 })
1160}
1161
1162async fn clear_copilot_dir() {
1163 remove_matching(paths::copilot_dir(), |_| true).await
1164}
1165
1166async fn clear_copilot_config_dir() {
1167 remove_matching(copilot_chat::copilot_chat_config_dir(), |_| true).await
1168}
1169
1170async fn get_copilot_lsp(fs: Arc<dyn Fs>, node_runtime: NodeRuntime) -> anyhow::Result<PathBuf> {
1171 const PACKAGE_NAME: &str = "@github/copilot-language-server";
1172 const SERVER_PATH: &str =
1173 "node_modules/@github/copilot-language-server/dist/language-server.js";
1174
1175 let latest_version = node_runtime
1176 .npm_package_latest_version(PACKAGE_NAME)
1177 .await?;
1178 let server_path = paths::copilot_dir().join(SERVER_PATH);
1179
1180 fs.create_dir(paths::copilot_dir()).await?;
1181
1182 let should_install = node_runtime
1183 .should_install_npm_package(
1184 PACKAGE_NAME,
1185 &server_path,
1186 paths::copilot_dir(),
1187 VersionStrategy::Latest(&latest_version),
1188 )
1189 .await;
1190 if should_install {
1191 node_runtime
1192 .npm_install_packages(paths::copilot_dir(), &[(PACKAGE_NAME, &latest_version)])
1193 .await?;
1194 }
1195
1196 Ok(server_path)
1197}
1198
1199#[cfg(test)]
1200mod tests {
1201 use super::*;
1202 use gpui::TestAppContext;
1203 use util::path;
1204
1205 #[gpui::test(iterations = 10)]
1206 async fn test_buffer_management(cx: &mut TestAppContext) {
1207 let (copilot, mut lsp) = Copilot::fake(cx);
1208
1209 let buffer_1 = cx.new(|cx| Buffer::local("Hello", cx));
1210 let buffer_1_uri: lsp::Url = format!("buffer://{}", buffer_1.entity_id().as_u64())
1211 .parse()
1212 .unwrap();
1213 copilot.update(cx, |copilot, cx| copilot.register_buffer(&buffer_1, cx));
1214 assert_eq!(
1215 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1216 .await,
1217 lsp::DidOpenTextDocumentParams {
1218 text_document: lsp::TextDocumentItem::new(
1219 buffer_1_uri.clone(),
1220 "plaintext".into(),
1221 0,
1222 "Hello".into()
1223 ),
1224 }
1225 );
1226
1227 let buffer_2 = cx.new(|cx| Buffer::local("Goodbye", cx));
1228 let buffer_2_uri: lsp::Url = format!("buffer://{}", buffer_2.entity_id().as_u64())
1229 .parse()
1230 .unwrap();
1231 copilot.update(cx, |copilot, cx| copilot.register_buffer(&buffer_2, cx));
1232 assert_eq!(
1233 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1234 .await,
1235 lsp::DidOpenTextDocumentParams {
1236 text_document: lsp::TextDocumentItem::new(
1237 buffer_2_uri.clone(),
1238 "plaintext".into(),
1239 0,
1240 "Goodbye".into()
1241 ),
1242 }
1243 );
1244
1245 buffer_1.update(cx, |buffer, cx| buffer.edit([(5..5, " world")], None, cx));
1246 assert_eq!(
1247 lsp.receive_notification::<lsp::notification::DidChangeTextDocument>()
1248 .await,
1249 lsp::DidChangeTextDocumentParams {
1250 text_document: lsp::VersionedTextDocumentIdentifier::new(buffer_1_uri.clone(), 1),
1251 content_changes: vec![lsp::TextDocumentContentChangeEvent {
1252 range: Some(lsp::Range::new(
1253 lsp::Position::new(0, 5),
1254 lsp::Position::new(0, 5)
1255 )),
1256 range_length: None,
1257 text: " world".into(),
1258 }],
1259 }
1260 );
1261
1262 // Ensure updates to the file are reflected in the LSP.
1263 buffer_1.update(cx, |buffer, cx| {
1264 buffer.file_updated(
1265 Arc::new(File {
1266 abs_path: path!("/root/child/buffer-1").into(),
1267 path: Path::new("child/buffer-1").into(),
1268 }),
1269 cx,
1270 )
1271 });
1272 assert_eq!(
1273 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1274 .await,
1275 lsp::DidCloseTextDocumentParams {
1276 text_document: lsp::TextDocumentIdentifier::new(buffer_1_uri),
1277 }
1278 );
1279 let buffer_1_uri = lsp::Url::from_file_path(path!("/root/child/buffer-1")).unwrap();
1280 assert_eq!(
1281 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1282 .await,
1283 lsp::DidOpenTextDocumentParams {
1284 text_document: lsp::TextDocumentItem::new(
1285 buffer_1_uri.clone(),
1286 "plaintext".into(),
1287 1,
1288 "Hello world".into()
1289 ),
1290 }
1291 );
1292
1293 // Ensure all previously-registered buffers are closed when signing out.
1294 lsp.set_request_handler::<request::SignOut, _, _>(|_, _| async {
1295 Ok(request::SignOutResult {})
1296 });
1297 copilot
1298 .update(cx, |copilot, cx| copilot.sign_out(cx))
1299 .await
1300 .unwrap();
1301 assert_eq!(
1302 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1303 .await,
1304 lsp::DidCloseTextDocumentParams {
1305 text_document: lsp::TextDocumentIdentifier::new(buffer_1_uri.clone()),
1306 }
1307 );
1308 assert_eq!(
1309 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1310 .await,
1311 lsp::DidCloseTextDocumentParams {
1312 text_document: lsp::TextDocumentIdentifier::new(buffer_2_uri.clone()),
1313 }
1314 );
1315
1316 // Ensure all previously-registered buffers are re-opened when signing in.
1317 lsp.set_request_handler::<request::SignInInitiate, _, _>(|_, _| async {
1318 Ok(request::SignInInitiateResult::AlreadySignedIn {
1319 user: "user-1".into(),
1320 })
1321 });
1322 copilot
1323 .update(cx, |copilot, cx| copilot.sign_in(cx))
1324 .await
1325 .unwrap();
1326
1327 assert_eq!(
1328 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1329 .await,
1330 lsp::DidOpenTextDocumentParams {
1331 text_document: lsp::TextDocumentItem::new(
1332 buffer_1_uri.clone(),
1333 "plaintext".into(),
1334 0,
1335 "Hello world".into()
1336 ),
1337 }
1338 );
1339 assert_eq!(
1340 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1341 .await,
1342 lsp::DidOpenTextDocumentParams {
1343 text_document: lsp::TextDocumentItem::new(
1344 buffer_2_uri.clone(),
1345 "plaintext".into(),
1346 0,
1347 "Goodbye".into()
1348 ),
1349 }
1350 );
1351 // Dropping a buffer causes it to be closed on the LSP side as well.
1352 cx.update(|_| drop(buffer_2));
1353 assert_eq!(
1354 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1355 .await,
1356 lsp::DidCloseTextDocumentParams {
1357 text_document: lsp::TextDocumentIdentifier::new(buffer_2_uri),
1358 }
1359 );
1360 }
1361
1362 struct File {
1363 abs_path: PathBuf,
1364 path: Arc<Path>,
1365 }
1366
1367 impl language::File for File {
1368 fn as_local(&self) -> Option<&dyn language::LocalFile> {
1369 Some(self)
1370 }
1371
1372 fn disk_state(&self) -> language::DiskState {
1373 language::DiskState::Present {
1374 mtime: ::fs::MTime::from_seconds_and_nanos(100, 42),
1375 }
1376 }
1377
1378 fn path(&self) -> &Arc<Path> {
1379 &self.path
1380 }
1381
1382 fn full_path(&self, _: &App) -> PathBuf {
1383 unimplemented!()
1384 }
1385
1386 fn file_name<'a>(&'a self, _: &'a App) -> &'a std::ffi::OsStr {
1387 unimplemented!()
1388 }
1389
1390 fn to_proto(&self, _: &App) -> rpc::proto::File {
1391 unimplemented!()
1392 }
1393
1394 fn worktree_id(&self, _: &App) -> settings::WorktreeId {
1395 settings::WorktreeId::from_usize(0)
1396 }
1397
1398 fn is_private(&self) -> bool {
1399 false
1400 }
1401 }
1402
1403 impl language::LocalFile for File {
1404 fn abs_path(&self, _: &App) -> PathBuf {
1405 self.abs_path.clone()
1406 }
1407
1408 fn load(&self, _: &App) -> Task<Result<String>> {
1409 unimplemented!()
1410 }
1411
1412 fn load_bytes(&self, _cx: &App) -> Task<Result<Vec<u8>>> {
1413 unimplemented!()
1414 }
1415 }
1416}
1417
1418#[cfg(test)]
1419#[ctor::ctor]
1420fn init_logger() {
1421 zlog::init_test();
1422}