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