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