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, VersionCheck};
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 this.send_configuration_update(cx);
353 })
354 .detach();
355 this
356 }
357
358 fn shutdown_language_server(
359 &mut self,
360 _cx: &mut Context<Self>,
361 ) -> impl Future<Output = ()> + use<> {
362 let shutdown = match mem::replace(&mut self.server, CopilotServer::Disabled) {
363 CopilotServer::Running(server) => Some(Box::pin(async move { server.lsp.shutdown() })),
364 _ => None,
365 };
366
367 async move {
368 if let Some(shutdown) = shutdown {
369 shutdown.await;
370 }
371 }
372 }
373
374 fn start_copilot(
375 &mut self,
376 check_edit_prediction_provider: bool,
377 awaiting_sign_in_after_start: bool,
378 cx: &mut Context<Self>,
379 ) {
380 if !matches!(self.server, CopilotServer::Disabled) {
381 return;
382 }
383 let language_settings = all_language_settings(None, cx);
384 if check_edit_prediction_provider
385 && language_settings.edit_predictions.provider != EditPredictionProvider::Copilot
386 {
387 return;
388 }
389 let server_id = self.server_id;
390 let fs = self.fs.clone();
391 let node_runtime = self.node_runtime.clone();
392 let env = self.build_env(&language_settings.edit_predictions.copilot);
393 let start_task = cx
394 .spawn(async move |this, cx| {
395 Self::start_language_server(
396 server_id,
397 fs,
398 node_runtime,
399 env,
400 this,
401 awaiting_sign_in_after_start,
402 cx,
403 )
404 .await
405 })
406 .shared();
407 self.server = CopilotServer::Starting { task: start_task };
408 cx.notify();
409 }
410
411 fn build_env(&self, copilot_settings: &CopilotSettings) -> Option<HashMap<String, String>> {
412 let proxy_url = copilot_settings.proxy.clone()?;
413 let no_verify = copilot_settings.proxy_no_verify;
414 let http_or_https_proxy = if proxy_url.starts_with("http:") {
415 Some("HTTP_PROXY")
416 } else if proxy_url.starts_with("https:") {
417 Some("HTTPS_PROXY")
418 } else {
419 log::error!(
420 "Unsupported protocol scheme for language server proxy (must be http or https)"
421 );
422 None
423 };
424
425 let mut env = HashMap::default();
426
427 if let Some(proxy_type) = http_or_https_proxy {
428 env.insert(proxy_type.to_string(), proxy_url);
429 if let Some(true) = no_verify {
430 env.insert("NODE_TLS_REJECT_UNAUTHORIZED".to_string(), "0".to_string());
431 };
432 }
433
434 if let Ok(oauth_token) = env::var(copilot_chat::COPILOT_OAUTH_ENV_VAR) {
435 env.insert(copilot_chat::COPILOT_OAUTH_ENV_VAR.to_string(), oauth_token);
436 }
437
438 if env.is_empty() { None } else { Some(env) }
439 }
440
441 fn send_configuration_update(&mut self, cx: &mut Context<Self>) {
442 let copilot_settings = all_language_settings(None, cx)
443 .edit_predictions
444 .copilot
445 .clone();
446
447 let settings = json!({
448 "http": {
449 "proxy": copilot_settings.proxy,
450 "proxyStrictSSL": !copilot_settings.proxy_no_verify.unwrap_or(false)
451 },
452 "github-enterprise": {
453 "uri": copilot_settings.enterprise_uri
454 }
455 });
456
457 if let Some(copilot_chat) = copilot_chat::CopilotChat::global(cx) {
458 copilot_chat.update(cx, |chat, cx| {
459 chat.set_configuration(
460 copilot_chat::CopilotChatConfiguration {
461 enterprise_uri: copilot_settings.enterprise_uri.clone(),
462 },
463 cx,
464 );
465 });
466 }
467
468 if let Ok(server) = self.server.as_running() {
469 server
470 .lsp
471 .notify::<lsp::notification::DidChangeConfiguration>(
472 &lsp::DidChangeConfigurationParams { settings },
473 )
474 .log_err();
475 }
476 }
477
478 #[cfg(any(test, feature = "test-support"))]
479 pub fn fake(cx: &mut gpui::TestAppContext) -> (Entity<Self>, lsp::FakeLanguageServer) {
480 use fs::FakeFs;
481 use lsp::FakeLanguageServer;
482 use node_runtime::NodeRuntime;
483
484 let (server, fake_server) = FakeLanguageServer::new(
485 LanguageServerId(0),
486 LanguageServerBinary {
487 path: "path/to/copilot".into(),
488 arguments: vec![],
489 env: None,
490 },
491 "copilot".into(),
492 Default::default(),
493 &mut cx.to_async(),
494 );
495 let node_runtime = NodeRuntime::unavailable();
496 let this = cx.new(|cx| Self {
497 server_id: LanguageServerId(0),
498 fs: FakeFs::new(cx.background_executor().clone()),
499 node_runtime,
500 server: CopilotServer::Running(RunningCopilotServer {
501 lsp: Arc::new(server),
502 sign_in_status: SignInStatus::Authorized,
503 registered_buffers: Default::default(),
504 }),
505 _subscription: cx.on_app_quit(Self::shutdown_language_server),
506 buffers: Default::default(),
507 });
508 (this, fake_server)
509 }
510
511 async fn start_language_server(
512 new_server_id: LanguageServerId,
513 fs: Arc<dyn Fs>,
514 node_runtime: NodeRuntime,
515 env: Option<HashMap<String, String>>,
516 this: WeakEntity<Self>,
517 awaiting_sign_in_after_start: bool,
518 cx: &mut AsyncApp,
519 ) {
520 let start_language_server = async {
521 let server_path = get_copilot_lsp(fs, node_runtime.clone()).await?;
522 let node_path = node_runtime.binary_path().await?;
523 let arguments: Vec<OsString> = vec![server_path.into(), "--stdio".into()];
524 let binary = LanguageServerBinary {
525 path: node_path,
526 arguments,
527 env,
528 };
529
530 let root_path = if cfg!(target_os = "windows") {
531 Path::new("C:/")
532 } else {
533 Path::new("/")
534 };
535
536 let server_name = LanguageServerName("copilot".into());
537 let server = LanguageServer::new(
538 Arc::new(Mutex::new(None)),
539 new_server_id,
540 server_name,
541 binary,
542 root_path,
543 None,
544 Default::default(),
545 cx,
546 )?;
547
548 server
549 .on_notification::<StatusNotification, _>(|_, _| { /* Silence the notification */ })
550 .detach();
551
552 let configuration = lsp::DidChangeConfigurationParams {
553 settings: Default::default(),
554 };
555
556 let editor_info = request::SetEditorInfoParams {
557 editor_info: request::EditorInfo {
558 name: "zed".into(),
559 version: env!("CARGO_PKG_VERSION").into(),
560 },
561 editor_plugin_info: request::EditorPluginInfo {
562 name: "zed-copilot".into(),
563 version: "0.0.1".into(),
564 },
565 };
566 let editor_info_json = serde_json::to_value(&editor_info)?;
567
568 let server = cx
569 .update(|cx| {
570 let mut params = server.default_initialize_params(false, cx);
571 params.initialization_options = Some(editor_info_json);
572 server.initialize(params, configuration.into(), cx)
573 })?
574 .await?;
575
576 let status = server
577 .request::<request::CheckStatus>(request::CheckStatusParams {
578 local_checks_only: false,
579 })
580 .await
581 .into_response()
582 .context("copilot: check status")?;
583
584 anyhow::Ok((server, status))
585 };
586
587 let server = start_language_server.await;
588 this.update(cx, |this, cx| {
589 cx.notify();
590 match server {
591 Ok((server, status)) => {
592 this.server = CopilotServer::Running(RunningCopilotServer {
593 lsp: server,
594 sign_in_status: SignInStatus::SignedOut {
595 awaiting_signing_in: awaiting_sign_in_after_start,
596 },
597 registered_buffers: Default::default(),
598 });
599 cx.emit(Event::CopilotLanguageServerStarted);
600 this.update_sign_in_status(status, cx);
601 // Send configuration now that the LSP is fully started
602 this.send_configuration_update(cx);
603 }
604 Err(error) => {
605 this.server = CopilotServer::Error(error.to_string().into());
606 cx.notify()
607 }
608 }
609 })
610 .ok();
611 }
612
613 pub(crate) fn sign_in(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
614 if let CopilotServer::Running(server) = &mut self.server {
615 let task = match &server.sign_in_status {
616 SignInStatus::Authorized { .. } => Task::ready(Ok(())).shared(),
617 SignInStatus::SigningIn { task, .. } => {
618 cx.notify();
619 task.clone()
620 }
621 SignInStatus::SignedOut { .. } | SignInStatus::Unauthorized { .. } => {
622 let lsp = server.lsp.clone();
623 let task = cx
624 .spawn(async move |this, cx| {
625 let sign_in = async {
626 let sign_in = lsp
627 .request::<request::SignInInitiate>(
628 request::SignInInitiateParams {},
629 )
630 .await
631 .into_response()
632 .context("copilot sign-in")?;
633 match sign_in {
634 request::SignInInitiateResult::AlreadySignedIn { user } => {
635 Ok(request::SignInStatus::Ok { user: Some(user) })
636 }
637 request::SignInInitiateResult::PromptUserDeviceFlow(flow) => {
638 this.update(cx, |this, cx| {
639 if let CopilotServer::Running(RunningCopilotServer {
640 sign_in_status: status,
641 ..
642 }) = &mut this.server
643 {
644 if let SignInStatus::SigningIn {
645 prompt: prompt_flow,
646 ..
647 } = status
648 {
649 *prompt_flow = Some(flow.clone());
650 cx.notify();
651 }
652 }
653 })?;
654 let response = lsp
655 .request::<request::SignInConfirm>(
656 request::SignInConfirmParams {
657 user_code: flow.user_code,
658 },
659 )
660 .await
661 .into_response()
662 .context("copilot: sign in confirm")?;
663 Ok(response)
664 }
665 }
666 };
667
668 let sign_in = sign_in.await;
669 this.update(cx, |this, cx| match sign_in {
670 Ok(status) => {
671 this.update_sign_in_status(status, cx);
672 Ok(())
673 }
674 Err(error) => {
675 this.update_sign_in_status(
676 request::SignInStatus::NotSignedIn,
677 cx,
678 );
679 Err(Arc::new(error))
680 }
681 })?
682 })
683 .shared();
684 server.sign_in_status = SignInStatus::SigningIn {
685 prompt: None,
686 task: task.clone(),
687 };
688 cx.notify();
689 task
690 }
691 };
692
693 cx.background_spawn(task.map_err(|err| anyhow!("{err:?}")))
694 } else {
695 // If we're downloading, wait until download is finished
696 // If we're in a stuck state, display to the user
697 Task::ready(Err(anyhow!("copilot hasn't started yet")))
698 }
699 }
700
701 pub(crate) fn sign_out(&mut self, cx: &mut Context<Self>) -> Task<Result<()>> {
702 self.update_sign_in_status(request::SignInStatus::NotSignedIn, cx);
703 match &self.server {
704 CopilotServer::Running(RunningCopilotServer { lsp: server, .. }) => {
705 let server = server.clone();
706 cx.background_spawn(async move {
707 server
708 .request::<request::SignOut>(request::SignOutParams {})
709 .await
710 .into_response()
711 .context("copilot: sign in confirm")?;
712 anyhow::Ok(())
713 })
714 }
715 CopilotServer::Disabled => cx.background_spawn(async {
716 clear_copilot_config_dir().await;
717 anyhow::Ok(())
718 }),
719 _ => Task::ready(Err(anyhow!("copilot hasn't started yet"))),
720 }
721 }
722
723 pub(crate) fn reinstall(&mut self, cx: &mut Context<Self>) -> Shared<Task<()>> {
724 let language_settings = all_language_settings(None, cx);
725 let env = self.build_env(&language_settings.edit_predictions.copilot);
726 let start_task = cx
727 .spawn({
728 let fs = self.fs.clone();
729 let node_runtime = self.node_runtime.clone();
730 let server_id = self.server_id;
731 async move |this, cx| {
732 clear_copilot_dir().await;
733 Self::start_language_server(server_id, fs, node_runtime, env, this, false, cx)
734 .await
735 }
736 })
737 .shared();
738
739 self.server = CopilotServer::Starting {
740 task: start_task.clone(),
741 };
742
743 cx.notify();
744
745 start_task
746 }
747
748 pub fn language_server(&self) -> Option<&Arc<LanguageServer>> {
749 if let CopilotServer::Running(server) = &self.server {
750 Some(&server.lsp)
751 } else {
752 None
753 }
754 }
755
756 pub fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) {
757 let weak_buffer = buffer.downgrade();
758 self.buffers.insert(weak_buffer.clone());
759
760 if let CopilotServer::Running(RunningCopilotServer {
761 lsp: server,
762 sign_in_status: status,
763 registered_buffers,
764 ..
765 }) = &mut self.server
766 {
767 if !matches!(status, SignInStatus::Authorized { .. }) {
768 return;
769 }
770
771 let entry = registered_buffers.entry(buffer.entity_id());
772 if let Entry::Vacant(e) = entry {
773 let Ok(uri) = uri_for_buffer(buffer, cx) else {
774 return;
775 };
776 let language_id = id_for_language(buffer.read(cx).language());
777 let snapshot = buffer.read(cx).snapshot();
778 server
779 .notify::<lsp::notification::DidOpenTextDocument>(
780 &lsp::DidOpenTextDocumentParams {
781 text_document: lsp::TextDocumentItem {
782 uri: uri.clone(),
783 language_id: language_id.clone(),
784 version: 0,
785 text: snapshot.text(),
786 },
787 },
788 )
789 .ok();
790
791 e.insert(RegisteredBuffer {
792 uri,
793 language_id,
794 snapshot,
795 snapshot_version: 0,
796 pending_buffer_change: Task::ready(Some(())),
797 _subscriptions: [
798 cx.subscribe(buffer, |this, buffer, event, cx| {
799 this.handle_buffer_event(buffer, event, cx).log_err();
800 }),
801 cx.observe_release(buffer, move |this, _buffer, _cx| {
802 this.buffers.remove(&weak_buffer);
803 this.unregister_buffer(&weak_buffer);
804 }),
805 ],
806 });
807 }
808 }
809 }
810
811 fn handle_buffer_event(
812 &mut self,
813 buffer: Entity<Buffer>,
814 event: &language::BufferEvent,
815 cx: &mut Context<Self>,
816 ) -> Result<()> {
817 if let Ok(server) = self.server.as_running() {
818 if let Some(registered_buffer) = server.registered_buffers.get_mut(&buffer.entity_id())
819 {
820 match event {
821 language::BufferEvent::Edited => {
822 drop(registered_buffer.report_changes(&buffer, cx));
823 }
824 language::BufferEvent::Saved => {
825 server
826 .lsp
827 .notify::<lsp::notification::DidSaveTextDocument>(
828 &lsp::DidSaveTextDocumentParams {
829 text_document: lsp::TextDocumentIdentifier::new(
830 registered_buffer.uri.clone(),
831 ),
832 text: None,
833 },
834 )?;
835 }
836 language::BufferEvent::FileHandleChanged
837 | language::BufferEvent::LanguageChanged => {
838 let new_language_id = id_for_language(buffer.read(cx).language());
839 let Ok(new_uri) = uri_for_buffer(&buffer, cx) else {
840 return Ok(());
841 };
842 if new_uri != registered_buffer.uri
843 || new_language_id != registered_buffer.language_id
844 {
845 let old_uri = mem::replace(&mut registered_buffer.uri, new_uri);
846 registered_buffer.language_id = new_language_id;
847 server
848 .lsp
849 .notify::<lsp::notification::DidCloseTextDocument>(
850 &lsp::DidCloseTextDocumentParams {
851 text_document: lsp::TextDocumentIdentifier::new(old_uri),
852 },
853 )?;
854 server
855 .lsp
856 .notify::<lsp::notification::DidOpenTextDocument>(
857 &lsp::DidOpenTextDocumentParams {
858 text_document: lsp::TextDocumentItem::new(
859 registered_buffer.uri.clone(),
860 registered_buffer.language_id.clone(),
861 registered_buffer.snapshot_version,
862 registered_buffer.snapshot.text(),
863 ),
864 },
865 )?;
866 }
867 }
868 _ => {}
869 }
870 }
871 }
872
873 Ok(())
874 }
875
876 fn unregister_buffer(&mut self, buffer: &WeakEntity<Buffer>) {
877 if let Ok(server) = self.server.as_running() {
878 if let Some(buffer) = server.registered_buffers.remove(&buffer.entity_id()) {
879 server
880 .lsp
881 .notify::<lsp::notification::DidCloseTextDocument>(
882 &lsp::DidCloseTextDocumentParams {
883 text_document: lsp::TextDocumentIdentifier::new(buffer.uri),
884 },
885 )
886 .ok();
887 }
888 }
889 }
890
891 pub fn completions<T>(
892 &mut self,
893 buffer: &Entity<Buffer>,
894 position: T,
895 cx: &mut Context<Self>,
896 ) -> Task<Result<Vec<Completion>>>
897 where
898 T: ToPointUtf16,
899 {
900 self.request_completions::<request::GetCompletions, _>(buffer, position, cx)
901 }
902
903 pub fn completions_cycling<T>(
904 &mut self,
905 buffer: &Entity<Buffer>,
906 position: T,
907 cx: &mut Context<Self>,
908 ) -> Task<Result<Vec<Completion>>>
909 where
910 T: ToPointUtf16,
911 {
912 self.request_completions::<request::GetCompletionsCycling, _>(buffer, position, cx)
913 }
914
915 pub fn accept_completion(
916 &mut self,
917 completion: &Completion,
918 cx: &mut Context<Self>,
919 ) -> Task<Result<()>> {
920 let server = match self.server.as_authenticated() {
921 Ok(server) => server,
922 Err(error) => return Task::ready(Err(error)),
923 };
924 let request =
925 server
926 .lsp
927 .request::<request::NotifyAccepted>(request::NotifyAcceptedParams {
928 uuid: completion.uuid.clone(),
929 });
930 cx.background_spawn(async move {
931 request
932 .await
933 .into_response()
934 .context("copilot: notify accepted")?;
935 Ok(())
936 })
937 }
938
939 pub fn discard_completions(
940 &mut self,
941 completions: &[Completion],
942 cx: &mut Context<Self>,
943 ) -> Task<Result<()>> {
944 let server = match self.server.as_authenticated() {
945 Ok(server) => server,
946 Err(_) => return Task::ready(Ok(())),
947 };
948 let request =
949 server
950 .lsp
951 .request::<request::NotifyRejected>(request::NotifyRejectedParams {
952 uuids: completions
953 .iter()
954 .map(|completion| completion.uuid.clone())
955 .collect(),
956 });
957 cx.background_spawn(async move {
958 request
959 .await
960 .into_response()
961 .context("copilot: notify rejected")?;
962 Ok(())
963 })
964 }
965
966 fn request_completions<R, T>(
967 &mut self,
968 buffer: &Entity<Buffer>,
969 position: T,
970 cx: &mut Context<Self>,
971 ) -> Task<Result<Vec<Completion>>>
972 where
973 R: 'static
974 + lsp::request::Request<
975 Params = request::GetCompletionsParams,
976 Result = request::GetCompletionsResult,
977 >,
978 T: ToPointUtf16,
979 {
980 self.register_buffer(buffer, cx);
981
982 let server = match self.server.as_authenticated() {
983 Ok(server) => server,
984 Err(error) => return Task::ready(Err(error)),
985 };
986 let lsp = server.lsp.clone();
987 let registered_buffer = server
988 .registered_buffers
989 .get_mut(&buffer.entity_id())
990 .unwrap();
991 let snapshot = registered_buffer.report_changes(buffer, cx);
992 let buffer = buffer.read(cx);
993 let uri = registered_buffer.uri.clone();
994 let position = position.to_point_utf16(buffer);
995 let settings = language_settings(
996 buffer.language_at(position).map(|l| l.name()),
997 buffer.file(),
998 cx,
999 );
1000 let tab_size = settings.tab_size;
1001 let hard_tabs = settings.hard_tabs;
1002 let relative_path = buffer
1003 .file()
1004 .map(|file| file.path().to_path_buf())
1005 .unwrap_or_default();
1006
1007 cx.background_spawn(async move {
1008 let (version, snapshot) = snapshot.await?;
1009 let result = lsp
1010 .request::<R>(request::GetCompletionsParams {
1011 doc: request::GetCompletionsDocument {
1012 uri,
1013 tab_size: tab_size.into(),
1014 indent_size: 1,
1015 insert_spaces: !hard_tabs,
1016 relative_path: relative_path.to_string_lossy().into(),
1017 position: point_to_lsp(position),
1018 version: version.try_into().unwrap(),
1019 },
1020 })
1021 .await
1022 .into_response()
1023 .context("copilot: get completions")?;
1024 let completions = result
1025 .completions
1026 .into_iter()
1027 .map(|completion| {
1028 let start = snapshot
1029 .clip_point_utf16(point_from_lsp(completion.range.start), Bias::Left);
1030 let end =
1031 snapshot.clip_point_utf16(point_from_lsp(completion.range.end), Bias::Left);
1032 Completion {
1033 uuid: completion.uuid,
1034 range: snapshot.anchor_before(start)..snapshot.anchor_after(end),
1035 text: completion.text,
1036 }
1037 })
1038 .collect();
1039 anyhow::Ok(completions)
1040 })
1041 }
1042
1043 pub fn status(&self) -> Status {
1044 match &self.server {
1045 CopilotServer::Starting { task } => Status::Starting { task: task.clone() },
1046 CopilotServer::Disabled => Status::Disabled,
1047 CopilotServer::Error(error) => Status::Error(error.clone()),
1048 CopilotServer::Running(RunningCopilotServer { sign_in_status, .. }) => {
1049 match sign_in_status {
1050 SignInStatus::Authorized { .. } => Status::Authorized,
1051 SignInStatus::Unauthorized { .. } => Status::Unauthorized,
1052 SignInStatus::SigningIn { prompt, .. } => Status::SigningIn {
1053 prompt: prompt.clone(),
1054 },
1055 SignInStatus::SignedOut {
1056 awaiting_signing_in,
1057 } => Status::SignedOut {
1058 awaiting_signing_in: *awaiting_signing_in,
1059 },
1060 }
1061 }
1062 }
1063 }
1064
1065 fn update_sign_in_status(&mut self, lsp_status: request::SignInStatus, cx: &mut Context<Self>) {
1066 self.buffers.retain(|buffer| buffer.is_upgradable());
1067
1068 if let Ok(server) = self.server.as_running() {
1069 match lsp_status {
1070 request::SignInStatus::Ok { user: Some(_) }
1071 | request::SignInStatus::MaybeOk { .. }
1072 | request::SignInStatus::AlreadySignedIn { .. } => {
1073 server.sign_in_status = SignInStatus::Authorized;
1074 cx.emit(Event::CopilotAuthSignedIn);
1075 for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1076 if let Some(buffer) = buffer.upgrade() {
1077 self.register_buffer(&buffer, cx);
1078 }
1079 }
1080 }
1081 request::SignInStatus::NotAuthorized { .. } => {
1082 server.sign_in_status = SignInStatus::Unauthorized;
1083 for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1084 self.unregister_buffer(&buffer);
1085 }
1086 }
1087 request::SignInStatus::Ok { user: None } | request::SignInStatus::NotSignedIn => {
1088 if !matches!(server.sign_in_status, SignInStatus::SignedOut { .. }) {
1089 server.sign_in_status = SignInStatus::SignedOut {
1090 awaiting_signing_in: false,
1091 };
1092 }
1093 cx.emit(Event::CopilotAuthSignedOut);
1094 for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
1095 self.unregister_buffer(&buffer);
1096 }
1097 }
1098 }
1099
1100 cx.notify();
1101 }
1102 }
1103
1104 fn update_action_visibilities(&self, cx: &mut App) {
1105 let signed_in_actions = [
1106 TypeId::of::<Suggest>(),
1107 TypeId::of::<NextSuggestion>(),
1108 TypeId::of::<PreviousSuggestion>(),
1109 TypeId::of::<Reinstall>(),
1110 ];
1111 let auth_actions = [TypeId::of::<SignOut>()];
1112 let no_auth_actions = [TypeId::of::<SignIn>()];
1113 let status = self.status();
1114
1115 let is_ai_disabled = DisableAiSettings::get_global(cx).disable_ai;
1116 let filter = CommandPaletteFilter::global_mut(cx);
1117
1118 if is_ai_disabled {
1119 filter.hide_action_types(&signed_in_actions);
1120 filter.hide_action_types(&auth_actions);
1121 filter.hide_action_types(&no_auth_actions);
1122 } else {
1123 match status {
1124 Status::Disabled => {
1125 filter.hide_action_types(&signed_in_actions);
1126 filter.hide_action_types(&auth_actions);
1127 filter.hide_action_types(&no_auth_actions);
1128 }
1129 Status::Authorized => {
1130 filter.hide_action_types(&no_auth_actions);
1131 filter.show_action_types(signed_in_actions.iter().chain(&auth_actions));
1132 }
1133 _ => {
1134 filter.hide_action_types(&signed_in_actions);
1135 filter.hide_action_types(&auth_actions);
1136 filter.show_action_types(no_auth_actions.iter());
1137 }
1138 }
1139 }
1140 }
1141}
1142
1143fn id_for_language(language: Option<&Arc<Language>>) -> String {
1144 language
1145 .map(|language| language.lsp_id())
1146 .unwrap_or_else(|| "plaintext".to_string())
1147}
1148
1149fn uri_for_buffer(buffer: &Entity<Buffer>, cx: &App) -> Result<lsp::Url, ()> {
1150 if let Some(file) = buffer.read(cx).file().and_then(|file| file.as_local()) {
1151 lsp::Url::from_file_path(file.abs_path(cx))
1152 } else {
1153 format!("buffer://{}", buffer.entity_id())
1154 .parse()
1155 .map_err(|_| ())
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 // pinning it: https://github.com/zed-industries/zed/issues/36093
1173 const PINNED_VERSION: &str = "1.354";
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 &PINNED_VERSION,
1184 VersionCheck::VersionMismatch,
1185 )
1186 .await;
1187 if should_install {
1188 node_runtime
1189 .npm_install_packages(paths::copilot_dir(), &[(PACKAGE_NAME, &PINNED_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}