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