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;
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 util::{ResultExt, fs::remove_matching};
43use workspace::Workspace;
44
45pub use crate::copilot_completion_provider::CopilotCompletionProvider;
46pub use crate::sign_in::{CopilotCodeVerification, initiate_sign_in, reinstall_and_sign_in};
47
48actions!(
49 copilot,
50 [
51 /// Requests a code completion suggestion from Copilot.
52 Suggest,
53 /// Cycles to the next Copilot suggestion.
54 NextSuggestion,
55 /// Cycles to the previous Copilot suggestion.
56 PreviousSuggestion,
57 /// Reinstalls the Copilot language server.
58 Reinstall,
59 /// Signs in to GitHub Copilot.
60 SignIn,
61 /// Signs out of GitHub Copilot.
62 SignOut
63 ]
64);
65
66pub fn init(
67 new_server_id: LanguageServerId,
68 fs: Arc<dyn Fs>,
69 http: Arc<dyn HttpClient>,
70 node_runtime: NodeRuntime,
71 cx: &mut App,
72) {
73 let language_settings = all_language_settings(None, cx);
74 let configuration = copilot_chat::CopilotChatConfiguration {
75 enterprise_uri: language_settings
76 .edit_predictions
77 .copilot
78 .enterprise_uri
79 .clone(),
80 };
81 copilot_chat::init(fs.clone(), http.clone(), configuration, cx);
82
83 let copilot = cx.new({
84 let node_runtime = node_runtime.clone();
85 move |cx| Copilot::start(new_server_id, fs, node_runtime, cx)
86 });
87 Copilot::set_global(copilot.clone(), cx);
88 cx.observe(&copilot, |copilot, cx| {
89 copilot.update(cx, |copilot, cx| copilot.update_action_visibilities(cx));
90 })
91 .detach();
92 cx.observe_global::<SettingsStore>(|cx| {
93 if let Some(copilot) = Copilot::global(cx) {
94 copilot.update(cx, |copilot, cx| copilot.update_action_visibilities(cx));
95 }
96 })
97 .detach();
98
99 cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
100 workspace.register_action(|workspace, _: &SignIn, window, cx| {
101 if let Some(copilot) = Copilot::global(cx) {
102 let is_reinstall = false;
103 initiate_sign_in_within_workspace(workspace, copilot, is_reinstall, window, cx);
104 }
105 });
106 workspace.register_action(|workspace, _: &Reinstall, window, cx| {
107 if let Some(copilot) = Copilot::global(cx) {
108 reinstall_and_sign_in_within_workspace(workspace, copilot, window, cx);
109 }
110 });
111 workspace.register_action(|workspace, _: &SignOut, _window, cx| {
112 if let Some(copilot) = Copilot::global(cx) {
113 sign_out_within_workspace(workspace, copilot, cx);
114 }
115 });
116 })
117 .detach();
118}
119
120enum CopilotServer {
121 Disabled,
122 Starting { task: Shared<Task<()>> },
123 Error(Arc<str>),
124 Running(RunningCopilotServer),
125}
126
127impl CopilotServer {
128 fn as_authenticated(&mut self) -> Result<&mut RunningCopilotServer> {
129 let server = self.as_running()?;
130 anyhow::ensure!(
131 matches!(server.sign_in_status, SignInStatus::Authorized { .. }),
132 "must sign in before using copilot"
133 );
134 Ok(server)
135 }
136
137 fn as_running(&mut self) -> Result<&mut RunningCopilotServer> {
138 match self {
139 CopilotServer::Starting { .. } => anyhow::bail!("copilot is still starting"),
140 CopilotServer::Disabled => anyhow::bail!("copilot is disabled"),
141 CopilotServer::Error(error) => {
142 anyhow::bail!("copilot was not started because of an error: {error}")
143 }
144 CopilotServer::Running(server) => Ok(server),
145 }
146 }
147}
148
149struct RunningCopilotServer {
150 lsp: Arc<LanguageServer>,
151 sign_in_status: SignInStatus,
152 registered_buffers: HashMap<EntityId, RegisteredBuffer>,
153}
154
155#[derive(Clone, Debug)]
156enum SignInStatus {
157 Authorized,
158 Unauthorized,
159 SigningIn {
160 prompt: Option<request::PromptUserDeviceFlow>,
161 task: Shared<Task<Result<(), Arc<anyhow::Error>>>>,
162 },
163 SignedOut {
164 awaiting_signing_in: bool,
165 },
166}
167
168#[derive(Debug, Clone)]
169pub enum Status {
170 Starting {
171 task: Shared<Task<()>>,
172 },
173 Error(Arc<str>),
174 Disabled,
175 SignedOut {
176 awaiting_signing_in: bool,
177 },
178 SigningIn {
179 prompt: Option<request::PromptUserDeviceFlow>,
180 },
181 Unauthorized,
182 Authorized,
183}
184
185impl Status {
186 pub fn is_authorized(&self) -> bool {
187 matches!(self, Status::Authorized)
188 }
189
190 pub fn is_configured(&self) -> bool {
191 matches!(
192 self,
193 Status::Starting { .. }
194 | Status::Error(_)
195 | Status::SigningIn { .. }
196 | Status::Authorized
197 )
198 }
199}
200
201struct RegisteredBuffer {
202 uri: lsp::Url,
203 language_id: String,
204 snapshot: BufferSnapshot,
205 snapshot_version: i32,
206 _subscriptions: [gpui::Subscription; 2],
207 pending_buffer_change: Task<Option<()>>,
208}
209
210impl RegisteredBuffer {
211 fn report_changes(
212 &mut self,
213 buffer: &Entity<Buffer>,
214 cx: &mut Context<Copilot>,
215 ) -> oneshot::Receiver<(i32, BufferSnapshot)> {
216 let (done_tx, done_rx) = oneshot::channel();
217
218 if buffer.read(cx).version() == self.snapshot.version {
219 let _ = done_tx.send((self.snapshot_version, self.snapshot.clone()));
220 } else {
221 let buffer = buffer.downgrade();
222 let id = buffer.entity_id();
223 let prev_pending_change =
224 mem::replace(&mut self.pending_buffer_change, Task::ready(None));
225 self.pending_buffer_change = cx.spawn(async move |copilot, cx| {
226 prev_pending_change.await;
227
228 let old_version = copilot
229 .update(cx, |copilot, _| {
230 let server = copilot.server.as_authenticated().log_err()?;
231 let buffer = server.registered_buffers.get_mut(&id)?;
232 Some(buffer.snapshot.version.clone())
233 })
234 .ok()??;
235 let new_snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot()).ok()?;
236
237 let content_changes = cx
238 .background_spawn({
239 let new_snapshot = new_snapshot.clone();
240 async move {
241 new_snapshot
242 .edits_since::<(PointUtf16, usize)>(&old_version)
243 .map(|edit| {
244 let edit_start = edit.new.start.0;
245 let edit_end = edit_start + (edit.old.end.0 - edit.old.start.0);
246 let new_text = new_snapshot
247 .text_for_range(edit.new.start.1..edit.new.end.1)
248 .collect();
249 lsp::TextDocumentContentChangeEvent {
250 range: Some(lsp::Range::new(
251 point_to_lsp(edit_start),
252 point_to_lsp(edit_end),
253 )),
254 range_length: None,
255 text: new_text,
256 }
257 })
258 .collect::<Vec<_>>()
259 }
260 })
261 .await;
262
263 copilot
264 .update(cx, |copilot, _| {
265 let server = copilot.server.as_authenticated().log_err()?;
266 let buffer = server.registered_buffers.get_mut(&id)?;
267 if !content_changes.is_empty() {
268 buffer.snapshot_version += 1;
269 buffer.snapshot = new_snapshot;
270 server
271 .lsp
272 .notify::<lsp::notification::DidChangeTextDocument>(
273 &lsp::DidChangeTextDocumentParams {
274 text_document: lsp::VersionedTextDocumentIdentifier::new(
275 buffer.uri.clone(),
276 buffer.snapshot_version,
277 ),
278 content_changes,
279 },
280 )
281 .ok();
282 }
283 let _ = done_tx.send((buffer.snapshot_version, buffer.snapshot.clone()));
284 Some(())
285 })
286 .ok()?;
287
288 Some(())
289 });
290 }
291
292 done_rx
293 }
294}
295
296#[derive(Debug)]
297pub struct Completion {
298 pub uuid: String,
299 pub range: Range<Anchor>,
300 pub text: String,
301}
302
303pub struct Copilot {
304 fs: Arc<dyn Fs>,
305 node_runtime: NodeRuntime,
306 server: CopilotServer,
307 buffers: HashSet<WeakEntity<Buffer>>,
308 server_id: LanguageServerId,
309 _subscription: gpui::Subscription,
310}
311
312pub enum Event {
313 CopilotLanguageServerStarted,
314 CopilotAuthSignedIn,
315 CopilotAuthSignedOut,
316}
317
318impl EventEmitter<Event> for Copilot {}
319
320struct GlobalCopilot(Entity<Copilot>);
321
322impl Global for GlobalCopilot {}
323
324impl Copilot {
325 pub fn global(cx: &App) -> Option<Entity<Self>> {
326 cx.try_global::<GlobalCopilot>()
327 .map(|model| model.0.clone())
328 }
329
330 pub fn set_global(copilot: Entity<Self>, cx: &mut App) {
331 cx.set_global(GlobalCopilot(copilot));
332 }
333
334 fn start(
335 new_server_id: LanguageServerId,
336 fs: Arc<dyn Fs>,
337 node_runtime: NodeRuntime,
338 cx: &mut Context<Self>,
339 ) -> Self {
340 let mut this = Self {
341 server_id: new_server_id,
342 fs,
343 node_runtime,
344 server: CopilotServer::Disabled,
345 buffers: Default::default(),
346 _subscription: cx.on_app_quit(Self::shutdown_language_server),
347 };
348 this.start_copilot(true, false, cx);
349 cx.observe_global::<SettingsStore>(move |this, cx| {
350 this.start_copilot(true, false, cx);
351 this.send_configuration_update(cx);
352 })
353 .detach();
354 this
355 }
356
357 fn shutdown_language_server(
358 &mut self,
359 _cx: &mut Context<Self>,
360 ) -> impl Future<Output = ()> + use<> {
361 let shutdown = match mem::replace(&mut self.server, CopilotServer::Disabled) {
362 CopilotServer::Running(server) => Some(Box::pin(async move { server.lsp.shutdown() })),
363 _ => None,
364 };
365
366 async move {
367 if let Some(shutdown) = shutdown {
368 shutdown.await;
369 }
370 }
371 }
372
373 fn start_copilot(
374 &mut self,
375 check_edit_prediction_provider: bool,
376 awaiting_sign_in_after_start: bool,
377 cx: &mut Context<Self>,
378 ) {
379 if !matches!(self.server, CopilotServer::Disabled) {
380 return;
381 }
382 let language_settings = all_language_settings(None, cx);
383 if check_edit_prediction_provider
384 && language_settings.edit_predictions.provider != EditPredictionProvider::Copilot
385 {
386 return;
387 }
388 let server_id = self.server_id;
389 let fs = self.fs.clone();
390 let node_runtime = self.node_runtime.clone();
391 let env = self.build_env(&language_settings.edit_predictions.copilot);
392 let start_task = cx
393 .spawn(async move |this, cx| {
394 Self::start_language_server(
395 server_id,
396 fs,
397 node_runtime,
398 env,
399 this,
400 awaiting_sign_in_after_start,
401 cx,
402 )
403 .await
404 })
405 .shared();
406 self.server = CopilotServer::Starting { task: start_task };
407 cx.notify();
408 }
409
410 fn build_env(&self, copilot_settings: &CopilotSettings) -> Option<HashMap<String, String>> {
411 let proxy_url = copilot_settings.proxy.clone()?;
412 let no_verify = copilot_settings.proxy_no_verify;
413 let http_or_https_proxy = if proxy_url.starts_with("http:") {
414 Some("HTTP_PROXY")
415 } else if proxy_url.starts_with("https:") {
416 Some("HTTPS_PROXY")
417 } else {
418 log::error!(
419 "Unsupported protocol scheme for language server proxy (must be http or https)"
420 );
421 None
422 };
423
424 let mut env = HashMap::default();
425
426 if let Some(proxy_type) = http_or_https_proxy {
427 env.insert(proxy_type.to_string(), proxy_url);
428 if let Some(true) = no_verify {
429 env.insert("NODE_TLS_REJECT_UNAUTHORIZED".to_string(), "0".to_string());
430 };
431 }
432
433 if let Ok(oauth_token) = env::var(copilot_chat::COPILOT_OAUTH_ENV_VAR) {
434 env.insert(copilot_chat::COPILOT_OAUTH_ENV_VAR.to_string(), oauth_token);
435 }
436
437 if env.is_empty() { None } else { Some(env) }
438 }
439
440 fn send_configuration_update(&mut self, cx: &mut Context<Self>) {
441 let copilot_settings = all_language_settings(None, cx)
442 .edit_predictions
443 .copilot
444 .clone();
445
446 let settings = json!({
447 "http": {
448 "proxy": copilot_settings.proxy,
449 "proxyStrictSSL": !copilot_settings.proxy_no_verify.unwrap_or(false)
450 },
451 "github-enterprise": {
452 "uri": copilot_settings.enterprise_uri
453 }
454 });
455
456 if let Some(copilot_chat) = copilot_chat::CopilotChat::global(cx) {
457 copilot_chat.update(cx, |chat, cx| {
458 chat.set_configuration(
459 copilot_chat::CopilotChatConfiguration {
460 enterprise_uri: copilot_settings.enterprise_uri.clone(),
461 },
462 cx,
463 );
464 });
465 }
466
467 if let Ok(server) = self.server.as_running() {
468 server
469 .lsp
470 .notify::<lsp::notification::DidChangeConfiguration>(
471 &lsp::DidChangeConfigurationParams { settings },
472 )
473 .log_err();
474 }
475 }
476
477 #[cfg(any(test, feature = "test-support"))]
478 pub fn fake(cx: &mut gpui::TestAppContext) -> (Entity<Self>, lsp::FakeLanguageServer) {
479 use fs::FakeFs;
480 use lsp::FakeLanguageServer;
481 use node_runtime::NodeRuntime;
482
483 let (server, fake_server) = FakeLanguageServer::new(
484 LanguageServerId(0),
485 LanguageServerBinary {
486 path: "path/to/copilot".into(),
487 arguments: vec![],
488 env: None,
489 },
490 "copilot".into(),
491 Default::default(),
492 &mut cx.to_async(),
493 );
494 let node_runtime = NodeRuntime::unavailable();
495 let this = cx.new(|cx| Self {
496 server_id: LanguageServerId(0),
497 fs: FakeFs::new(cx.background_executor().clone()),
498 node_runtime,
499 server: CopilotServer::Running(RunningCopilotServer {
500 lsp: Arc::new(server),
501 sign_in_status: SignInStatus::Authorized,
502 registered_buffers: Default::default(),
503 }),
504 _subscription: cx.on_app_quit(Self::shutdown_language_server),
505 buffers: Default::default(),
506 });
507 (this, fake_server)
508 }
509
510 async fn start_language_server(
511 new_server_id: LanguageServerId,
512 fs: Arc<dyn Fs>,
513 node_runtime: NodeRuntime,
514 env: Option<HashMap<String, String>>,
515 this: WeakEntity<Self>,
516 awaiting_sign_in_after_start: bool,
517 cx: &mut AsyncApp,
518 ) {
519 let start_language_server = async {
520 let server_path = get_copilot_lsp(fs, node_runtime.clone()).await?;
521 let node_path = node_runtime.binary_path().await?;
522 let arguments: Vec<OsString> = vec![server_path.into(), "--stdio".into()];
523 let binary = LanguageServerBinary {
524 path: node_path,
525 arguments,
526 env,
527 };
528
529 let root_path = if cfg!(target_os = "windows") {
530 Path::new("C:/")
531 } else {
532 Path::new("/")
533 };
534
535 let server_name = LanguageServerName("copilot".into());
536 let server = LanguageServer::new(
537 Arc::new(Mutex::new(None)),
538 new_server_id,
539 server_name,
540 binary,
541 root_path,
542 None,
543 Default::default(),
544 cx,
545 )?;
546
547 server
548 .on_notification::<StatusNotification, _>(|_, _| { /* Silence the notification */ })
549 .detach();
550
551 let configuration = lsp::DidChangeConfigurationParams {
552 settings: Default::default(),
553 };
554
555 let editor_info = request::SetEditorInfoParams {
556 editor_info: request::EditorInfo {
557 name: "zed".into(),
558 version: env!("CARGO_PKG_VERSION").into(),
559 },
560 editor_plugin_info: request::EditorPluginInfo {
561 name: "zed-copilot".into(),
562 version: "0.0.1".into(),
563 },
564 };
565 let editor_info_json = serde_json::to_value(&editor_info)?;
566
567 let server = cx
568 .update(|cx| {
569 let mut params = server.default_initialize_params(false, cx);
570 params.initialization_options = Some(editor_info_json);
571 server.initialize(params, configuration.into(), cx)
572 })?
573 .await?;
574
575 let status = server
576 .request::<request::CheckStatus>(request::CheckStatusParams {
577 local_checks_only: false,
578 })
579 .await
580 .into_response()
581 .context("copilot: check status")?;
582
583 anyhow::Ok((server, status))
584 };
585
586 let server = start_language_server.await;
587 this.update(cx, |this, cx| {
588 cx.notify();
589 match server {
590 Ok((server, status)) => {
591 this.server = CopilotServer::Running(RunningCopilotServer {
592 lsp: server,
593 sign_in_status: SignInStatus::SignedOut {
594 awaiting_signing_in: awaiting_sign_in_after_start,
595 },
596 registered_buffers: Default::default(),
597 });
598 cx.emit(Event::CopilotLanguageServerStarted);
599 this.update_sign_in_status(status, cx);
600 // Send configuration now that the LSP is fully started
601 this.send_configuration_update(cx);
602 }
603 Err(error) => {
604 this.server = CopilotServer::Error(error.to_string().into());
605 cx.notify()
606 }
607 }
608 })
609 .ok();
610 }
611
612 pub(crate) fn sign_in(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
613 if let CopilotServer::Running(server) = &mut self.server {
614 let task = match &server.sign_in_status {
615 SignInStatus::Authorized { .. } => Task::ready(Ok(())).shared(),
616 SignInStatus::SigningIn { task, .. } => {
617 cx.notify();
618 task.clone()
619 }
620 SignInStatus::SignedOut { .. } | SignInStatus::Unauthorized { .. } => {
621 let lsp = server.lsp.clone();
622 let task = cx
623 .spawn(async move |this, cx| {
624 let sign_in = async {
625 let sign_in = lsp
626 .request::<request::SignInInitiate>(
627 request::SignInInitiateParams {},
628 )
629 .await
630 .into_response()
631 .context("copilot sign-in")?;
632 match sign_in {
633 request::SignInInitiateResult::AlreadySignedIn { user } => {
634 Ok(request::SignInStatus::Ok { user: Some(user) })
635 }
636 request::SignInInitiateResult::PromptUserDeviceFlow(flow) => {
637 this.update(cx, |this, cx| {
638 if let CopilotServer::Running(RunningCopilotServer {
639 sign_in_status: status,
640 ..
641 }) = &mut this.server
642 {
643 if let SignInStatus::SigningIn {
644 prompt: prompt_flow,
645 ..
646 } = status
647 {
648 *prompt_flow = Some(flow.clone());
649 cx.notify();
650 }
651 }
652 })?;
653 let response = lsp
654 .request::<request::SignInConfirm>(
655 request::SignInConfirmParams {
656 user_code: flow.user_code,
657 },
658 )
659 .await
660 .into_response()
661 .context("copilot: sign in confirm")?;
662 Ok(response)
663 }
664 }
665 };
666
667 let sign_in = sign_in.await;
668 this.update(cx, |this, cx| match sign_in {
669 Ok(status) => {
670 this.update_sign_in_status(status, cx);
671 Ok(())
672 }
673 Err(error) => {
674 this.update_sign_in_status(
675 request::SignInStatus::NotSignedIn,
676 cx,
677 );
678 Err(Arc::new(error))
679 }
680 })?
681 })
682 .shared();
683 server.sign_in_status = SignInStatus::SigningIn {
684 prompt: None,
685 task: task.clone(),
686 };
687 cx.notify();
688 task
689 }
690 };
691
692 cx.background_spawn(task.map_err(|err| anyhow!("{err:?}")))
693 } else {
694 // If we're downloading, wait until download is finished
695 // If we're in a stuck state, display to the user
696 Task::ready(Err(anyhow!("copilot hasn't started yet")))
697 }
698 }
699
700 pub(crate) fn sign_out(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
701 self.update_sign_in_status(request::SignInStatus::NotSignedIn, cx);
702 match &self.server {
703 CopilotServer::Running(RunningCopilotServer { lsp: server, .. }) => {
704 let server = server.clone();
705 cx.background_spawn(async move {
706 server
707 .request::<request::SignOut>(request::SignOutParams {})
708 .await
709 .into_response()
710 .context("copilot: sign in confirm")?;
711 anyhow::Ok(())
712 })
713 }
714 CopilotServer::Disabled => cx.background_spawn(async {
715 clear_copilot_config_dir().await;
716 anyhow::Ok(())
717 }),
718 _ => Task::ready(Err(anyhow!("copilot hasn't started yet"))),
719 }
720 }
721
722 pub(crate) fn reinstall(&mut self, cx: &mut Context<Self>) -> Shared<Task<()>> {
723 let language_settings = all_language_settings(None, cx);
724 let env = self.build_env(&language_settings.edit_predictions.copilot);
725 let start_task = cx
726 .spawn({
727 let fs = self.fs.clone();
728 let node_runtime = self.node_runtime.clone();
729 let server_id = self.server_id;
730 async move |this, cx| {
731 clear_copilot_dir().await;
732 Self::start_language_server(server_id, fs, node_runtime, env, this, false, cx)
733 .await
734 }
735 })
736 .shared();
737
738 self.server = CopilotServer::Starting {
739 task: start_task.clone(),
740 };
741
742 cx.notify();
743
744 start_task
745 }
746
747 pub fn language_server(&self) -> Option<&Arc<LanguageServer>> {
748 if let CopilotServer::Running(server) = &self.server {
749 Some(&server.lsp)
750 } else {
751 None
752 }
753 }
754
755 pub fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) {
756 let weak_buffer = buffer.downgrade();
757 self.buffers.insert(weak_buffer.clone());
758
759 if let CopilotServer::Running(RunningCopilotServer {
760 lsp: server,
761 sign_in_status: status,
762 registered_buffers,
763 ..
764 }) = &mut self.server
765 {
766 if !matches!(status, SignInStatus::Authorized { .. }) {
767 return;
768 }
769
770 let entry = registered_buffers.entry(buffer.entity_id());
771 if let Entry::Vacant(e) = entry {
772 let Ok(uri) = uri_for_buffer(buffer, cx) else {
773 return;
774 };
775 let language_id = id_for_language(buffer.read(cx).language());
776 let snapshot = buffer.read(cx).snapshot();
777 server
778 .notify::<lsp::notification::DidOpenTextDocument>(
779 &lsp::DidOpenTextDocumentParams {
780 text_document: lsp::TextDocumentItem {
781 uri: uri.clone(),
782 language_id: language_id.clone(),
783 version: 0,
784 text: snapshot.text(),
785 },
786 },
787 )
788 .ok();
789
790 e.insert(RegisteredBuffer {
791 uri,
792 language_id,
793 snapshot,
794 snapshot_version: 0,
795 pending_buffer_change: Task::ready(Some(())),
796 _subscriptions: [
797 cx.subscribe(buffer, |this, buffer, event, cx| {
798 this.handle_buffer_event(buffer, event, cx).log_err();
799 }),
800 cx.observe_release(buffer, move |this, _buffer, _cx| {
801 this.buffers.remove(&weak_buffer);
802 this.unregister_buffer(&weak_buffer);
803 }),
804 ],
805 });
806 }
807 }
808 }
809
810 fn handle_buffer_event(
811 &mut self,
812 buffer: Entity<Buffer>,
813 event: &language::BufferEvent,
814 cx: &mut Context<Self>,
815 ) -> Result<()> {
816 if let Ok(server) = self.server.as_running() {
817 if let Some(registered_buffer) = server.registered_buffers.get_mut(&buffer.entity_id())
818 {
819 match event {
820 language::BufferEvent::Edited => {
821 drop(registered_buffer.report_changes(&buffer, cx));
822 }
823 language::BufferEvent::Saved => {
824 server
825 .lsp
826 .notify::<lsp::notification::DidSaveTextDocument>(
827 &lsp::DidSaveTextDocumentParams {
828 text_document: lsp::TextDocumentIdentifier::new(
829 registered_buffer.uri.clone(),
830 ),
831 text: None,
832 },
833 )?;
834 }
835 language::BufferEvent::FileHandleChanged
836 | language::BufferEvent::LanguageChanged => {
837 let new_language_id = id_for_language(buffer.read(cx).language());
838 let Ok(new_uri) = uri_for_buffer(&buffer, cx) else {
839 return Ok(());
840 };
841 if new_uri != registered_buffer.uri
842 || new_language_id != registered_buffer.language_id
843 {
844 let old_uri = mem::replace(&mut registered_buffer.uri, new_uri);
845 registered_buffer.language_id = new_language_id;
846 server
847 .lsp
848 .notify::<lsp::notification::DidCloseTextDocument>(
849 &lsp::DidCloseTextDocumentParams {
850 text_document: lsp::TextDocumentIdentifier::new(old_uri),
851 },
852 )?;
853 server
854 .lsp
855 .notify::<lsp::notification::DidOpenTextDocument>(
856 &lsp::DidOpenTextDocumentParams {
857 text_document: lsp::TextDocumentItem::new(
858 registered_buffer.uri.clone(),
859 registered_buffer.language_id.clone(),
860 registered_buffer.snapshot_version,
861 registered_buffer.snapshot.text(),
862 ),
863 },
864 )?;
865 }
866 }
867 _ => {}
868 }
869 }
870 }
871
872 Ok(())
873 }
874
875 fn unregister_buffer(&mut self, buffer: &WeakEntity<Buffer>) {
876 if let Ok(server) = self.server.as_running() {
877 if let Some(buffer) = server.registered_buffers.remove(&buffer.entity_id()) {
878 server
879 .lsp
880 .notify::<lsp::notification::DidCloseTextDocument>(
881 &lsp::DidCloseTextDocumentParams {
882 text_document: lsp::TextDocumentIdentifier::new(buffer.uri),
883 },
884 )
885 .ok();
886 }
887 }
888 }
889
890 pub fn completions<T>(
891 &mut self,
892 buffer: &Entity<Buffer>,
893 position: T,
894 cx: &mut Context<Self>,
895 ) -> Task<Result<Vec<Completion>>>
896 where
897 T: ToPointUtf16,
898 {
899 self.request_completions::<request::GetCompletions, _>(buffer, position, cx)
900 }
901
902 pub fn completions_cycling<T>(
903 &mut self,
904 buffer: &Entity<Buffer>,
905 position: T,
906 cx: &mut Context<Self>,
907 ) -> Task<Result<Vec<Completion>>>
908 where
909 T: ToPointUtf16,
910 {
911 self.request_completions::<request::GetCompletionsCycling, _>(buffer, position, cx)
912 }
913
914 pub fn accept_completion(
915 &mut self,
916 completion: &Completion,
917 cx: &mut Context<Self>,
918 ) -> Task<Result<()>> {
919 let server = match self.server.as_authenticated() {
920 Ok(server) => server,
921 Err(error) => return Task::ready(Err(error)),
922 };
923 let request =
924 server
925 .lsp
926 .request::<request::NotifyAccepted>(request::NotifyAcceptedParams {
927 uuid: completion.uuid.clone(),
928 });
929 cx.background_spawn(async move {
930 request
931 .await
932 .into_response()
933 .context("copilot: notify accepted")?;
934 Ok(())
935 })
936 }
937
938 pub fn discard_completions(
939 &mut self,
940 completions: &[Completion],
941 cx: &mut Context<Self>,
942 ) -> Task<Result<()>> {
943 let server = match self.server.as_authenticated() {
944 Ok(server) => server,
945 Err(_) => return Task::ready(Ok(())),
946 };
947 let request =
948 server
949 .lsp
950 .request::<request::NotifyRejected>(request::NotifyRejectedParams {
951 uuids: completions
952 .iter()
953 .map(|completion| completion.uuid.clone())
954 .collect(),
955 });
956 cx.background_spawn(async move {
957 request
958 .await
959 .into_response()
960 .context("copilot: notify rejected")?;
961 Ok(())
962 })
963 }
964
965 fn request_completions<R, T>(
966 &mut self,
967 buffer: &Entity<Buffer>,
968 position: T,
969 cx: &mut Context<Self>,
970 ) -> Task<Result<Vec<Completion>>>
971 where
972 R: 'static
973 + lsp::request::Request<
974 Params = request::GetCompletionsParams,
975 Result = request::GetCompletionsResult,
976 >,
977 T: ToPointUtf16,
978 {
979 self.register_buffer(buffer, cx);
980
981 let server = match self.server.as_authenticated() {
982 Ok(server) => server,
983 Err(error) => return Task::ready(Err(error)),
984 };
985 let lsp = server.lsp.clone();
986 let registered_buffer = server
987 .registered_buffers
988 .get_mut(&buffer.entity_id())
989 .unwrap();
990 let snapshot = registered_buffer.report_changes(buffer, cx);
991 let buffer = buffer.read(cx);
992 let uri = registered_buffer.uri.clone();
993 let position = position.to_point_utf16(buffer);
994 let settings = language_settings(
995 buffer.language_at(position).map(|l| l.name()),
996 buffer.file(),
997 cx,
998 );
999 let tab_size = settings.tab_size;
1000 let hard_tabs = settings.hard_tabs;
1001 let relative_path = buffer
1002 .file()
1003 .map(|file| file.path().to_path_buf())
1004 .unwrap_or_default();
1005
1006 cx.background_spawn(async move {
1007 let (version, snapshot) = snapshot.await?;
1008 let result = lsp
1009 .request::<R>(request::GetCompletionsParams {
1010 doc: request::GetCompletionsDocument {
1011 uri,
1012 tab_size: tab_size.into(),
1013 indent_size: 1,
1014 insert_spaces: !hard_tabs,
1015 relative_path: relative_path.to_string_lossy().into(),
1016 position: point_to_lsp(position),
1017 version: version.try_into().unwrap(),
1018 },
1019 })
1020 .await
1021 .into_response()
1022 .context("copilot: get completions")?;
1023 let completions = result
1024 .completions
1025 .into_iter()
1026 .map(|completion| {
1027 let start = snapshot
1028 .clip_point_utf16(point_from_lsp(completion.range.start), Bias::Left);
1029 let end =
1030 snapshot.clip_point_utf16(point_from_lsp(completion.range.end), Bias::Left);
1031 Completion {
1032 uuid: completion.uuid,
1033 range: snapshot.anchor_before(start)..snapshot.anchor_after(end),
1034 text: completion.text,
1035 }
1036 })
1037 .collect();
1038 anyhow::Ok(completions)
1039 })
1040 }
1041
1042 pub fn status(&self) -> Status {
1043 match &self.server {
1044 CopilotServer::Starting { task } => Status::Starting { task: task.clone() },
1045 CopilotServer::Disabled => Status::Disabled,
1046 CopilotServer::Error(error) => Status::Error(error.clone()),
1047 CopilotServer::Running(RunningCopilotServer { sign_in_status, .. }) => {
1048 match sign_in_status {
1049 SignInStatus::Authorized { .. } => Status::Authorized,
1050 SignInStatus::Unauthorized { .. } => Status::Unauthorized,
1051 SignInStatus::SigningIn { prompt, .. } => Status::SigningIn {
1052 prompt: prompt.clone(),
1053 },
1054 SignInStatus::SignedOut {
1055 awaiting_signing_in,
1056 } => Status::SignedOut {
1057 awaiting_signing_in: *awaiting_signing_in,
1058 },
1059 }
1060 }
1061 }
1062 }
1063
1064 fn update_sign_in_status(&mut self, lsp_status: request::SignInStatus, cx: &mut Context<Self>) {
1065 self.buffers.retain(|buffer| buffer.is_upgradable());
1066
1067 if let Ok(server) = self.server.as_running() {
1068 match lsp_status {
1069 request::SignInStatus::Ok { user: Some(_) }
1070 | request::SignInStatus::MaybeOk { .. }
1071 | request::SignInStatus::AlreadySignedIn { .. } => {
1072 server.sign_in_status = SignInStatus::Authorized;
1073 cx.emit(Event::CopilotAuthSignedIn);
1074 for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1075 if let Some(buffer) = buffer.upgrade() {
1076 self.register_buffer(&buffer, cx);
1077 }
1078 }
1079 }
1080 request::SignInStatus::NotAuthorized { .. } => {
1081 server.sign_in_status = SignInStatus::Unauthorized;
1082 for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1083 self.unregister_buffer(&buffer);
1084 }
1085 }
1086 request::SignInStatus::Ok { user: None } | request::SignInStatus::NotSignedIn => {
1087 if !matches!(server.sign_in_status, SignInStatus::SignedOut { .. }) {
1088 server.sign_in_status = SignInStatus::SignedOut {
1089 awaiting_signing_in: false,
1090 };
1091 }
1092 cx.emit(Event::CopilotAuthSignedOut);
1093 for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1094 self.unregister_buffer(&buffer);
1095 }
1096 }
1097 }
1098
1099 cx.notify();
1100 }
1101 }
1102
1103 fn update_action_visibilities(&self, cx: &mut App) {
1104 let signed_in_actions = [
1105 TypeId::of::<Suggest>(),
1106 TypeId::of::<NextSuggestion>(),
1107 TypeId::of::<PreviousSuggestion>(),
1108 TypeId::of::<Reinstall>(),
1109 ];
1110 let auth_actions = [TypeId::of::<SignOut>()];
1111 let no_auth_actions = [TypeId::of::<SignIn>()];
1112 let status = self.status();
1113
1114 let is_ai_disabled = DisableAiSettings::get_global(cx).disable_ai;
1115 let filter = CommandPaletteFilter::global_mut(cx);
1116
1117 if is_ai_disabled {
1118 filter.hide_action_types(&signed_in_actions);
1119 filter.hide_action_types(&auth_actions);
1120 filter.hide_action_types(&no_auth_actions);
1121 } else {
1122 match status {
1123 Status::Disabled => {
1124 filter.hide_action_types(&signed_in_actions);
1125 filter.hide_action_types(&auth_actions);
1126 filter.hide_action_types(&no_auth_actions);
1127 }
1128 Status::Authorized => {
1129 filter.hide_action_types(&no_auth_actions);
1130 filter.show_action_types(signed_in_actions.iter().chain(&auth_actions));
1131 }
1132 _ => {
1133 filter.hide_action_types(&signed_in_actions);
1134 filter.hide_action_types(&auth_actions);
1135 filter.show_action_types(no_auth_actions.iter());
1136 }
1137 }
1138 }
1139 }
1140}
1141
1142fn id_for_language(language: Option<&Arc<Language>>) -> String {
1143 language
1144 .map(|language| language.lsp_id())
1145 .unwrap_or_else(|| "plaintext".to_string())
1146}
1147
1148fn uri_for_buffer(buffer: &Entity<Buffer>, cx: &App) -> Result<lsp::Url, ()> {
1149 if let Some(file) = buffer.read(cx).file().and_then(|file| file.as_local()) {
1150 lsp::Url::from_file_path(file.abs_path(cx))
1151 } else {
1152 format!("buffer://{}", buffer.entity_id())
1153 .parse()
1154 .map_err(|_| ())
1155 }
1156}
1157
1158async fn clear_copilot_dir() {
1159 remove_matching(paths::copilot_dir(), |_| true).await
1160}
1161
1162async fn clear_copilot_config_dir() {
1163 remove_matching(copilot_chat::copilot_chat_config_dir(), |_| true).await
1164}
1165
1166async fn get_copilot_lsp(fs: Arc<dyn Fs>, node_runtime: NodeRuntime) -> anyhow::Result<PathBuf> {
1167 const PACKAGE_NAME: &str = "@github/copilot-language-server";
1168 const SERVER_PATH: &str =
1169 "node_modules/@github/copilot-language-server/dist/language-server.js";
1170
1171 let latest_version = node_runtime
1172 .npm_package_latest_version(PACKAGE_NAME)
1173 .await?;
1174 let server_path = paths::copilot_dir().join(SERVER_PATH);
1175
1176 fs.create_dir(paths::copilot_dir()).await?;
1177
1178 let should_install = node_runtime
1179 .should_install_npm_package(
1180 PACKAGE_NAME,
1181 &server_path,
1182 paths::copilot_dir(),
1183 &latest_version,
1184 )
1185 .await;
1186 if should_install {
1187 node_runtime
1188 .npm_install_packages(paths::copilot_dir(), &[(PACKAGE_NAME, &latest_version)])
1189 .await?;
1190 }
1191
1192 Ok(server_path)
1193}
1194
1195#[cfg(test)]
1196mod tests {
1197 use super::*;
1198 use gpui::TestAppContext;
1199 use util::path;
1200
1201 #[gpui::test(iterations = 10)]
1202 async fn test_buffer_management(cx: &mut TestAppContext) {
1203 let (copilot, mut lsp) = Copilot::fake(cx);
1204
1205 let buffer_1 = cx.new(|cx| Buffer::local("Hello", cx));
1206 let buffer_1_uri: lsp::Url = format!("buffer://{}", buffer_1.entity_id().as_u64())
1207 .parse()
1208 .unwrap();
1209 copilot.update(cx, |copilot, cx| copilot.register_buffer(&buffer_1, cx));
1210 assert_eq!(
1211 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1212 .await,
1213 lsp::DidOpenTextDocumentParams {
1214 text_document: lsp::TextDocumentItem::new(
1215 buffer_1_uri.clone(),
1216 "plaintext".into(),
1217 0,
1218 "Hello".into()
1219 ),
1220 }
1221 );
1222
1223 let buffer_2 = cx.new(|cx| Buffer::local("Goodbye", cx));
1224 let buffer_2_uri: lsp::Url = format!("buffer://{}", buffer_2.entity_id().as_u64())
1225 .parse()
1226 .unwrap();
1227 copilot.update(cx, |copilot, cx| copilot.register_buffer(&buffer_2, cx));
1228 assert_eq!(
1229 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1230 .await,
1231 lsp::DidOpenTextDocumentParams {
1232 text_document: lsp::TextDocumentItem::new(
1233 buffer_2_uri.clone(),
1234 "plaintext".into(),
1235 0,
1236 "Goodbye".into()
1237 ),
1238 }
1239 );
1240
1241 buffer_1.update(cx, |buffer, cx| buffer.edit([(5..5, " world")], None, cx));
1242 assert_eq!(
1243 lsp.receive_notification::<lsp::notification::DidChangeTextDocument>()
1244 .await,
1245 lsp::DidChangeTextDocumentParams {
1246 text_document: lsp::VersionedTextDocumentIdentifier::new(buffer_1_uri.clone(), 1),
1247 content_changes: vec![lsp::TextDocumentContentChangeEvent {
1248 range: Some(lsp::Range::new(
1249 lsp::Position::new(0, 5),
1250 lsp::Position::new(0, 5)
1251 )),
1252 range_length: None,
1253 text: " world".into(),
1254 }],
1255 }
1256 );
1257
1258 // Ensure updates to the file are reflected in the LSP.
1259 buffer_1.update(cx, |buffer, cx| {
1260 buffer.file_updated(
1261 Arc::new(File {
1262 abs_path: path!("/root/child/buffer-1").into(),
1263 path: Path::new("child/buffer-1").into(),
1264 }),
1265 cx,
1266 )
1267 });
1268 assert_eq!(
1269 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1270 .await,
1271 lsp::DidCloseTextDocumentParams {
1272 text_document: lsp::TextDocumentIdentifier::new(buffer_1_uri),
1273 }
1274 );
1275 let buffer_1_uri = lsp::Url::from_file_path(path!("/root/child/buffer-1")).unwrap();
1276 assert_eq!(
1277 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1278 .await,
1279 lsp::DidOpenTextDocumentParams {
1280 text_document: lsp::TextDocumentItem::new(
1281 buffer_1_uri.clone(),
1282 "plaintext".into(),
1283 1,
1284 "Hello world".into()
1285 ),
1286 }
1287 );
1288
1289 // Ensure all previously-registered buffers are closed when signing out.
1290 lsp.set_request_handler::<request::SignOut, _, _>(|_, _| async {
1291 Ok(request::SignOutResult {})
1292 });
1293 copilot
1294 .update(cx, |copilot, cx| copilot.sign_out(cx))
1295 .await
1296 .unwrap();
1297 assert_eq!(
1298 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1299 .await,
1300 lsp::DidCloseTextDocumentParams {
1301 text_document: lsp::TextDocumentIdentifier::new(buffer_1_uri.clone()),
1302 }
1303 );
1304 assert_eq!(
1305 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1306 .await,
1307 lsp::DidCloseTextDocumentParams {
1308 text_document: lsp::TextDocumentIdentifier::new(buffer_2_uri.clone()),
1309 }
1310 );
1311
1312 // Ensure all previously-registered buffers are re-opened when signing in.
1313 lsp.set_request_handler::<request::SignInInitiate, _, _>(|_, _| async {
1314 Ok(request::SignInInitiateResult::AlreadySignedIn {
1315 user: "user-1".into(),
1316 })
1317 });
1318 copilot
1319 .update(cx, |copilot, cx| copilot.sign_in(cx))
1320 .await
1321 .unwrap();
1322
1323 assert_eq!(
1324 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1325 .await,
1326 lsp::DidOpenTextDocumentParams {
1327 text_document: lsp::TextDocumentItem::new(
1328 buffer_1_uri.clone(),
1329 "plaintext".into(),
1330 0,
1331 "Hello world".into()
1332 ),
1333 }
1334 );
1335 assert_eq!(
1336 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1337 .await,
1338 lsp::DidOpenTextDocumentParams {
1339 text_document: lsp::TextDocumentItem::new(
1340 buffer_2_uri.clone(),
1341 "plaintext".into(),
1342 0,
1343 "Goodbye".into()
1344 ),
1345 }
1346 );
1347 // Dropping a buffer causes it to be closed on the LSP side as well.
1348 cx.update(|_| drop(buffer_2));
1349 assert_eq!(
1350 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1351 .await,
1352 lsp::DidCloseTextDocumentParams {
1353 text_document: lsp::TextDocumentIdentifier::new(buffer_2_uri),
1354 }
1355 );
1356 }
1357
1358 struct File {
1359 abs_path: PathBuf,
1360 path: Arc<Path>,
1361 }
1362
1363 impl language::File for File {
1364 fn as_local(&self) -> Option<&dyn language::LocalFile> {
1365 Some(self)
1366 }
1367
1368 fn disk_state(&self) -> language::DiskState {
1369 language::DiskState::Present {
1370 mtime: ::fs::MTime::from_seconds_and_nanos(100, 42),
1371 }
1372 }
1373
1374 fn path(&self) -> &Arc<Path> {
1375 &self.path
1376 }
1377
1378 fn full_path(&self, _: &App) -> PathBuf {
1379 unimplemented!()
1380 }
1381
1382 fn file_name<'a>(&'a self, _: &'a App) -> &'a std::ffi::OsStr {
1383 unimplemented!()
1384 }
1385
1386 fn to_proto(&self, _: &App) -> rpc::proto::File {
1387 unimplemented!()
1388 }
1389
1390 fn worktree_id(&self, _: &App) -> settings::WorktreeId {
1391 settings::WorktreeId::from_usize(0)
1392 }
1393
1394 fn is_private(&self) -> bool {
1395 false
1396 }
1397 }
1398
1399 impl language::LocalFile for File {
1400 fn abs_path(&self, _: &App) -> PathBuf {
1401 self.abs_path.clone()
1402 }
1403
1404 fn load(&self, _: &App) -> Task<Result<String>> {
1405 unimplemented!()
1406 }
1407
1408 fn load_bytes(&self, _cx: &App) -> Task<Result<Vec<u8>>> {
1409 unimplemented!()
1410 }
1411 }
1412}
1413
1414#[cfg(test)]
1415#[ctor::ctor]
1416fn init_logger() {
1417 zlog::init_test();
1418}