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