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