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