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