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 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 ) -> impl Future<Output = ()> {
432 async move {
433 let start_language_server = async {
434 let server_path = get_copilot_lsp(http).await?;
435 let node_path = node_runtime.binary_path().await?;
436 let arguments: Vec<OsString> = vec![server_path.into(), "--stdio".into()];
437 let binary = LanguageServerBinary {
438 path: node_path,
439 arguments,
440 // TODO: We could set HTTP_PROXY etc here and fix the copilot issue.
441 env: None,
442 };
443
444 let root_path = if cfg!(target_os = "windows") {
445 Path::new("C:/")
446 } else {
447 Path::new("/")
448 };
449
450 let server = LanguageServer::new(
451 Arc::new(Mutex::new(None)),
452 new_server_id,
453 binary,
454 root_path,
455 None,
456 cx.clone(),
457 )?;
458
459 server
460 .on_notification::<StatusNotification, _>(
461 |_, _| { /* Silence the notification */ },
462 )
463 .detach();
464 let server = cx.update(|cx| server.initialize(None, cx))?.await?;
465
466 let status = server
467 .request::<request::CheckStatus>(request::CheckStatusParams {
468 local_checks_only: false,
469 })
470 .await?;
471
472 server
473 .request::<request::SetEditorInfo>(request::SetEditorInfoParams {
474 editor_info: request::EditorInfo {
475 name: "zed".into(),
476 version: env!("CARGO_PKG_VERSION").into(),
477 },
478 editor_plugin_info: request::EditorPluginInfo {
479 name: "zed-copilot".into(),
480 version: "0.0.1".into(),
481 },
482 })
483 .await?;
484
485 anyhow::Ok((server, status))
486 };
487
488 let server = start_language_server.await;
489 this.update(&mut cx, |this, cx| {
490 cx.notify();
491 match server {
492 Ok((server, status)) => {
493 this.server = CopilotServer::Running(RunningCopilotServer {
494 lsp: server,
495 sign_in_status: SignInStatus::SignedOut,
496 registered_buffers: Default::default(),
497 });
498 cx.emit(Event::CopilotLanguageServerStarted);
499 this.update_sign_in_status(status, cx);
500 }
501 Err(error) => {
502 this.server = CopilotServer::Error(error.to_string().into());
503 cx.notify()
504 }
505 }
506 })
507 .ok();
508 }
509 }
510
511 pub fn sign_in(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
512 if let CopilotServer::Running(server) = &mut self.server {
513 let task = match &server.sign_in_status {
514 SignInStatus::Authorized { .. } => Task::ready(Ok(())).shared(),
515 SignInStatus::SigningIn { task, .. } => {
516 cx.notify();
517 task.clone()
518 }
519 SignInStatus::SignedOut | SignInStatus::Unauthorized { .. } => {
520 let lsp = server.lsp.clone();
521 let task = cx
522 .spawn(|this, mut cx| async move {
523 let sign_in = async {
524 let sign_in = lsp
525 .request::<request::SignInInitiate>(
526 request::SignInInitiateParams {},
527 )
528 .await?;
529 match sign_in {
530 request::SignInInitiateResult::AlreadySignedIn { user } => {
531 Ok(request::SignInStatus::Ok { user: Some(user) })
532 }
533 request::SignInInitiateResult::PromptUserDeviceFlow(flow) => {
534 this.update(&mut cx, |this, cx| {
535 if let CopilotServer::Running(RunningCopilotServer {
536 sign_in_status: status,
537 ..
538 }) = &mut this.server
539 {
540 if let SignInStatus::SigningIn {
541 prompt: prompt_flow,
542 ..
543 } = status
544 {
545 *prompt_flow = Some(flow.clone());
546 cx.notify();
547 }
548 }
549 })?;
550 let response = lsp
551 .request::<request::SignInConfirm>(
552 request::SignInConfirmParams {
553 user_code: flow.user_code,
554 },
555 )
556 .await?;
557 Ok(response)
558 }
559 }
560 };
561
562 let sign_in = sign_in.await;
563 this.update(&mut cx, |this, cx| match sign_in {
564 Ok(status) => {
565 this.update_sign_in_status(status, cx);
566 Ok(())
567 }
568 Err(error) => {
569 this.update_sign_in_status(
570 request::SignInStatus::NotSignedIn,
571 cx,
572 );
573 Err(Arc::new(error))
574 }
575 })?
576 })
577 .shared();
578 server.sign_in_status = SignInStatus::SigningIn {
579 prompt: None,
580 task: task.clone(),
581 };
582 cx.notify();
583 task
584 }
585 };
586
587 cx.background_executor()
588 .spawn(task.map_err(|err| anyhow!("{:?}", err)))
589 } else {
590 // If we're downloading, wait until download is finished
591 // If we're in a stuck state, display to the user
592 Task::ready(Err(anyhow!("copilot hasn't started yet")))
593 }
594 }
595
596 pub fn sign_out(&mut self, cx: &mut ModelContext<Self>) -> Task<Result<()>> {
597 self.update_sign_in_status(request::SignInStatus::NotSignedIn, cx);
598 if let CopilotServer::Running(RunningCopilotServer { lsp: server, .. }) = &self.server {
599 let server = server.clone();
600 cx.background_executor().spawn(async move {
601 server
602 .request::<request::SignOut>(request::SignOutParams {})
603 .await?;
604 anyhow::Ok(())
605 })
606 } else {
607 Task::ready(Err(anyhow!("copilot hasn't started yet")))
608 }
609 }
610
611 pub fn reinstall(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
612 let start_task = cx
613 .spawn({
614 let http = self.http.clone();
615 let node_runtime = self.node_runtime.clone();
616 let server_id = self.server_id;
617 move |this, cx| async move {
618 clear_copilot_dir().await;
619 Self::start_language_server(server_id, http, node_runtime, this, cx).await
620 }
621 })
622 .shared();
623
624 self.server = CopilotServer::Starting {
625 task: start_task.clone(),
626 };
627
628 cx.notify();
629
630 cx.background_executor().spawn(start_task)
631 }
632
633 pub fn language_server(&self) -> Option<&Arc<LanguageServer>> {
634 if let CopilotServer::Running(server) = &self.server {
635 Some(&server.lsp)
636 } else {
637 None
638 }
639 }
640
641 pub fn register_buffer(&mut self, buffer: &Model<Buffer>, cx: &mut ModelContext<Self>) {
642 let weak_buffer = buffer.downgrade();
643 self.buffers.insert(weak_buffer.clone());
644
645 if let CopilotServer::Running(RunningCopilotServer {
646 lsp: server,
647 sign_in_status: status,
648 registered_buffers,
649 ..
650 }) = &mut self.server
651 {
652 if !matches!(status, SignInStatus::Authorized { .. }) {
653 return;
654 }
655
656 registered_buffers
657 .entry(buffer.entity_id())
658 .or_insert_with(|| {
659 let uri: lsp::Url = uri_for_buffer(buffer, cx);
660 let language_id = id_for_language(buffer.read(cx).language());
661 let snapshot = buffer.read(cx).snapshot();
662 server
663 .notify::<lsp::notification::DidOpenTextDocument>(
664 lsp::DidOpenTextDocumentParams {
665 text_document: lsp::TextDocumentItem {
666 uri: uri.clone(),
667 language_id: language_id.clone(),
668 version: 0,
669 text: snapshot.text(),
670 },
671 },
672 )
673 .log_err();
674
675 RegisteredBuffer {
676 uri,
677 language_id,
678 snapshot,
679 snapshot_version: 0,
680 pending_buffer_change: Task::ready(Some(())),
681 _subscriptions: [
682 cx.subscribe(buffer, |this, buffer, event, cx| {
683 this.handle_buffer_event(buffer, event, cx).log_err();
684 }),
685 cx.observe_release(buffer, move |this, _buffer, _cx| {
686 this.buffers.remove(&weak_buffer);
687 this.unregister_buffer(&weak_buffer);
688 }),
689 ],
690 }
691 });
692 }
693 }
694
695 fn handle_buffer_event(
696 &mut self,
697 buffer: Model<Buffer>,
698 event: &language::Event,
699 cx: &mut ModelContext<Self>,
700 ) -> Result<()> {
701 if let Ok(server) = self.server.as_running() {
702 if let Some(registered_buffer) = server.registered_buffers.get_mut(&buffer.entity_id())
703 {
704 match event {
705 language::Event::Edited => {
706 drop(registered_buffer.report_changes(&buffer, cx));
707 }
708 language::Event::Saved => {
709 server
710 .lsp
711 .notify::<lsp::notification::DidSaveTextDocument>(
712 lsp::DidSaveTextDocumentParams {
713 text_document: lsp::TextDocumentIdentifier::new(
714 registered_buffer.uri.clone(),
715 ),
716 text: None,
717 },
718 )?;
719 }
720 language::Event::FileHandleChanged | language::Event::LanguageChanged => {
721 let new_language_id = id_for_language(buffer.read(cx).language());
722 let new_uri = uri_for_buffer(&buffer, cx);
723 if new_uri != registered_buffer.uri
724 || new_language_id != registered_buffer.language_id
725 {
726 let old_uri = mem::replace(&mut registered_buffer.uri, new_uri);
727 registered_buffer.language_id = new_language_id;
728 server
729 .lsp
730 .notify::<lsp::notification::DidCloseTextDocument>(
731 lsp::DidCloseTextDocumentParams {
732 text_document: lsp::TextDocumentIdentifier::new(old_uri),
733 },
734 )?;
735 server
736 .lsp
737 .notify::<lsp::notification::DidOpenTextDocument>(
738 lsp::DidOpenTextDocumentParams {
739 text_document: lsp::TextDocumentItem::new(
740 registered_buffer.uri.clone(),
741 registered_buffer.language_id.clone(),
742 registered_buffer.snapshot_version,
743 registered_buffer.snapshot.text(),
744 ),
745 },
746 )?;
747 }
748 }
749 _ => {}
750 }
751 }
752 }
753
754 Ok(())
755 }
756
757 fn unregister_buffer(&mut self, buffer: &WeakModel<Buffer>) {
758 if let Ok(server) = self.server.as_running() {
759 if let Some(buffer) = server.registered_buffers.remove(&buffer.entity_id()) {
760 server
761 .lsp
762 .notify::<lsp::notification::DidCloseTextDocument>(
763 lsp::DidCloseTextDocumentParams {
764 text_document: lsp::TextDocumentIdentifier::new(buffer.uri),
765 },
766 )
767 .log_err();
768 }
769 }
770 }
771
772 pub fn completions<T>(
773 &mut self,
774 buffer: &Model<Buffer>,
775 position: T,
776 cx: &mut ModelContext<Self>,
777 ) -> Task<Result<Vec<Completion>>>
778 where
779 T: ToPointUtf16,
780 {
781 self.request_completions::<request::GetCompletions, _>(buffer, position, cx)
782 }
783
784 pub fn completions_cycling<T>(
785 &mut self,
786 buffer: &Model<Buffer>,
787 position: T,
788 cx: &mut ModelContext<Self>,
789 ) -> Task<Result<Vec<Completion>>>
790 where
791 T: ToPointUtf16,
792 {
793 self.request_completions::<request::GetCompletionsCycling, _>(buffer, position, cx)
794 }
795
796 pub fn accept_completion(
797 &mut self,
798 completion: &Completion,
799 cx: &mut ModelContext<Self>,
800 ) -> Task<Result<()>> {
801 let server = match self.server.as_authenticated() {
802 Ok(server) => server,
803 Err(error) => return Task::ready(Err(error)),
804 };
805 let request =
806 server
807 .lsp
808 .request::<request::NotifyAccepted>(request::NotifyAcceptedParams {
809 uuid: completion.uuid.clone(),
810 });
811 cx.background_executor().spawn(async move {
812 request.await?;
813 Ok(())
814 })
815 }
816
817 pub fn discard_completions(
818 &mut self,
819 completions: &[Completion],
820 cx: &mut ModelContext<Self>,
821 ) -> Task<Result<()>> {
822 let server = match self.server.as_authenticated() {
823 Ok(server) => server,
824 Err(_) => return Task::ready(Ok(())),
825 };
826 let request =
827 server
828 .lsp
829 .request::<request::NotifyRejected>(request::NotifyRejectedParams {
830 uuids: completions
831 .iter()
832 .map(|completion| completion.uuid.clone())
833 .collect(),
834 });
835 cx.background_executor().spawn(async move {
836 request.await?;
837 Ok(())
838 })
839 }
840
841 fn request_completions<R, T>(
842 &mut self,
843 buffer: &Model<Buffer>,
844 position: T,
845 cx: &mut ModelContext<Self>,
846 ) -> Task<Result<Vec<Completion>>>
847 where
848 R: 'static
849 + lsp::request::Request<
850 Params = request::GetCompletionsParams,
851 Result = request::GetCompletionsResult,
852 >,
853 T: ToPointUtf16,
854 {
855 self.register_buffer(buffer, cx);
856
857 let server = match self.server.as_authenticated() {
858 Ok(server) => server,
859 Err(error) => return Task::ready(Err(error)),
860 };
861 let lsp = server.lsp.clone();
862 let registered_buffer = server
863 .registered_buffers
864 .get_mut(&buffer.entity_id())
865 .unwrap();
866 let snapshot = registered_buffer.report_changes(buffer, cx);
867 let buffer = buffer.read(cx);
868 let uri = registered_buffer.uri.clone();
869 let position = position.to_point_utf16(buffer);
870 let settings = language_settings(buffer.language_at(position).as_ref(), buffer.file(), cx);
871 let tab_size = settings.tab_size;
872 let hard_tabs = settings.hard_tabs;
873 let relative_path = buffer
874 .file()
875 .map(|file| file.path().to_path_buf())
876 .unwrap_or_default();
877
878 cx.background_executor().spawn(async move {
879 let (version, snapshot) = snapshot.await?;
880 let result = lsp
881 .request::<R>(request::GetCompletionsParams {
882 doc: request::GetCompletionsDocument {
883 uri,
884 tab_size: tab_size.into(),
885 indent_size: 1,
886 insert_spaces: !hard_tabs,
887 relative_path: relative_path.to_string_lossy().into(),
888 position: point_to_lsp(position),
889 version: version.try_into().unwrap(),
890 },
891 })
892 .await?;
893 let completions = result
894 .completions
895 .into_iter()
896 .map(|completion| {
897 let start = snapshot
898 .clip_point_utf16(point_from_lsp(completion.range.start), Bias::Left);
899 let end =
900 snapshot.clip_point_utf16(point_from_lsp(completion.range.end), Bias::Left);
901 Completion {
902 uuid: completion.uuid,
903 range: snapshot.anchor_before(start)..snapshot.anchor_after(end),
904 text: completion.text,
905 }
906 })
907 .collect();
908 anyhow::Ok(completions)
909 })
910 }
911
912 pub fn status(&self) -> Status {
913 match &self.server {
914 CopilotServer::Starting { task } => Status::Starting { task: task.clone() },
915 CopilotServer::Disabled => Status::Disabled,
916 CopilotServer::Error(error) => Status::Error(error.clone()),
917 CopilotServer::Running(RunningCopilotServer { sign_in_status, .. }) => {
918 match sign_in_status {
919 SignInStatus::Authorized { .. } => Status::Authorized,
920 SignInStatus::Unauthorized { .. } => Status::Unauthorized,
921 SignInStatus::SigningIn { prompt, .. } => Status::SigningIn {
922 prompt: prompt.clone(),
923 },
924 SignInStatus::SignedOut => Status::SignedOut,
925 }
926 }
927 }
928 }
929
930 fn update_sign_in_status(
931 &mut self,
932 lsp_status: request::SignInStatus,
933 cx: &mut ModelContext<Self>,
934 ) {
935 self.buffers.retain(|buffer| buffer.is_upgradable());
936
937 if let Ok(server) = self.server.as_running() {
938 match lsp_status {
939 request::SignInStatus::Ok { user: Some(_) }
940 | request::SignInStatus::MaybeOk { .. }
941 | request::SignInStatus::AlreadySignedIn { .. } => {
942 server.sign_in_status = SignInStatus::Authorized;
943 cx.emit(Event::CopilotAuthSignedIn);
944 for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
945 if let Some(buffer) = buffer.upgrade() {
946 self.register_buffer(&buffer, cx);
947 }
948 }
949 }
950 request::SignInStatus::NotAuthorized { .. } => {
951 server.sign_in_status = SignInStatus::Unauthorized;
952 for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
953 self.unregister_buffer(&buffer);
954 }
955 }
956 request::SignInStatus::Ok { user: None } | request::SignInStatus::NotSignedIn => {
957 server.sign_in_status = SignInStatus::SignedOut;
958 cx.emit(Event::CopilotAuthSignedOut);
959 for buffer in self.buffers.iter().cloned().collect::<Vec<_>>() {
960 self.unregister_buffer(&buffer);
961 }
962 }
963 }
964
965 cx.notify();
966 }
967 }
968}
969
970fn id_for_language(language: Option<&Arc<Language>>) -> String {
971 language
972 .map(|language| language.lsp_id())
973 .unwrap_or_else(|| "plaintext".to_string())
974}
975
976fn uri_for_buffer(buffer: &Model<Buffer>, cx: &AppContext) -> lsp::Url {
977 if let Some(file) = buffer.read(cx).file().and_then(|file| file.as_local()) {
978 lsp::Url::from_file_path(file.abs_path(cx)).unwrap()
979 } else {
980 format!("buffer://{}", buffer.entity_id()).parse().unwrap()
981 }
982}
983
984async fn clear_copilot_dir() {
985 remove_matching(paths::copilot_dir(), |_| true).await
986}
987
988async fn get_copilot_lsp(http: Arc<dyn HttpClient>) -> anyhow::Result<PathBuf> {
989 const SERVER_PATH: &str = "dist/agent.js";
990
991 ///Check for the latest copilot language server and download it if we haven't already
992 async fn fetch_latest(http: Arc<dyn HttpClient>) -> anyhow::Result<PathBuf> {
993 let release =
994 latest_github_release("zed-industries/copilot", true, false, http.clone()).await?;
995
996 let version_dir = &paths::copilot_dir().join(format!("copilot-{}", release.tag_name));
997
998 fs::create_dir_all(version_dir).await?;
999 let server_path = version_dir.join(SERVER_PATH);
1000
1001 if fs::metadata(&server_path).await.is_err() {
1002 // Copilot LSP looks for this dist dir specifically, so lets add it in.
1003 let dist_dir = version_dir.join("dist");
1004 fs::create_dir_all(dist_dir.as_path()).await?;
1005
1006 let url = &release
1007 .assets
1008 .get(0)
1009 .context("Github release for copilot contained no assets")?
1010 .browser_download_url;
1011
1012 let mut response = http
1013 .get(url, Default::default(), true)
1014 .await
1015 .context("error downloading copilot release")?;
1016 let decompressed_bytes = GzipDecoder::new(BufReader::new(response.body_mut()));
1017 let archive = Archive::new(decompressed_bytes);
1018 archive.unpack(dist_dir).await?;
1019
1020 remove_matching(paths::copilot_dir(), |entry| entry != version_dir).await;
1021 }
1022
1023 Ok(server_path)
1024 }
1025
1026 match fetch_latest(http).await {
1027 ok @ Result::Ok(..) => ok,
1028 e @ Err(..) => {
1029 e.log_err();
1030 // Fetch a cached binary, if it exists
1031 maybe!(async {
1032 let mut last_version_dir = None;
1033 let mut entries = fs::read_dir(paths::copilot_dir()).await?;
1034 while let Some(entry) = entries.next().await {
1035 let entry = entry?;
1036 if entry.file_type().await?.is_dir() {
1037 last_version_dir = Some(entry.path());
1038 }
1039 }
1040 let last_version_dir =
1041 last_version_dir.ok_or_else(|| anyhow!("no cached binary"))?;
1042 let server_path = last_version_dir.join(SERVER_PATH);
1043 if server_path.exists() {
1044 Ok(server_path)
1045 } else {
1046 Err(anyhow!(
1047 "missing executable in directory {:?}",
1048 last_version_dir
1049 ))
1050 }
1051 })
1052 .await
1053 }
1054 }
1055}
1056
1057#[cfg(test)]
1058mod tests {
1059 use super::*;
1060 use gpui::TestAppContext;
1061
1062 #[gpui::test(iterations = 10)]
1063 async fn test_buffer_management(cx: &mut TestAppContext) {
1064 let (copilot, mut lsp) = Copilot::fake(cx);
1065
1066 let buffer_1 = cx.new_model(|cx| Buffer::local("Hello", cx));
1067 let buffer_1_uri: lsp::Url = format!("buffer://{}", buffer_1.entity_id().as_u64())
1068 .parse()
1069 .unwrap();
1070 copilot.update(cx, |copilot, cx| copilot.register_buffer(&buffer_1, cx));
1071 assert_eq!(
1072 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1073 .await,
1074 lsp::DidOpenTextDocumentParams {
1075 text_document: lsp::TextDocumentItem::new(
1076 buffer_1_uri.clone(),
1077 "plaintext".into(),
1078 0,
1079 "Hello".into()
1080 ),
1081 }
1082 );
1083
1084 let buffer_2 = cx.new_model(|cx| Buffer::local("Goodbye", cx));
1085 let buffer_2_uri: lsp::Url = format!("buffer://{}", buffer_2.entity_id().as_u64())
1086 .parse()
1087 .unwrap();
1088 copilot.update(cx, |copilot, cx| copilot.register_buffer(&buffer_2, cx));
1089 assert_eq!(
1090 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1091 .await,
1092 lsp::DidOpenTextDocumentParams {
1093 text_document: lsp::TextDocumentItem::new(
1094 buffer_2_uri.clone(),
1095 "plaintext".into(),
1096 0,
1097 "Goodbye".into()
1098 ),
1099 }
1100 );
1101
1102 buffer_1.update(cx, |buffer, cx| buffer.edit([(5..5, " world")], None, cx));
1103 assert_eq!(
1104 lsp.receive_notification::<lsp::notification::DidChangeTextDocument>()
1105 .await,
1106 lsp::DidChangeTextDocumentParams {
1107 text_document: lsp::VersionedTextDocumentIdentifier::new(buffer_1_uri.clone(), 1),
1108 content_changes: vec![lsp::TextDocumentContentChangeEvent {
1109 range: Some(lsp::Range::new(
1110 lsp::Position::new(0, 5),
1111 lsp::Position::new(0, 5)
1112 )),
1113 range_length: None,
1114 text: " world".into(),
1115 }],
1116 }
1117 );
1118
1119 // Ensure updates to the file are reflected in the LSP.
1120 buffer_1.update(cx, |buffer, cx| {
1121 buffer.file_updated(
1122 Arc::new(File {
1123 abs_path: "/root/child/buffer-1".into(),
1124 path: Path::new("child/buffer-1").into(),
1125 }),
1126 cx,
1127 )
1128 });
1129 assert_eq!(
1130 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1131 .await,
1132 lsp::DidCloseTextDocumentParams {
1133 text_document: lsp::TextDocumentIdentifier::new(buffer_1_uri),
1134 }
1135 );
1136 let buffer_1_uri = lsp::Url::from_file_path("/root/child/buffer-1").unwrap();
1137 assert_eq!(
1138 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1139 .await,
1140 lsp::DidOpenTextDocumentParams {
1141 text_document: lsp::TextDocumentItem::new(
1142 buffer_1_uri.clone(),
1143 "plaintext".into(),
1144 1,
1145 "Hello world".into()
1146 ),
1147 }
1148 );
1149
1150 // Ensure all previously-registered buffers are closed when signing out.
1151 lsp.handle_request::<request::SignOut, _, _>(|_, _| async {
1152 Ok(request::SignOutResult {})
1153 });
1154 copilot
1155 .update(cx, |copilot, cx| copilot.sign_out(cx))
1156 .await
1157 .unwrap();
1158 assert_eq!(
1159 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1160 .await,
1161 lsp::DidCloseTextDocumentParams {
1162 text_document: lsp::TextDocumentIdentifier::new(buffer_1_uri.clone()),
1163 }
1164 );
1165 assert_eq!(
1166 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1167 .await,
1168 lsp::DidCloseTextDocumentParams {
1169 text_document: lsp::TextDocumentIdentifier::new(buffer_2_uri.clone()),
1170 }
1171 );
1172
1173 // Ensure all previously-registered buffers are re-opened when signing in.
1174 lsp.handle_request::<request::SignInInitiate, _, _>(|_, _| async {
1175 Ok(request::SignInInitiateResult::AlreadySignedIn {
1176 user: "user-1".into(),
1177 })
1178 });
1179 copilot
1180 .update(cx, |copilot, cx| copilot.sign_in(cx))
1181 .await
1182 .unwrap();
1183
1184 assert_eq!(
1185 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1186 .await,
1187 lsp::DidOpenTextDocumentParams {
1188 text_document: lsp::TextDocumentItem::new(
1189 buffer_1_uri.clone(),
1190 "plaintext".into(),
1191 0,
1192 "Hello world".into()
1193 ),
1194 }
1195 );
1196 assert_eq!(
1197 lsp.receive_notification::<lsp::notification::DidOpenTextDocument>()
1198 .await,
1199 lsp::DidOpenTextDocumentParams {
1200 text_document: lsp::TextDocumentItem::new(
1201 buffer_2_uri.clone(),
1202 "plaintext".into(),
1203 0,
1204 "Goodbye".into()
1205 ),
1206 }
1207 );
1208 // Dropping a buffer causes it to be closed on the LSP side as well.
1209 cx.update(|_| drop(buffer_2));
1210 assert_eq!(
1211 lsp.receive_notification::<lsp::notification::DidCloseTextDocument>()
1212 .await,
1213 lsp::DidCloseTextDocumentParams {
1214 text_document: lsp::TextDocumentIdentifier::new(buffer_2_uri),
1215 }
1216 );
1217 }
1218
1219 struct File {
1220 abs_path: PathBuf,
1221 path: Arc<Path>,
1222 }
1223
1224 impl language::File for File {
1225 fn as_local(&self) -> Option<&dyn language::LocalFile> {
1226 Some(self)
1227 }
1228
1229 fn mtime(&self) -> Option<std::time::SystemTime> {
1230 unimplemented!()
1231 }
1232
1233 fn path(&self) -> &Arc<Path> {
1234 &self.path
1235 }
1236
1237 fn full_path(&self, _: &AppContext) -> PathBuf {
1238 unimplemented!()
1239 }
1240
1241 fn file_name<'a>(&'a self, _: &'a AppContext) -> &'a std::ffi::OsStr {
1242 unimplemented!()
1243 }
1244
1245 fn is_deleted(&self) -> bool {
1246 unimplemented!()
1247 }
1248
1249 fn as_any(&self) -> &dyn std::any::Any {
1250 unimplemented!()
1251 }
1252
1253 fn to_proto(&self, _: &AppContext) -> rpc::proto::File {
1254 unimplemented!()
1255 }
1256
1257 fn worktree_id(&self) -> usize {
1258 0
1259 }
1260
1261 fn is_private(&self) -> bool {
1262 false
1263 }
1264 }
1265
1266 impl language::LocalFile for File {
1267 fn abs_path(&self, _: &AppContext) -> PathBuf {
1268 self.abs_path.clone()
1269 }
1270
1271 fn load(&self, _: &AppContext) -> Task<Result<String>> {
1272 unimplemented!()
1273 }
1274 }
1275}