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