1mod completion_diff_element;
2mod init;
3mod input_excerpt;
4mod license_detection;
5mod onboarding_modal;
6mod onboarding_telemetry;
7mod rate_completion_modal;
8
9pub(crate) use completion_diff_element::*;
10use db::kvp::KEY_VALUE_STORE;
11pub use init::*;
12use inline_completion::{DataCollectionState, EditPredictionUsage};
13use license_detection::LICENSE_FILES_TO_CHECK;
14pub use license_detection::is_license_eligible_for_data_collection;
15pub use rate_completion_modal::*;
16
17use anyhow::{Context as _, Result, anyhow};
18use arrayvec::ArrayVec;
19use client::{Client, UserStore};
20use collections::{HashMap, HashSet, VecDeque};
21use futures::AsyncReadExt;
22use gpui::{
23 App, AppContext as _, AsyncApp, Context, Entity, EntityId, Global, SemanticVersion,
24 Subscription, Task, WeakEntity, actions,
25};
26use http_client::{AsyncBody, HttpClient, Method, Request, Response};
27use input_excerpt::excerpt_for_cursor_position;
28use language::{
29 Anchor, Buffer, BufferSnapshot, EditPreview, OffsetRangeExt, ToOffset, ToPoint, text_diff,
30};
31use language_model::{LlmApiToken, RefreshLlmTokenListener};
32use postage::watch;
33use project::Project;
34use release_channel::AppVersion;
35use settings::WorktreeId;
36use std::str::FromStr;
37use std::{
38 borrow::Cow,
39 cmp,
40 fmt::Write,
41 future::Future,
42 mem,
43 ops::Range,
44 path::Path,
45 rc::Rc,
46 sync::Arc,
47 time::{Duration, Instant},
48};
49use telemetry_events::InlineCompletionRating;
50use thiserror::Error;
51use util::{ResultExt, maybe};
52use uuid::Uuid;
53use workspace::Workspace;
54use workspace::notifications::{ErrorMessagePrompt, NotificationId};
55use worktree::Worktree;
56use zed_llm_client::{
57 AcceptEditPredictionBody, EXPIRED_LLM_TOKEN_HEADER_NAME, MINIMUM_REQUIRED_VERSION_HEADER_NAME,
58 PredictEditsBody, PredictEditsResponse, ZED_VERSION_HEADER_NAME,
59};
60
61const CURSOR_MARKER: &'static str = "<|user_cursor_is_here|>";
62const START_OF_FILE_MARKER: &'static str = "<|start_of_file|>";
63const EDITABLE_REGION_START_MARKER: &'static str = "<|editable_region_start|>";
64const EDITABLE_REGION_END_MARKER: &'static str = "<|editable_region_end|>";
65const BUFFER_CHANGE_GROUPING_INTERVAL: Duration = Duration::from_secs(1);
66const ZED_PREDICT_DATA_COLLECTION_CHOICE: &str = "zed_predict_data_collection_choice";
67
68const MAX_CONTEXT_TOKENS: usize = 150;
69const MAX_REWRITE_TOKENS: usize = 350;
70const MAX_EVENT_TOKENS: usize = 500;
71
72/// Maximum number of events to track.
73const MAX_EVENT_COUNT: usize = 16;
74
75actions!(edit_prediction, [ClearHistory]);
76
77#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
78pub struct InlineCompletionId(Uuid);
79
80impl From<InlineCompletionId> for gpui::ElementId {
81 fn from(value: InlineCompletionId) -> Self {
82 gpui::ElementId::Uuid(value.0)
83 }
84}
85
86impl std::fmt::Display for InlineCompletionId {
87 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88 write!(f, "{}", self.0)
89 }
90}
91
92#[derive(Clone)]
93struct ZetaGlobal(Entity<Zeta>);
94
95impl Global for ZetaGlobal {}
96
97#[derive(Clone)]
98pub struct InlineCompletion {
99 id: InlineCompletionId,
100 path: Arc<Path>,
101 excerpt_range: Range<usize>,
102 cursor_offset: usize,
103 edits: Arc<[(Range<Anchor>, String)]>,
104 snapshot: BufferSnapshot,
105 edit_preview: EditPreview,
106 input_outline: Arc<str>,
107 input_events: Arc<str>,
108 input_excerpt: Arc<str>,
109 output_excerpt: Arc<str>,
110 request_sent_at: Instant,
111 response_received_at: Instant,
112}
113
114impl InlineCompletion {
115 fn latency(&self) -> Duration {
116 self.response_received_at
117 .duration_since(self.request_sent_at)
118 }
119
120 fn interpolate(&self, new_snapshot: &BufferSnapshot) -> Option<Vec<(Range<Anchor>, String)>> {
121 interpolate(&self.snapshot, new_snapshot, self.edits.clone())
122 }
123}
124
125fn interpolate(
126 old_snapshot: &BufferSnapshot,
127 new_snapshot: &BufferSnapshot,
128 current_edits: Arc<[(Range<Anchor>, String)]>,
129) -> Option<Vec<(Range<Anchor>, String)>> {
130 let mut edits = Vec::new();
131
132 let mut model_edits = current_edits.into_iter().peekable();
133 for user_edit in new_snapshot.edits_since::<usize>(&old_snapshot.version) {
134 while let Some((model_old_range, _)) = model_edits.peek() {
135 let model_old_range = model_old_range.to_offset(old_snapshot);
136 if model_old_range.end < user_edit.old.start {
137 let (model_old_range, model_new_text) = model_edits.next().unwrap();
138 edits.push((model_old_range.clone(), model_new_text.clone()));
139 } else {
140 break;
141 }
142 }
143
144 if let Some((model_old_range, model_new_text)) = model_edits.peek() {
145 let model_old_offset_range = model_old_range.to_offset(old_snapshot);
146 if user_edit.old == model_old_offset_range {
147 let user_new_text = new_snapshot
148 .text_for_range(user_edit.new.clone())
149 .collect::<String>();
150
151 if let Some(model_suffix) = model_new_text.strip_prefix(&user_new_text) {
152 if !model_suffix.is_empty() {
153 let anchor = old_snapshot.anchor_after(user_edit.old.end);
154 edits.push((anchor..anchor, model_suffix.to_string()));
155 }
156
157 model_edits.next();
158 continue;
159 }
160 }
161 }
162
163 return None;
164 }
165
166 edits.extend(model_edits.cloned());
167
168 if edits.is_empty() { None } else { Some(edits) }
169}
170
171impl std::fmt::Debug for InlineCompletion {
172 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
173 f.debug_struct("InlineCompletion")
174 .field("id", &self.id)
175 .field("path", &self.path)
176 .field("edits", &self.edits)
177 .finish_non_exhaustive()
178 }
179}
180
181pub struct Zeta {
182 workspace: Option<WeakEntity<Workspace>>,
183 client: Arc<Client>,
184 events: VecDeque<Event>,
185 registered_buffers: HashMap<gpui::EntityId, RegisteredBuffer>,
186 shown_completions: VecDeque<InlineCompletion>,
187 rated_completions: HashSet<InlineCompletionId>,
188 data_collection_choice: Entity<DataCollectionChoice>,
189 llm_token: LlmApiToken,
190 _llm_token_subscription: Subscription,
191 last_usage: Option<EditPredictionUsage>,
192 /// Whether the terms of service have been accepted.
193 tos_accepted: bool,
194 /// Whether an update to a newer version of Zed is required to continue using Zeta.
195 update_required: bool,
196 user_store: Entity<UserStore>,
197 _user_store_subscription: Subscription,
198 license_detection_watchers: HashMap<WorktreeId, Rc<LicenseDetectionWatcher>>,
199}
200
201impl Zeta {
202 pub fn global(cx: &mut App) -> Option<Entity<Self>> {
203 cx.try_global::<ZetaGlobal>().map(|global| global.0.clone())
204 }
205
206 pub fn register(
207 workspace: Option<WeakEntity<Workspace>>,
208 worktree: Option<Entity<Worktree>>,
209 client: Arc<Client>,
210 user_store: Entity<UserStore>,
211 cx: &mut App,
212 ) -> Entity<Self> {
213 let this = Self::global(cx).unwrap_or_else(|| {
214 let entity = cx.new(|cx| Self::new(workspace, client, user_store, cx));
215 cx.set_global(ZetaGlobal(entity.clone()));
216 entity
217 });
218
219 this.update(cx, move |this, cx| {
220 if let Some(worktree) = worktree {
221 worktree.update(cx, |worktree, cx| {
222 this.license_detection_watchers
223 .entry(worktree.id())
224 .or_insert_with(|| Rc::new(LicenseDetectionWatcher::new(worktree, cx)));
225 });
226 }
227 });
228
229 this
230 }
231
232 pub fn clear_history(&mut self) {
233 self.events.clear();
234 }
235
236 pub fn usage(&self, cx: &App) -> Option<EditPredictionUsage> {
237 self.last_usage.or_else(|| {
238 let user_store = self.user_store.read(cx);
239 maybe!({
240 let amount = user_store.edit_predictions_usage_amount()?;
241 let limit = user_store.edit_predictions_usage_limit()?.variant?;
242
243 Some(EditPredictionUsage {
244 amount: amount as i32,
245 limit: match limit {
246 proto::usage_limit::Variant::Limited(limited) => {
247 zed_llm_client::UsageLimit::Limited(limited.limit as i32)
248 }
249 proto::usage_limit::Variant::Unlimited(_) => {
250 zed_llm_client::UsageLimit::Unlimited
251 }
252 },
253 })
254 })
255 })
256 }
257
258 fn new(
259 workspace: Option<WeakEntity<Workspace>>,
260 client: Arc<Client>,
261 user_store: Entity<UserStore>,
262 cx: &mut Context<Self>,
263 ) -> Self {
264 let refresh_llm_token_listener = RefreshLlmTokenListener::global(cx);
265
266 let data_collection_choice = Self::load_data_collection_choices();
267 let data_collection_choice = cx.new(|_| data_collection_choice);
268
269 Self {
270 workspace,
271 client,
272 events: VecDeque::new(),
273 shown_completions: VecDeque::new(),
274 rated_completions: HashSet::default(),
275 registered_buffers: HashMap::default(),
276 data_collection_choice,
277 llm_token: LlmApiToken::default(),
278 _llm_token_subscription: cx.subscribe(
279 &refresh_llm_token_listener,
280 |this, _listener, _event, cx| {
281 let client = this.client.clone();
282 let llm_token = this.llm_token.clone();
283 cx.spawn(async move |_this, _cx| {
284 llm_token.refresh(&client).await?;
285 anyhow::Ok(())
286 })
287 .detach_and_log_err(cx);
288 },
289 ),
290 last_usage: None,
291 tos_accepted: user_store
292 .read(cx)
293 .current_user_has_accepted_terms()
294 .unwrap_or(false),
295 update_required: false,
296 _user_store_subscription: cx.subscribe(&user_store, |this, user_store, event, cx| {
297 match event {
298 client::user::Event::PrivateUserInfoUpdated => {
299 this.tos_accepted = user_store
300 .read(cx)
301 .current_user_has_accepted_terms()
302 .unwrap_or(false);
303 }
304 _ => {}
305 }
306 }),
307 license_detection_watchers: HashMap::default(),
308 user_store,
309 }
310 }
311
312 fn push_event(&mut self, event: Event) {
313 if let Some(Event::BufferChange {
314 new_snapshot: last_new_snapshot,
315 timestamp: last_timestamp,
316 ..
317 }) = self.events.back_mut()
318 {
319 // Coalesce edits for the same buffer when they happen one after the other.
320 let Event::BufferChange {
321 old_snapshot,
322 new_snapshot,
323 timestamp,
324 } = &event;
325
326 if timestamp.duration_since(*last_timestamp) <= BUFFER_CHANGE_GROUPING_INTERVAL
327 && old_snapshot.remote_id() == last_new_snapshot.remote_id()
328 && old_snapshot.version == last_new_snapshot.version
329 {
330 *last_new_snapshot = new_snapshot.clone();
331 *last_timestamp = *timestamp;
332 return;
333 }
334 }
335
336 self.events.push_back(event);
337 if self.events.len() >= MAX_EVENT_COUNT {
338 self.events.drain(..MAX_EVENT_COUNT / 2);
339 }
340 }
341
342 pub fn register_buffer(&mut self, buffer: &Entity<Buffer>, cx: &mut Context<Self>) {
343 let buffer_id = buffer.entity_id();
344 let weak_buffer = buffer.downgrade();
345
346 if let std::collections::hash_map::Entry::Vacant(entry) =
347 self.registered_buffers.entry(buffer_id)
348 {
349 let snapshot = buffer.read(cx).snapshot();
350
351 entry.insert(RegisteredBuffer {
352 snapshot,
353 _subscriptions: [
354 cx.subscribe(buffer, move |this, buffer, event, cx| {
355 this.handle_buffer_event(buffer, event, cx);
356 }),
357 cx.observe_release(buffer, move |this, _buffer, _cx| {
358 this.registered_buffers.remove(&weak_buffer.entity_id());
359 }),
360 ],
361 });
362 };
363 }
364
365 fn handle_buffer_event(
366 &mut self,
367 buffer: Entity<Buffer>,
368 event: &language::BufferEvent,
369 cx: &mut Context<Self>,
370 ) {
371 if let language::BufferEvent::Edited = event {
372 self.report_changes_for_buffer(&buffer, cx);
373 }
374 }
375
376 fn request_completion_impl<F, R>(
377 &mut self,
378 workspace: Option<Entity<Workspace>>,
379 project: Option<&Entity<Project>>,
380 buffer: &Entity<Buffer>,
381 cursor: language::Anchor,
382 can_collect_data: bool,
383 cx: &mut Context<Self>,
384 perform_predict_edits: F,
385 ) -> Task<Result<Option<InlineCompletion>>>
386 where
387 F: FnOnce(PerformPredictEditsParams) -> R + 'static,
388 R: Future<Output = Result<(PredictEditsResponse, Option<EditPredictionUsage>)>>
389 + Send
390 + 'static,
391 {
392 let snapshot = self.report_changes_for_buffer(&buffer, cx);
393 let diagnostic_groups = snapshot.diagnostic_groups(None);
394 let cursor_point = cursor.to_point(&snapshot);
395 let cursor_offset = cursor_point.to_offset(&snapshot);
396 let events = self.events.clone();
397 let path: Arc<Path> = snapshot
398 .file()
399 .map(|f| Arc::from(f.full_path(cx).as_path()))
400 .unwrap_or_else(|| Arc::from(Path::new("untitled")));
401
402 let zeta = cx.entity();
403 let client = self.client.clone();
404 let llm_token = self.llm_token.clone();
405 let app_version = AppVersion::global(cx);
406
407 let buffer = buffer.clone();
408
409 let local_lsp_store =
410 project.and_then(|project| project.read(cx).lsp_store().read(cx).as_local());
411 let diagnostic_groups = if let Some(local_lsp_store) = local_lsp_store {
412 Some(
413 diagnostic_groups
414 .into_iter()
415 .filter_map(|(language_server_id, diagnostic_group)| {
416 let language_server =
417 local_lsp_store.running_language_server_for_id(language_server_id)?;
418
419 Some((
420 language_server.name(),
421 diagnostic_group.resolve::<usize>(&snapshot),
422 ))
423 })
424 .collect::<Vec<_>>(),
425 )
426 } else {
427 None
428 };
429
430 cx.spawn(async move |this, cx| {
431 let request_sent_at = Instant::now();
432
433 struct BackgroundValues {
434 input_events: String,
435 input_excerpt: String,
436 speculated_output: String,
437 editable_range: Range<usize>,
438 input_outline: String,
439 }
440
441 let values = cx
442 .background_spawn({
443 let snapshot = snapshot.clone();
444 let path = path.clone();
445 async move {
446 let path = path.to_string_lossy();
447 let input_excerpt = excerpt_for_cursor_position(
448 cursor_point,
449 &path,
450 &snapshot,
451 MAX_REWRITE_TOKENS,
452 MAX_CONTEXT_TOKENS,
453 );
454 let input_events = prompt_for_events(&events, MAX_EVENT_TOKENS);
455 let input_outline = prompt_for_outline(&snapshot);
456
457 anyhow::Ok(BackgroundValues {
458 input_events,
459 input_excerpt: input_excerpt.prompt,
460 speculated_output: input_excerpt.speculated_output,
461 editable_range: input_excerpt.editable_range.to_offset(&snapshot),
462 input_outline,
463 })
464 }
465 })
466 .await?;
467
468 log::debug!(
469 "Events:\n{}\nExcerpt:\n{:?}",
470 values.input_events,
471 values.input_excerpt
472 );
473
474 let body = PredictEditsBody {
475 input_events: values.input_events.clone(),
476 input_excerpt: values.input_excerpt.clone(),
477 speculated_output: Some(values.speculated_output),
478 outline: Some(values.input_outline.clone()),
479 can_collect_data,
480 diagnostic_groups: diagnostic_groups.and_then(|diagnostic_groups| {
481 diagnostic_groups
482 .into_iter()
483 .map(|(name, diagnostic_group)| {
484 Ok((name.to_string(), serde_json::to_value(diagnostic_group)?))
485 })
486 .collect::<Result<Vec<_>>>()
487 .log_err()
488 }),
489 };
490
491 let response = perform_predict_edits(PerformPredictEditsParams {
492 client,
493 llm_token,
494 app_version,
495 body,
496 })
497 .await;
498 let (response, usage) = match response {
499 Ok(response) => response,
500 Err(err) => {
501 if err.is::<ZedUpdateRequiredError>() {
502 cx.update(|cx| {
503 zeta.update(cx, |zeta, _cx| {
504 zeta.update_required = true;
505 });
506
507 if let Some(workspace) = workspace {
508 workspace.update(cx, |workspace, cx| {
509 workspace.show_notification(
510 NotificationId::unique::<ZedUpdateRequiredError>(),
511 cx,
512 |cx| {
513 cx.new(|cx| {
514 ErrorMessagePrompt::new(err.to_string(), cx)
515 .with_link_button(
516 "Update Zed",
517 "https://zed.dev/releases",
518 )
519 })
520 },
521 );
522 });
523 }
524 })
525 .ok();
526 }
527
528 return Err(err);
529 }
530 };
531
532 log::debug!("completion response: {}", &response.output_excerpt);
533
534 if let Some(usage) = usage {
535 this.update(cx, |this, _cx| {
536 this.last_usage = Some(usage);
537 })
538 .ok();
539 }
540
541 Self::process_completion_response(
542 response,
543 buffer,
544 &snapshot,
545 values.editable_range,
546 cursor_offset,
547 path,
548 values.input_outline,
549 values.input_events,
550 values.input_excerpt,
551 request_sent_at,
552 &cx,
553 )
554 .await
555 })
556 }
557
558 // Generates several example completions of various states to fill the Zeta completion modal
559 #[cfg(any(test, feature = "test-support"))]
560 pub fn fill_with_fake_completions(&mut self, cx: &mut Context<Self>) -> Task<()> {
561 use language::Point;
562
563 let test_buffer_text = indoc::indoc! {r#"a longggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg line
564 And maybe a short line
565
566 Then a few lines
567
568 and then another
569 "#};
570
571 let project = None;
572 let buffer = cx.new(|cx| Buffer::local(test_buffer_text, cx));
573 let position = buffer.read(cx).anchor_before(Point::new(1, 0));
574
575 let completion_tasks = vec![
576 self.fake_completion(
577 project,
578 &buffer,
579 position,
580 PredictEditsResponse {
581 request_id: Uuid::parse_str("e7861db5-0cea-4761-b1c5-ad083ac53a80").unwrap(),
582 output_excerpt: format!("{EDITABLE_REGION_START_MARKER}
583a longggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg line
584[here's an edit]
585And maybe a short line
586Then a few lines
587and then another
588{EDITABLE_REGION_END_MARKER}
589 ", ),
590 },
591 cx,
592 ),
593 self.fake_completion(
594 project,
595 &buffer,
596 position,
597 PredictEditsResponse {
598 request_id: Uuid::parse_str("077c556a-2c49-44e2-bbc6-dafc09032a5e").unwrap(),
599 output_excerpt: format!(r#"{EDITABLE_REGION_START_MARKER}
600a longggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg line
601And maybe a short line
602[and another edit]
603Then a few lines
604and then another
605{EDITABLE_REGION_END_MARKER}
606 "#),
607 },
608 cx,
609 ),
610 self.fake_completion(
611 project,
612 &buffer,
613 position,
614 PredictEditsResponse {
615 request_id: Uuid::parse_str("df8c7b23-3d1d-4f99-a306-1f6264a41277").unwrap(),
616 output_excerpt: format!(r#"{EDITABLE_REGION_START_MARKER}
617a longggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg line
618And maybe a short line
619
620Then a few lines
621
622and then another
623{EDITABLE_REGION_END_MARKER}
624 "#),
625 },
626 cx,
627 ),
628 self.fake_completion(
629 project,
630 &buffer,
631 position,
632 PredictEditsResponse {
633 request_id: Uuid::parse_str("c743958d-e4d8-44a8-aa5b-eb1e305c5f5c").unwrap(),
634 output_excerpt: format!(r#"{EDITABLE_REGION_START_MARKER}
635a longggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg line
636And maybe a short line
637
638Then a few lines
639
640and then another
641{EDITABLE_REGION_END_MARKER}
642 "#),
643 },
644 cx,
645 ),
646 self.fake_completion(
647 project,
648 &buffer,
649 position,
650 PredictEditsResponse {
651 request_id: Uuid::parse_str("ff5cd7ab-ad06-4808-986e-d3391e7b8355").unwrap(),
652 output_excerpt: format!(r#"{EDITABLE_REGION_START_MARKER}
653a longggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg line
654And maybe a short line
655Then a few lines
656[a third completion]
657and then another
658{EDITABLE_REGION_END_MARKER}
659 "#),
660 },
661 cx,
662 ),
663 self.fake_completion(
664 project,
665 &buffer,
666 position,
667 PredictEditsResponse {
668 request_id: Uuid::parse_str("83cafa55-cdba-4b27-8474-1865ea06be94").unwrap(),
669 output_excerpt: format!(r#"{EDITABLE_REGION_START_MARKER}
670a longggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg line
671And maybe a short line
672and then another
673[fourth completion example]
674{EDITABLE_REGION_END_MARKER}
675 "#),
676 },
677 cx,
678 ),
679 self.fake_completion(
680 project,
681 &buffer,
682 position,
683 PredictEditsResponse {
684 request_id: Uuid::parse_str("d5bd3afd-8723-47c7-bd77-15a3a926867b").unwrap(),
685 output_excerpt: format!(r#"{EDITABLE_REGION_START_MARKER}
686a longggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg line
687And maybe a short line
688Then a few lines
689and then another
690[fifth and final completion]
691{EDITABLE_REGION_END_MARKER}
692 "#),
693 },
694 cx,
695 ),
696 ];
697
698 cx.spawn(async move |zeta, cx| {
699 for task in completion_tasks {
700 task.await.unwrap();
701 }
702
703 zeta.update(cx, |zeta, _cx| {
704 zeta.shown_completions.get_mut(2).unwrap().edits = Arc::new([]);
705 zeta.shown_completions.get_mut(3).unwrap().edits = Arc::new([]);
706 })
707 .ok();
708 })
709 }
710
711 #[cfg(any(test, feature = "test-support"))]
712 pub fn fake_completion(
713 &mut self,
714 project: Option<&Entity<Project>>,
715 buffer: &Entity<Buffer>,
716 position: language::Anchor,
717 response: PredictEditsResponse,
718 cx: &mut Context<Self>,
719 ) -> Task<Result<Option<InlineCompletion>>> {
720 use std::future::ready;
721
722 self.request_completion_impl(None, project, buffer, position, false, cx, |_params| {
723 ready(Ok((response, None)))
724 })
725 }
726
727 pub fn request_completion(
728 &mut self,
729 project: Option<&Entity<Project>>,
730 buffer: &Entity<Buffer>,
731 position: language::Anchor,
732 can_collect_data: bool,
733 cx: &mut Context<Self>,
734 ) -> Task<Result<Option<InlineCompletion>>> {
735 let workspace = self
736 .workspace
737 .as_ref()
738 .and_then(|workspace| workspace.upgrade());
739 self.request_completion_impl(
740 workspace,
741 project,
742 buffer,
743 position,
744 can_collect_data,
745 cx,
746 Self::perform_predict_edits,
747 )
748 }
749
750 fn perform_predict_edits(
751 params: PerformPredictEditsParams,
752 ) -> impl Future<Output = Result<(PredictEditsResponse, Option<EditPredictionUsage>)>> {
753 async move {
754 let PerformPredictEditsParams {
755 client,
756 llm_token,
757 app_version,
758 body,
759 ..
760 } = params;
761
762 let http_client = client.http_client();
763 let mut token = llm_token.acquire(&client).await?;
764 let mut did_retry = false;
765
766 loop {
767 let request_builder = http_client::Request::builder().method(Method::POST);
768 let request_builder =
769 if let Ok(predict_edits_url) = std::env::var("ZED_PREDICT_EDITS_URL") {
770 request_builder.uri(predict_edits_url)
771 } else {
772 request_builder.uri(
773 http_client
774 .build_zed_llm_url("/predict_edits/v2", &[])?
775 .as_ref(),
776 )
777 };
778 let request = request_builder
779 .header("Content-Type", "application/json")
780 .header("Authorization", format!("Bearer {}", token))
781 .header(ZED_VERSION_HEADER_NAME, app_version.to_string())
782 .body(serde_json::to_string(&body)?.into())?;
783
784 let mut response = http_client.send(request).await?;
785
786 if let Some(minimum_required_version) = response
787 .headers()
788 .get(MINIMUM_REQUIRED_VERSION_HEADER_NAME)
789 .and_then(|version| SemanticVersion::from_str(version.to_str().ok()?).ok())
790 {
791 if app_version < minimum_required_version {
792 return Err(anyhow!(ZedUpdateRequiredError {
793 minimum_version: minimum_required_version
794 }));
795 }
796 }
797
798 if response.status().is_success() {
799 let usage = EditPredictionUsage::from_headers(response.headers()).ok();
800
801 let mut body = String::new();
802 response.body_mut().read_to_string(&mut body).await?;
803 return Ok((serde_json::from_str(&body)?, usage));
804 } else if !did_retry
805 && response
806 .headers()
807 .get(EXPIRED_LLM_TOKEN_HEADER_NAME)
808 .is_some()
809 {
810 did_retry = true;
811 token = llm_token.refresh(&client).await?;
812 } else {
813 let mut body = String::new();
814 response.body_mut().read_to_string(&mut body).await?;
815 return Err(anyhow!(
816 "error predicting edits.\nStatus: {:?}\nBody: {}",
817 response.status(),
818 body
819 ));
820 }
821 }
822 }
823 }
824
825 fn accept_edit_prediction(
826 &mut self,
827 request_id: InlineCompletionId,
828 cx: &mut Context<Self>,
829 ) -> Task<Result<()>> {
830 let client = self.client.clone();
831 let llm_token = self.llm_token.clone();
832 let app_version = AppVersion::global(cx);
833 cx.spawn(async move |this, cx| {
834 let http_client = client.http_client();
835 let mut response = llm_token_retry(&llm_token, &client, |token| {
836 let request_builder = http_client::Request::builder().method(Method::POST);
837 let request_builder =
838 if let Ok(accept_prediction_url) = std::env::var("ZED_ACCEPT_PREDICTION_URL") {
839 request_builder.uri(accept_prediction_url)
840 } else {
841 request_builder.uri(
842 http_client
843 .build_zed_llm_url("/predict_edits/accept", &[])?
844 .as_ref(),
845 )
846 };
847 Ok(request_builder
848 .header("Content-Type", "application/json")
849 .header("Authorization", format!("Bearer {}", token))
850 .header(ZED_VERSION_HEADER_NAME, app_version.to_string())
851 .body(
852 serde_json::to_string(&AcceptEditPredictionBody {
853 request_id: request_id.0,
854 })?
855 .into(),
856 )?)
857 })
858 .await?;
859
860 if let Some(minimum_required_version) = response
861 .headers()
862 .get(MINIMUM_REQUIRED_VERSION_HEADER_NAME)
863 .and_then(|version| SemanticVersion::from_str(version.to_str().ok()?).ok())
864 {
865 if app_version < minimum_required_version {
866 return Err(anyhow!(ZedUpdateRequiredError {
867 minimum_version: minimum_required_version
868 }));
869 }
870 }
871
872 if response.status().is_success() {
873 if let Some(usage) = EditPredictionUsage::from_headers(response.headers()).ok() {
874 this.update(cx, |this, cx| {
875 this.last_usage = Some(usage);
876 cx.notify();
877 })?;
878 }
879
880 Ok(())
881 } else {
882 let mut body = String::new();
883 response.body_mut().read_to_string(&mut body).await?;
884 Err(anyhow!(
885 "error accepting edit prediction.\nStatus: {:?}\nBody: {}",
886 response.status(),
887 body
888 ))
889 }
890 })
891 }
892
893 fn process_completion_response(
894 prediction_response: PredictEditsResponse,
895 buffer: Entity<Buffer>,
896 snapshot: &BufferSnapshot,
897 editable_range: Range<usize>,
898 cursor_offset: usize,
899 path: Arc<Path>,
900 input_outline: String,
901 input_events: String,
902 input_excerpt: String,
903 request_sent_at: Instant,
904 cx: &AsyncApp,
905 ) -> Task<Result<Option<InlineCompletion>>> {
906 let snapshot = snapshot.clone();
907 let request_id = prediction_response.request_id;
908 let output_excerpt = prediction_response.output_excerpt;
909 cx.spawn(async move |cx| {
910 let output_excerpt: Arc<str> = output_excerpt.into();
911
912 let edits: Arc<[(Range<Anchor>, String)]> = cx
913 .background_spawn({
914 let output_excerpt = output_excerpt.clone();
915 let editable_range = editable_range.clone();
916 let snapshot = snapshot.clone();
917 async move { Self::parse_edits(output_excerpt, editable_range, &snapshot) }
918 })
919 .await?
920 .into();
921
922 let Some((edits, snapshot, edit_preview)) = buffer.read_with(cx, {
923 let edits = edits.clone();
924 |buffer, cx| {
925 let new_snapshot = buffer.snapshot();
926 let edits: Arc<[(Range<Anchor>, String)]> =
927 interpolate(&snapshot, &new_snapshot, edits)?.into();
928 Some((edits.clone(), new_snapshot, buffer.preview_edits(edits, cx)))
929 }
930 })?
931 else {
932 return anyhow::Ok(None);
933 };
934
935 let edit_preview = edit_preview.await;
936
937 Ok(Some(InlineCompletion {
938 id: InlineCompletionId(request_id),
939 path,
940 excerpt_range: editable_range,
941 cursor_offset,
942 edits,
943 edit_preview,
944 snapshot,
945 input_outline: input_outline.into(),
946 input_events: input_events.into(),
947 input_excerpt: input_excerpt.into(),
948 output_excerpt,
949 request_sent_at,
950 response_received_at: Instant::now(),
951 }))
952 })
953 }
954
955 fn parse_edits(
956 output_excerpt: Arc<str>,
957 editable_range: Range<usize>,
958 snapshot: &BufferSnapshot,
959 ) -> Result<Vec<(Range<Anchor>, String)>> {
960 let content = output_excerpt.replace(CURSOR_MARKER, "");
961
962 let start_markers = content
963 .match_indices(EDITABLE_REGION_START_MARKER)
964 .collect::<Vec<_>>();
965 anyhow::ensure!(
966 start_markers.len() == 1,
967 "expected exactly one start marker, found {}",
968 start_markers.len()
969 );
970
971 let end_markers = content
972 .match_indices(EDITABLE_REGION_END_MARKER)
973 .collect::<Vec<_>>();
974 anyhow::ensure!(
975 end_markers.len() == 1,
976 "expected exactly one end marker, found {}",
977 end_markers.len()
978 );
979
980 let sof_markers = content
981 .match_indices(START_OF_FILE_MARKER)
982 .collect::<Vec<_>>();
983 anyhow::ensure!(
984 sof_markers.len() <= 1,
985 "expected at most one start-of-file marker, found {}",
986 sof_markers.len()
987 );
988
989 let codefence_start = start_markers[0].0;
990 let content = &content[codefence_start..];
991
992 let newline_ix = content.find('\n').context("could not find newline")?;
993 let content = &content[newline_ix + 1..];
994
995 let codefence_end = content
996 .rfind(&format!("\n{EDITABLE_REGION_END_MARKER}"))
997 .context("could not find end marker")?;
998 let new_text = &content[..codefence_end];
999
1000 let old_text = snapshot
1001 .text_for_range(editable_range.clone())
1002 .collect::<String>();
1003
1004 Ok(Self::compute_edits(
1005 old_text,
1006 new_text,
1007 editable_range.start,
1008 &snapshot,
1009 ))
1010 }
1011
1012 pub fn compute_edits(
1013 old_text: String,
1014 new_text: &str,
1015 offset: usize,
1016 snapshot: &BufferSnapshot,
1017 ) -> Vec<(Range<Anchor>, String)> {
1018 text_diff(&old_text, &new_text)
1019 .into_iter()
1020 .map(|(mut old_range, new_text)| {
1021 old_range.start += offset;
1022 old_range.end += offset;
1023
1024 let prefix_len = common_prefix(
1025 snapshot.chars_for_range(old_range.clone()),
1026 new_text.chars(),
1027 );
1028 old_range.start += prefix_len;
1029
1030 let suffix_len = common_prefix(
1031 snapshot.reversed_chars_for_range(old_range.clone()),
1032 new_text[prefix_len..].chars().rev(),
1033 );
1034 old_range.end = old_range.end.saturating_sub(suffix_len);
1035
1036 let new_text = new_text[prefix_len..new_text.len() - suffix_len].to_string();
1037 let range = if old_range.is_empty() {
1038 let anchor = snapshot.anchor_after(old_range.start);
1039 anchor..anchor
1040 } else {
1041 snapshot.anchor_after(old_range.start)..snapshot.anchor_before(old_range.end)
1042 };
1043 (range, new_text)
1044 })
1045 .collect()
1046 }
1047
1048 pub fn is_completion_rated(&self, completion_id: InlineCompletionId) -> bool {
1049 self.rated_completions.contains(&completion_id)
1050 }
1051
1052 pub fn completion_shown(&mut self, completion: &InlineCompletion, cx: &mut Context<Self>) {
1053 self.shown_completions.push_front(completion.clone());
1054 if self.shown_completions.len() > 50 {
1055 let completion = self.shown_completions.pop_back().unwrap();
1056 self.rated_completions.remove(&completion.id);
1057 }
1058 cx.notify();
1059 }
1060
1061 pub fn rate_completion(
1062 &mut self,
1063 completion: &InlineCompletion,
1064 rating: InlineCompletionRating,
1065 feedback: String,
1066 cx: &mut Context<Self>,
1067 ) {
1068 self.rated_completions.insert(completion.id);
1069 telemetry::event!(
1070 "Edit Prediction Rated",
1071 rating,
1072 input_events = completion.input_events,
1073 input_excerpt = completion.input_excerpt,
1074 input_outline = completion.input_outline,
1075 output_excerpt = completion.output_excerpt,
1076 feedback
1077 );
1078 self.client.telemetry().flush_events().detach();
1079 cx.notify();
1080 }
1081
1082 pub fn shown_completions(&self) -> impl DoubleEndedIterator<Item = &InlineCompletion> {
1083 self.shown_completions.iter()
1084 }
1085
1086 pub fn shown_completions_len(&self) -> usize {
1087 self.shown_completions.len()
1088 }
1089
1090 fn report_changes_for_buffer(
1091 &mut self,
1092 buffer: &Entity<Buffer>,
1093 cx: &mut Context<Self>,
1094 ) -> BufferSnapshot {
1095 self.register_buffer(buffer, cx);
1096
1097 let registered_buffer = self
1098 .registered_buffers
1099 .get_mut(&buffer.entity_id())
1100 .unwrap();
1101 let new_snapshot = buffer.read(cx).snapshot();
1102
1103 if new_snapshot.version != registered_buffer.snapshot.version {
1104 let old_snapshot = mem::replace(&mut registered_buffer.snapshot, new_snapshot.clone());
1105 self.push_event(Event::BufferChange {
1106 old_snapshot,
1107 new_snapshot: new_snapshot.clone(),
1108 timestamp: Instant::now(),
1109 });
1110 }
1111
1112 new_snapshot
1113 }
1114
1115 fn load_data_collection_choices() -> DataCollectionChoice {
1116 let choice = KEY_VALUE_STORE
1117 .read_kvp(ZED_PREDICT_DATA_COLLECTION_CHOICE)
1118 .log_err()
1119 .flatten();
1120
1121 match choice.as_deref() {
1122 Some("true") => DataCollectionChoice::Enabled,
1123 Some("false") => DataCollectionChoice::Disabled,
1124 Some(_) => {
1125 log::error!("unknown value in '{ZED_PREDICT_DATA_COLLECTION_CHOICE}'");
1126 DataCollectionChoice::NotAnswered
1127 }
1128 None => DataCollectionChoice::NotAnswered,
1129 }
1130 }
1131}
1132
1133struct PerformPredictEditsParams {
1134 pub client: Arc<Client>,
1135 pub llm_token: LlmApiToken,
1136 pub app_version: SemanticVersion,
1137 pub body: PredictEditsBody,
1138}
1139
1140#[derive(Error, Debug)]
1141#[error(
1142 "You must update to Zed version {minimum_version} or higher to continue using edit predictions."
1143)]
1144pub struct ZedUpdateRequiredError {
1145 minimum_version: SemanticVersion,
1146}
1147
1148struct LicenseDetectionWatcher {
1149 is_open_source_rx: watch::Receiver<bool>,
1150 _is_open_source_task: Task<()>,
1151}
1152
1153impl LicenseDetectionWatcher {
1154 pub fn new(worktree: &Worktree, cx: &mut Context<Worktree>) -> Self {
1155 let (mut is_open_source_tx, is_open_source_rx) = watch::channel_with::<bool>(false);
1156
1157 // Check if worktree is a single file, if so we do not need to check for a LICENSE file
1158 let task = if worktree.abs_path().is_file() {
1159 Task::ready(())
1160 } else {
1161 let loaded_files = LICENSE_FILES_TO_CHECK
1162 .iter()
1163 .map(Path::new)
1164 .map(|file| worktree.load_file(file, cx))
1165 .collect::<ArrayVec<_, { LICENSE_FILES_TO_CHECK.len() }>>();
1166
1167 cx.background_spawn(async move {
1168 for loaded_file in loaded_files.into_iter() {
1169 let Ok(loaded_file) = loaded_file.await else {
1170 continue;
1171 };
1172
1173 let path = &loaded_file.file.path;
1174 if is_license_eligible_for_data_collection(&loaded_file.text) {
1175 log::info!("detected '{path:?}' as open source license");
1176 *is_open_source_tx.borrow_mut() = true;
1177 } else {
1178 log::info!("didn't detect '{path:?}' as open source license");
1179 }
1180
1181 // stop on the first license that successfully read
1182 return;
1183 }
1184
1185 log::debug!("didn't find a license file to check, assuming closed source");
1186 })
1187 };
1188
1189 Self {
1190 is_open_source_rx,
1191 _is_open_source_task: task,
1192 }
1193 }
1194
1195 /// Answers false until we find out it's open source
1196 pub fn is_project_open_source(&self) -> bool {
1197 *self.is_open_source_rx.borrow()
1198 }
1199}
1200
1201fn common_prefix<T1: Iterator<Item = char>, T2: Iterator<Item = char>>(a: T1, b: T2) -> usize {
1202 a.zip(b)
1203 .take_while(|(a, b)| a == b)
1204 .map(|(a, _)| a.len_utf8())
1205 .sum()
1206}
1207
1208fn prompt_for_outline(snapshot: &BufferSnapshot) -> String {
1209 let mut input_outline = String::new();
1210
1211 writeln!(
1212 input_outline,
1213 "```{}",
1214 snapshot
1215 .file()
1216 .map_or(Cow::Borrowed("untitled"), |file| file
1217 .path()
1218 .to_string_lossy())
1219 )
1220 .unwrap();
1221
1222 if let Some(outline) = snapshot.outline(None) {
1223 for item in &outline.items {
1224 let spacing = " ".repeat(item.depth);
1225 writeln!(input_outline, "{}{}", spacing, item.text).unwrap();
1226 }
1227 }
1228
1229 writeln!(input_outline, "```").unwrap();
1230
1231 input_outline
1232}
1233
1234fn prompt_for_events(events: &VecDeque<Event>, mut remaining_tokens: usize) -> String {
1235 let mut result = String::new();
1236 for event in events.iter().rev() {
1237 let event_string = event.to_prompt();
1238 let event_tokens = tokens_for_bytes(event_string.len());
1239 if event_tokens > remaining_tokens {
1240 break;
1241 }
1242
1243 if !result.is_empty() {
1244 result.insert_str(0, "\n\n");
1245 }
1246 result.insert_str(0, &event_string);
1247 remaining_tokens -= event_tokens;
1248 }
1249 result
1250}
1251
1252struct RegisteredBuffer {
1253 snapshot: BufferSnapshot,
1254 _subscriptions: [gpui::Subscription; 2],
1255}
1256
1257#[derive(Clone)]
1258enum Event {
1259 BufferChange {
1260 old_snapshot: BufferSnapshot,
1261 new_snapshot: BufferSnapshot,
1262 timestamp: Instant,
1263 },
1264}
1265
1266impl Event {
1267 fn to_prompt(&self) -> String {
1268 match self {
1269 Event::BufferChange {
1270 old_snapshot,
1271 new_snapshot,
1272 ..
1273 } => {
1274 let mut prompt = String::new();
1275
1276 let old_path = old_snapshot
1277 .file()
1278 .map(|f| f.path().as_ref())
1279 .unwrap_or(Path::new("untitled"));
1280 let new_path = new_snapshot
1281 .file()
1282 .map(|f| f.path().as_ref())
1283 .unwrap_or(Path::new("untitled"));
1284 if old_path != new_path {
1285 writeln!(prompt, "User renamed {:?} to {:?}\n", old_path, new_path).unwrap();
1286 }
1287
1288 let diff = language::unified_diff(&old_snapshot.text(), &new_snapshot.text());
1289 if !diff.is_empty() {
1290 write!(
1291 prompt,
1292 "User edited {:?}:\n```diff\n{}\n```",
1293 new_path, diff
1294 )
1295 .unwrap();
1296 }
1297
1298 prompt
1299 }
1300 }
1301 }
1302}
1303
1304#[derive(Debug, Clone)]
1305struct CurrentInlineCompletion {
1306 buffer_id: EntityId,
1307 completion: InlineCompletion,
1308}
1309
1310impl CurrentInlineCompletion {
1311 fn should_replace_completion(&self, old_completion: &Self, snapshot: &BufferSnapshot) -> bool {
1312 if self.buffer_id != old_completion.buffer_id {
1313 return true;
1314 }
1315
1316 let Some(old_edits) = old_completion.completion.interpolate(&snapshot) else {
1317 return true;
1318 };
1319 let Some(new_edits) = self.completion.interpolate(&snapshot) else {
1320 return false;
1321 };
1322
1323 if old_edits.len() == 1 && new_edits.len() == 1 {
1324 let (old_range, old_text) = &old_edits[0];
1325 let (new_range, new_text) = &new_edits[0];
1326 new_range == old_range && new_text.starts_with(old_text)
1327 } else {
1328 true
1329 }
1330 }
1331}
1332
1333struct PendingCompletion {
1334 id: usize,
1335 _task: Task<()>,
1336}
1337
1338#[derive(Debug, Clone, Copy)]
1339pub enum DataCollectionChoice {
1340 NotAnswered,
1341 Enabled,
1342 Disabled,
1343}
1344
1345impl DataCollectionChoice {
1346 pub fn is_enabled(self) -> bool {
1347 match self {
1348 Self::Enabled => true,
1349 Self::NotAnswered | Self::Disabled => false,
1350 }
1351 }
1352
1353 pub fn is_answered(self) -> bool {
1354 match self {
1355 Self::Enabled | Self::Disabled => true,
1356 Self::NotAnswered => false,
1357 }
1358 }
1359
1360 pub fn toggle(&self) -> DataCollectionChoice {
1361 match self {
1362 Self::Enabled => Self::Disabled,
1363 Self::Disabled => Self::Enabled,
1364 Self::NotAnswered => Self::Enabled,
1365 }
1366 }
1367}
1368
1369impl From<bool> for DataCollectionChoice {
1370 fn from(value: bool) -> Self {
1371 match value {
1372 true => DataCollectionChoice::Enabled,
1373 false => DataCollectionChoice::Disabled,
1374 }
1375 }
1376}
1377
1378pub struct ProviderDataCollection {
1379 /// When set to None, data collection is not possible in the provider buffer
1380 choice: Option<Entity<DataCollectionChoice>>,
1381 license_detection_watcher: Option<Rc<LicenseDetectionWatcher>>,
1382}
1383
1384impl ProviderDataCollection {
1385 pub fn new(zeta: Entity<Zeta>, buffer: Option<Entity<Buffer>>, cx: &mut App) -> Self {
1386 let choice_and_watcher = buffer.and_then(|buffer| {
1387 let file = buffer.read(cx).file()?;
1388
1389 if !file.is_local() || file.is_private() {
1390 return None;
1391 }
1392
1393 let zeta = zeta.read(cx);
1394 let choice = zeta.data_collection_choice.clone();
1395
1396 let license_detection_watcher = zeta
1397 .license_detection_watchers
1398 .get(&file.worktree_id(cx))
1399 .cloned()?;
1400
1401 Some((choice, license_detection_watcher))
1402 });
1403
1404 if let Some((choice, watcher)) = choice_and_watcher {
1405 ProviderDataCollection {
1406 choice: Some(choice),
1407 license_detection_watcher: Some(watcher),
1408 }
1409 } else {
1410 ProviderDataCollection {
1411 choice: None,
1412 license_detection_watcher: None,
1413 }
1414 }
1415 }
1416
1417 pub fn can_collect_data(&self, cx: &App) -> bool {
1418 self.is_data_collection_enabled(cx) && self.is_project_open_source()
1419 }
1420
1421 pub fn is_data_collection_enabled(&self, cx: &App) -> bool {
1422 self.choice
1423 .as_ref()
1424 .is_some_and(|choice| choice.read(cx).is_enabled())
1425 }
1426
1427 fn is_project_open_source(&self) -> bool {
1428 self.license_detection_watcher
1429 .as_ref()
1430 .is_some_and(|watcher| watcher.is_project_open_source())
1431 }
1432
1433 pub fn toggle(&mut self, cx: &mut App) {
1434 if let Some(choice) = self.choice.as_mut() {
1435 let new_choice = choice.update(cx, |choice, _cx| {
1436 let new_choice = choice.toggle();
1437 *choice = new_choice;
1438 new_choice
1439 });
1440
1441 db::write_and_log(cx, move || {
1442 KEY_VALUE_STORE.write_kvp(
1443 ZED_PREDICT_DATA_COLLECTION_CHOICE.into(),
1444 new_choice.is_enabled().to_string(),
1445 )
1446 });
1447 }
1448 }
1449}
1450
1451async fn llm_token_retry(
1452 llm_token: &LlmApiToken,
1453 client: &Arc<Client>,
1454 build_request: impl Fn(String) -> Result<Request<AsyncBody>>,
1455) -> Result<Response<AsyncBody>> {
1456 let mut did_retry = false;
1457 let http_client = client.http_client();
1458 let mut token = llm_token.acquire(client).await?;
1459 loop {
1460 let request = build_request(token.clone())?;
1461 let response = http_client.send(request).await?;
1462
1463 if !did_retry
1464 && !response.status().is_success()
1465 && response
1466 .headers()
1467 .get(EXPIRED_LLM_TOKEN_HEADER_NAME)
1468 .is_some()
1469 {
1470 did_retry = true;
1471 token = llm_token.refresh(client).await?;
1472 continue;
1473 }
1474
1475 return Ok(response);
1476 }
1477}
1478
1479pub struct ZetaInlineCompletionProvider {
1480 zeta: Entity<Zeta>,
1481 pending_completions: ArrayVec<PendingCompletion, 2>,
1482 next_pending_completion_id: usize,
1483 current_completion: Option<CurrentInlineCompletion>,
1484 /// None if this is entirely disabled for this provider
1485 provider_data_collection: ProviderDataCollection,
1486 last_request_timestamp: Instant,
1487}
1488
1489impl ZetaInlineCompletionProvider {
1490 pub const THROTTLE_TIMEOUT: Duration = Duration::from_millis(300);
1491
1492 pub fn new(zeta: Entity<Zeta>, provider_data_collection: ProviderDataCollection) -> Self {
1493 Self {
1494 zeta,
1495 pending_completions: ArrayVec::new(),
1496 next_pending_completion_id: 0,
1497 current_completion: None,
1498 provider_data_collection,
1499 last_request_timestamp: Instant::now(),
1500 }
1501 }
1502}
1503
1504impl inline_completion::EditPredictionProvider for ZetaInlineCompletionProvider {
1505 fn name() -> &'static str {
1506 "zed-predict"
1507 }
1508
1509 fn display_name() -> &'static str {
1510 "Zed's Edit Predictions"
1511 }
1512
1513 fn show_completions_in_menu() -> bool {
1514 true
1515 }
1516
1517 fn show_tab_accept_marker() -> bool {
1518 true
1519 }
1520
1521 fn data_collection_state(&self, cx: &App) -> DataCollectionState {
1522 let is_project_open_source = self.provider_data_collection.is_project_open_source();
1523
1524 if self.provider_data_collection.is_data_collection_enabled(cx) {
1525 DataCollectionState::Enabled {
1526 is_project_open_source,
1527 }
1528 } else {
1529 DataCollectionState::Disabled {
1530 is_project_open_source,
1531 }
1532 }
1533 }
1534
1535 fn toggle_data_collection(&mut self, cx: &mut App) {
1536 self.provider_data_collection.toggle(cx);
1537 }
1538
1539 fn usage(&self, cx: &App) -> Option<EditPredictionUsage> {
1540 self.zeta.read(cx).usage(cx)
1541 }
1542
1543 fn is_enabled(
1544 &self,
1545 _buffer: &Entity<Buffer>,
1546 _cursor_position: language::Anchor,
1547 _cx: &App,
1548 ) -> bool {
1549 true
1550 }
1551
1552 fn needs_terms_acceptance(&self, cx: &App) -> bool {
1553 !self.zeta.read(cx).tos_accepted
1554 }
1555
1556 fn is_refreshing(&self) -> bool {
1557 !self.pending_completions.is_empty()
1558 }
1559
1560 fn refresh(
1561 &mut self,
1562 project: Option<Entity<Project>>,
1563 buffer: Entity<Buffer>,
1564 position: language::Anchor,
1565 _debounce: bool,
1566 cx: &mut Context<Self>,
1567 ) {
1568 if !self.zeta.read(cx).tos_accepted {
1569 return;
1570 }
1571
1572 if self.zeta.read(cx).update_required {
1573 return;
1574 }
1575
1576 if let Some(current_completion) = self.current_completion.as_ref() {
1577 let snapshot = buffer.read(cx).snapshot();
1578 if current_completion
1579 .completion
1580 .interpolate(&snapshot)
1581 .is_some()
1582 {
1583 return;
1584 }
1585 }
1586
1587 let pending_completion_id = self.next_pending_completion_id;
1588 self.next_pending_completion_id += 1;
1589 let can_collect_data = self.provider_data_collection.can_collect_data(cx);
1590 let last_request_timestamp = self.last_request_timestamp;
1591
1592 let task = cx.spawn(async move |this, cx| {
1593 if let Some(timeout) = (last_request_timestamp + Self::THROTTLE_TIMEOUT)
1594 .checked_duration_since(Instant::now())
1595 {
1596 cx.background_executor().timer(timeout).await;
1597 }
1598
1599 let completion_request = this.update(cx, |this, cx| {
1600 this.last_request_timestamp = Instant::now();
1601 this.zeta.update(cx, |zeta, cx| {
1602 zeta.request_completion(
1603 project.as_ref(),
1604 &buffer,
1605 position,
1606 can_collect_data,
1607 cx,
1608 )
1609 })
1610 });
1611
1612 let completion = match completion_request {
1613 Ok(completion_request) => {
1614 let completion_request = completion_request.await;
1615 completion_request.map(|c| {
1616 c.map(|completion| CurrentInlineCompletion {
1617 buffer_id: buffer.entity_id(),
1618 completion,
1619 })
1620 })
1621 }
1622 Err(error) => Err(error),
1623 };
1624 let Some(new_completion) = completion
1625 .context("edit prediction failed")
1626 .log_err()
1627 .flatten()
1628 else {
1629 this.update(cx, |this, cx| {
1630 if this.pending_completions[0].id == pending_completion_id {
1631 this.pending_completions.remove(0);
1632 } else {
1633 this.pending_completions.clear();
1634 }
1635
1636 cx.notify();
1637 })
1638 .ok();
1639 return;
1640 };
1641
1642 this.update(cx, |this, cx| {
1643 if this.pending_completions[0].id == pending_completion_id {
1644 this.pending_completions.remove(0);
1645 } else {
1646 this.pending_completions.clear();
1647 }
1648
1649 if let Some(old_completion) = this.current_completion.as_ref() {
1650 let snapshot = buffer.read(cx).snapshot();
1651 if new_completion.should_replace_completion(&old_completion, &snapshot) {
1652 this.zeta.update(cx, |zeta, cx| {
1653 zeta.completion_shown(&new_completion.completion, cx);
1654 });
1655 this.current_completion = Some(new_completion);
1656 }
1657 } else {
1658 this.zeta.update(cx, |zeta, cx| {
1659 zeta.completion_shown(&new_completion.completion, cx);
1660 });
1661 this.current_completion = Some(new_completion);
1662 }
1663
1664 cx.notify();
1665 })
1666 .ok();
1667 });
1668
1669 // We always maintain at most two pending completions. When we already
1670 // have two, we replace the newest one.
1671 if self.pending_completions.len() <= 1 {
1672 self.pending_completions.push(PendingCompletion {
1673 id: pending_completion_id,
1674 _task: task,
1675 });
1676 } else if self.pending_completions.len() == 2 {
1677 self.pending_completions.pop();
1678 self.pending_completions.push(PendingCompletion {
1679 id: pending_completion_id,
1680 _task: task,
1681 });
1682 }
1683 }
1684
1685 fn cycle(
1686 &mut self,
1687 _buffer: Entity<Buffer>,
1688 _cursor_position: language::Anchor,
1689 _direction: inline_completion::Direction,
1690 _cx: &mut Context<Self>,
1691 ) {
1692 // Right now we don't support cycling.
1693 }
1694
1695 fn accept(&mut self, cx: &mut Context<Self>) {
1696 let completion_id = self
1697 .current_completion
1698 .as_ref()
1699 .map(|completion| completion.completion.id);
1700 if let Some(completion_id) = completion_id {
1701 self.zeta
1702 .update(cx, |zeta, cx| {
1703 zeta.accept_edit_prediction(completion_id, cx)
1704 })
1705 .detach();
1706 }
1707 self.pending_completions.clear();
1708 }
1709
1710 fn discard(&mut self, _cx: &mut Context<Self>) {
1711 self.pending_completions.clear();
1712 self.current_completion.take();
1713 }
1714
1715 fn suggest(
1716 &mut self,
1717 buffer: &Entity<Buffer>,
1718 cursor_position: language::Anchor,
1719 cx: &mut Context<Self>,
1720 ) -> Option<inline_completion::InlineCompletion> {
1721 let CurrentInlineCompletion {
1722 buffer_id,
1723 completion,
1724 ..
1725 } = self.current_completion.as_mut()?;
1726
1727 // Invalidate previous completion if it was generated for a different buffer.
1728 if *buffer_id != buffer.entity_id() {
1729 self.current_completion.take();
1730 return None;
1731 }
1732
1733 let buffer = buffer.read(cx);
1734 let Some(edits) = completion.interpolate(&buffer.snapshot()) else {
1735 self.current_completion.take();
1736 return None;
1737 };
1738
1739 let cursor_row = cursor_position.to_point(buffer).row;
1740 let (closest_edit_ix, (closest_edit_range, _)) =
1741 edits.iter().enumerate().min_by_key(|(_, (range, _))| {
1742 let distance_from_start = cursor_row.abs_diff(range.start.to_point(buffer).row);
1743 let distance_from_end = cursor_row.abs_diff(range.end.to_point(buffer).row);
1744 cmp::min(distance_from_start, distance_from_end)
1745 })?;
1746
1747 let mut edit_start_ix = closest_edit_ix;
1748 for (range, _) in edits[..edit_start_ix].iter().rev() {
1749 let distance_from_closest_edit =
1750 closest_edit_range.start.to_point(buffer).row - range.end.to_point(buffer).row;
1751 if distance_from_closest_edit <= 1 {
1752 edit_start_ix -= 1;
1753 } else {
1754 break;
1755 }
1756 }
1757
1758 let mut edit_end_ix = closest_edit_ix + 1;
1759 for (range, _) in &edits[edit_end_ix..] {
1760 let distance_from_closest_edit =
1761 range.start.to_point(buffer).row - closest_edit_range.end.to_point(buffer).row;
1762 if distance_from_closest_edit <= 1 {
1763 edit_end_ix += 1;
1764 } else {
1765 break;
1766 }
1767 }
1768
1769 Some(inline_completion::InlineCompletion {
1770 id: Some(completion.id.to_string().into()),
1771 edits: edits[edit_start_ix..edit_end_ix].to_vec(),
1772 edit_preview: Some(completion.edit_preview.clone()),
1773 })
1774 }
1775}
1776
1777fn tokens_for_bytes(bytes: usize) -> usize {
1778 /// Typical number of string bytes per token for the purposes of limiting model input. This is
1779 /// intentionally low to err on the side of underestimating limits.
1780 const BYTES_PER_TOKEN_GUESS: usize = 3;
1781 bytes / BYTES_PER_TOKEN_GUESS
1782}
1783
1784#[cfg(test)]
1785mod tests {
1786 use client::test::FakeServer;
1787 use clock::FakeSystemClock;
1788 use gpui::TestAppContext;
1789 use http_client::FakeHttpClient;
1790 use indoc::indoc;
1791 use language::Point;
1792 use rpc::proto;
1793 use settings::SettingsStore;
1794
1795 use super::*;
1796
1797 #[gpui::test]
1798 async fn test_inline_completion_basic_interpolation(cx: &mut TestAppContext) {
1799 let buffer = cx.new(|cx| Buffer::local("Lorem ipsum dolor", cx));
1800 let edits: Arc<[(Range<Anchor>, String)]> = cx.update(|cx| {
1801 to_completion_edits(
1802 [(2..5, "REM".to_string()), (9..11, "".to_string())],
1803 &buffer,
1804 cx,
1805 )
1806 .into()
1807 });
1808
1809 let edit_preview = cx
1810 .read(|cx| buffer.read(cx).preview_edits(edits.clone(), cx))
1811 .await;
1812
1813 let completion = InlineCompletion {
1814 edits,
1815 edit_preview,
1816 path: Path::new("").into(),
1817 snapshot: cx.read(|cx| buffer.read(cx).snapshot()),
1818 id: InlineCompletionId(Uuid::new_v4()),
1819 excerpt_range: 0..0,
1820 cursor_offset: 0,
1821 input_outline: "".into(),
1822 input_events: "".into(),
1823 input_excerpt: "".into(),
1824 output_excerpt: "".into(),
1825 request_sent_at: Instant::now(),
1826 response_received_at: Instant::now(),
1827 };
1828
1829 cx.update(|cx| {
1830 assert_eq!(
1831 from_completion_edits(
1832 &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
1833 &buffer,
1834 cx
1835 ),
1836 vec![(2..5, "REM".to_string()), (9..11, "".to_string())]
1837 );
1838
1839 buffer.update(cx, |buffer, cx| buffer.edit([(2..5, "")], None, cx));
1840 assert_eq!(
1841 from_completion_edits(
1842 &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
1843 &buffer,
1844 cx
1845 ),
1846 vec![(2..2, "REM".to_string()), (6..8, "".to_string())]
1847 );
1848
1849 buffer.update(cx, |buffer, cx| buffer.undo(cx));
1850 assert_eq!(
1851 from_completion_edits(
1852 &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
1853 &buffer,
1854 cx
1855 ),
1856 vec![(2..5, "REM".to_string()), (9..11, "".to_string())]
1857 );
1858
1859 buffer.update(cx, |buffer, cx| buffer.edit([(2..5, "R")], None, cx));
1860 assert_eq!(
1861 from_completion_edits(
1862 &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
1863 &buffer,
1864 cx
1865 ),
1866 vec![(3..3, "EM".to_string()), (7..9, "".to_string())]
1867 );
1868
1869 buffer.update(cx, |buffer, cx| buffer.edit([(3..3, "E")], None, cx));
1870 assert_eq!(
1871 from_completion_edits(
1872 &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
1873 &buffer,
1874 cx
1875 ),
1876 vec![(4..4, "M".to_string()), (8..10, "".to_string())]
1877 );
1878
1879 buffer.update(cx, |buffer, cx| buffer.edit([(4..4, "M")], None, cx));
1880 assert_eq!(
1881 from_completion_edits(
1882 &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
1883 &buffer,
1884 cx
1885 ),
1886 vec![(9..11, "".to_string())]
1887 );
1888
1889 buffer.update(cx, |buffer, cx| buffer.edit([(4..5, "")], None, cx));
1890 assert_eq!(
1891 from_completion_edits(
1892 &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
1893 &buffer,
1894 cx
1895 ),
1896 vec![(4..4, "M".to_string()), (8..10, "".to_string())]
1897 );
1898
1899 buffer.update(cx, |buffer, cx| buffer.edit([(8..10, "")], None, cx));
1900 assert_eq!(
1901 from_completion_edits(
1902 &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
1903 &buffer,
1904 cx
1905 ),
1906 vec![(4..4, "M".to_string())]
1907 );
1908
1909 buffer.update(cx, |buffer, cx| buffer.edit([(4..6, "")], None, cx));
1910 assert_eq!(completion.interpolate(&buffer.read(cx).snapshot()), None);
1911 })
1912 }
1913
1914 #[gpui::test]
1915 async fn test_clean_up_diff(cx: &mut TestAppContext) {
1916 cx.update(|cx| {
1917 let settings_store = SettingsStore::test(cx);
1918 cx.set_global(settings_store);
1919 client::init_settings(cx);
1920 });
1921
1922 let edits = edits_for_prediction(
1923 indoc! {"
1924 fn main() {
1925 let word_1 = \"lorem\";
1926 let range = word.len()..word.len();
1927 }
1928 "},
1929 indoc! {"
1930 <|editable_region_start|>
1931 fn main() {
1932 let word_1 = \"lorem\";
1933 let range = word_1.len()..word_1.len();
1934 }
1935
1936 <|editable_region_end|>
1937 "},
1938 cx,
1939 )
1940 .await;
1941 assert_eq!(
1942 edits,
1943 [
1944 (Point::new(2, 20)..Point::new(2, 20), "_1".to_string()),
1945 (Point::new(2, 32)..Point::new(2, 32), "_1".to_string()),
1946 ]
1947 );
1948
1949 let edits = edits_for_prediction(
1950 indoc! {"
1951 fn main() {
1952 let story = \"the quick\"
1953 }
1954 "},
1955 indoc! {"
1956 <|editable_region_start|>
1957 fn main() {
1958 let story = \"the quick brown fox jumps over the lazy dog\";
1959 }
1960
1961 <|editable_region_end|>
1962 "},
1963 cx,
1964 )
1965 .await;
1966 assert_eq!(
1967 edits,
1968 [
1969 (
1970 Point::new(1, 26)..Point::new(1, 26),
1971 " brown fox jumps over the lazy dog".to_string()
1972 ),
1973 (Point::new(1, 27)..Point::new(1, 27), ";".to_string()),
1974 ]
1975 );
1976 }
1977
1978 #[gpui::test]
1979 async fn test_inline_completion_end_of_buffer(cx: &mut TestAppContext) {
1980 cx.update(|cx| {
1981 let settings_store = SettingsStore::test(cx);
1982 cx.set_global(settings_store);
1983 client::init_settings(cx);
1984 });
1985
1986 let buffer_content = "lorem\n";
1987 let completion_response = indoc! {"
1988 ```animals.js
1989 <|start_of_file|>
1990 <|editable_region_start|>
1991 lorem
1992 ipsum
1993 <|editable_region_end|>
1994 ```"};
1995
1996 let http_client = FakeHttpClient::create(move |_| async move {
1997 Ok(http_client::Response::builder()
1998 .status(200)
1999 .body(
2000 serde_json::to_string(&PredictEditsResponse {
2001 request_id: Uuid::parse_str("7e86480f-3536-4d2c-9334-8213e3445d45")
2002 .unwrap(),
2003 output_excerpt: completion_response.to_string(),
2004 })
2005 .unwrap()
2006 .into(),
2007 )
2008 .unwrap())
2009 });
2010
2011 let client = cx.update(|cx| Client::new(Arc::new(FakeSystemClock::new()), http_client, cx));
2012 cx.update(|cx| {
2013 RefreshLlmTokenListener::register(client.clone(), cx);
2014 });
2015 let server = FakeServer::for_client(42, &client, cx).await;
2016 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
2017 let zeta = cx.new(|cx| Zeta::new(None, client, user_store, cx));
2018
2019 let buffer = cx.new(|cx| Buffer::local(buffer_content, cx));
2020 let cursor = buffer.read_with(cx, |buffer, _| buffer.anchor_before(Point::new(1, 0)));
2021 let completion_task = zeta.update(cx, |zeta, cx| {
2022 zeta.request_completion(None, &buffer, cursor, false, cx)
2023 });
2024
2025 server.receive::<proto::GetUsers>().await.unwrap();
2026 let token_request = server.receive::<proto::GetLlmToken>().await.unwrap();
2027 server.respond(
2028 token_request.receipt(),
2029 proto::GetLlmTokenResponse { token: "".into() },
2030 );
2031
2032 let completion = completion_task.await.unwrap().unwrap();
2033 buffer.update(cx, |buffer, cx| {
2034 buffer.edit(completion.edits.iter().cloned(), None, cx)
2035 });
2036 assert_eq!(
2037 buffer.read_with(cx, |buffer, _| buffer.text()),
2038 "lorem\nipsum"
2039 );
2040 }
2041
2042 async fn edits_for_prediction(
2043 buffer_content: &str,
2044 completion_response: &str,
2045 cx: &mut TestAppContext,
2046 ) -> Vec<(Range<Point>, String)> {
2047 let completion_response = completion_response.to_string();
2048 let http_client = FakeHttpClient::create(move |_| {
2049 let completion = completion_response.clone();
2050 async move {
2051 Ok(http_client::Response::builder()
2052 .status(200)
2053 .body(
2054 serde_json::to_string(&PredictEditsResponse {
2055 request_id: Uuid::new_v4(),
2056 output_excerpt: completion,
2057 })
2058 .unwrap()
2059 .into(),
2060 )
2061 .unwrap())
2062 }
2063 });
2064
2065 let client = cx.update(|cx| Client::new(Arc::new(FakeSystemClock::new()), http_client, cx));
2066 cx.update(|cx| {
2067 RefreshLlmTokenListener::register(client.clone(), cx);
2068 });
2069 let server = FakeServer::for_client(42, &client, cx).await;
2070 let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
2071 let zeta = cx.new(|cx| Zeta::new(None, client, user_store, cx));
2072
2073 let buffer = cx.new(|cx| Buffer::local(buffer_content, cx));
2074 let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot());
2075 let cursor = buffer.read_with(cx, |buffer, _| buffer.anchor_before(Point::new(1, 0)));
2076 let completion_task = zeta.update(cx, |zeta, cx| {
2077 zeta.request_completion(None, &buffer, cursor, false, cx)
2078 });
2079
2080 server.receive::<proto::GetUsers>().await.unwrap();
2081 let token_request = server.receive::<proto::GetLlmToken>().await.unwrap();
2082 server.respond(
2083 token_request.receipt(),
2084 proto::GetLlmTokenResponse { token: "".into() },
2085 );
2086
2087 let completion = completion_task.await.unwrap().unwrap();
2088 completion
2089 .edits
2090 .into_iter()
2091 .map(|(old_range, new_text)| (old_range.to_point(&snapshot), new_text.clone()))
2092 .collect::<Vec<_>>()
2093 }
2094
2095 fn to_completion_edits(
2096 iterator: impl IntoIterator<Item = (Range<usize>, String)>,
2097 buffer: &Entity<Buffer>,
2098 cx: &App,
2099 ) -> Vec<(Range<Anchor>, String)> {
2100 let buffer = buffer.read(cx);
2101 iterator
2102 .into_iter()
2103 .map(|(range, text)| {
2104 (
2105 buffer.anchor_after(range.start)..buffer.anchor_before(range.end),
2106 text,
2107 )
2108 })
2109 .collect()
2110 }
2111
2112 fn from_completion_edits(
2113 editor_edits: &[(Range<Anchor>, String)],
2114 buffer: &Entity<Buffer>,
2115 cx: &App,
2116 ) -> Vec<(Range<usize>, String)> {
2117 let buffer = buffer.read(cx);
2118 editor_edits
2119 .iter()
2120 .map(|(range, text)| {
2121 (
2122 range.start.to_offset(buffer)..range.end.to_offset(buffer),
2123 text.clone(),
2124 )
2125 })
2126 .collect()
2127 }
2128
2129 #[ctor::ctor]
2130 fn init_logger() {
2131 if std::env::var("RUST_LOG").is_ok() {
2132 env_logger::init();
2133 }
2134 }
2135}