zeta.rs

   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::{HttpClient, Method};
  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    EXPIRED_LLM_TOKEN_HEADER_NAME, MINIMUM_REQUIRED_VERSION_HEADER_NAME, PredictEditsBody,
  58    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 process_completion_response(
 826        prediction_response: PredictEditsResponse,
 827        buffer: Entity<Buffer>,
 828        snapshot: &BufferSnapshot,
 829        editable_range: Range<usize>,
 830        cursor_offset: usize,
 831        path: Arc<Path>,
 832        input_outline: String,
 833        input_events: String,
 834        input_excerpt: String,
 835        request_sent_at: Instant,
 836        cx: &AsyncApp,
 837    ) -> Task<Result<Option<InlineCompletion>>> {
 838        let snapshot = snapshot.clone();
 839        let request_id = prediction_response.request_id;
 840        let output_excerpt = prediction_response.output_excerpt;
 841        cx.spawn(async move |cx| {
 842            let output_excerpt: Arc<str> = output_excerpt.into();
 843
 844            let edits: Arc<[(Range<Anchor>, String)]> = cx
 845                .background_spawn({
 846                    let output_excerpt = output_excerpt.clone();
 847                    let editable_range = editable_range.clone();
 848                    let snapshot = snapshot.clone();
 849                    async move { Self::parse_edits(output_excerpt, editable_range, &snapshot) }
 850                })
 851                .await?
 852                .into();
 853
 854            let Some((edits, snapshot, edit_preview)) = buffer.read_with(cx, {
 855                let edits = edits.clone();
 856                |buffer, cx| {
 857                    let new_snapshot = buffer.snapshot();
 858                    let edits: Arc<[(Range<Anchor>, String)]> =
 859                        interpolate(&snapshot, &new_snapshot, edits)?.into();
 860                    Some((edits.clone(), new_snapshot, buffer.preview_edits(edits, cx)))
 861                }
 862            })?
 863            else {
 864                return anyhow::Ok(None);
 865            };
 866
 867            let edit_preview = edit_preview.await;
 868
 869            Ok(Some(InlineCompletion {
 870                id: InlineCompletionId(request_id),
 871                path,
 872                excerpt_range: editable_range,
 873                cursor_offset,
 874                edits,
 875                edit_preview,
 876                snapshot,
 877                input_outline: input_outline.into(),
 878                input_events: input_events.into(),
 879                input_excerpt: input_excerpt.into(),
 880                output_excerpt,
 881                request_sent_at,
 882                response_received_at: Instant::now(),
 883            }))
 884        })
 885    }
 886
 887    fn parse_edits(
 888        output_excerpt: Arc<str>,
 889        editable_range: Range<usize>,
 890        snapshot: &BufferSnapshot,
 891    ) -> Result<Vec<(Range<Anchor>, String)>> {
 892        let content = output_excerpt.replace(CURSOR_MARKER, "");
 893
 894        let start_markers = content
 895            .match_indices(EDITABLE_REGION_START_MARKER)
 896            .collect::<Vec<_>>();
 897        anyhow::ensure!(
 898            start_markers.len() == 1,
 899            "expected exactly one start marker, found {}",
 900            start_markers.len()
 901        );
 902
 903        let end_markers = content
 904            .match_indices(EDITABLE_REGION_END_MARKER)
 905            .collect::<Vec<_>>();
 906        anyhow::ensure!(
 907            end_markers.len() == 1,
 908            "expected exactly one end marker, found {}",
 909            end_markers.len()
 910        );
 911
 912        let sof_markers = content
 913            .match_indices(START_OF_FILE_MARKER)
 914            .collect::<Vec<_>>();
 915        anyhow::ensure!(
 916            sof_markers.len() <= 1,
 917            "expected at most one start-of-file marker, found {}",
 918            sof_markers.len()
 919        );
 920
 921        let codefence_start = start_markers[0].0;
 922        let content = &content[codefence_start..];
 923
 924        let newline_ix = content.find('\n').context("could not find newline")?;
 925        let content = &content[newline_ix + 1..];
 926
 927        let codefence_end = content
 928            .rfind(&format!("\n{EDITABLE_REGION_END_MARKER}"))
 929            .context("could not find end marker")?;
 930        let new_text = &content[..codefence_end];
 931
 932        let old_text = snapshot
 933            .text_for_range(editable_range.clone())
 934            .collect::<String>();
 935
 936        Ok(Self::compute_edits(
 937            old_text,
 938            new_text,
 939            editable_range.start,
 940            &snapshot,
 941        ))
 942    }
 943
 944    pub fn compute_edits(
 945        old_text: String,
 946        new_text: &str,
 947        offset: usize,
 948        snapshot: &BufferSnapshot,
 949    ) -> Vec<(Range<Anchor>, String)> {
 950        text_diff(&old_text, &new_text)
 951            .into_iter()
 952            .map(|(mut old_range, new_text)| {
 953                old_range.start += offset;
 954                old_range.end += offset;
 955
 956                let prefix_len = common_prefix(
 957                    snapshot.chars_for_range(old_range.clone()),
 958                    new_text.chars(),
 959                );
 960                old_range.start += prefix_len;
 961
 962                let suffix_len = common_prefix(
 963                    snapshot.reversed_chars_for_range(old_range.clone()),
 964                    new_text[prefix_len..].chars().rev(),
 965                );
 966                old_range.end = old_range.end.saturating_sub(suffix_len);
 967
 968                let new_text = new_text[prefix_len..new_text.len() - suffix_len].to_string();
 969                let range = if old_range.is_empty() {
 970                    let anchor = snapshot.anchor_after(old_range.start);
 971                    anchor..anchor
 972                } else {
 973                    snapshot.anchor_after(old_range.start)..snapshot.anchor_before(old_range.end)
 974                };
 975                (range, new_text)
 976            })
 977            .collect()
 978    }
 979
 980    pub fn is_completion_rated(&self, completion_id: InlineCompletionId) -> bool {
 981        self.rated_completions.contains(&completion_id)
 982    }
 983
 984    pub fn completion_shown(&mut self, completion: &InlineCompletion, cx: &mut Context<Self>) {
 985        self.shown_completions.push_front(completion.clone());
 986        if self.shown_completions.len() > 50 {
 987            let completion = self.shown_completions.pop_back().unwrap();
 988            self.rated_completions.remove(&completion.id);
 989        }
 990        cx.notify();
 991    }
 992
 993    pub fn rate_completion(
 994        &mut self,
 995        completion: &InlineCompletion,
 996        rating: InlineCompletionRating,
 997        feedback: String,
 998        cx: &mut Context<Self>,
 999    ) {
1000        self.rated_completions.insert(completion.id);
1001        telemetry::event!(
1002            "Edit Prediction Rated",
1003            rating,
1004            input_events = completion.input_events,
1005            input_excerpt = completion.input_excerpt,
1006            input_outline = completion.input_outline,
1007            output_excerpt = completion.output_excerpt,
1008            feedback
1009        );
1010        self.client.telemetry().flush_events().detach();
1011        cx.notify();
1012    }
1013
1014    pub fn shown_completions(&self) -> impl DoubleEndedIterator<Item = &InlineCompletion> {
1015        self.shown_completions.iter()
1016    }
1017
1018    pub fn shown_completions_len(&self) -> usize {
1019        self.shown_completions.len()
1020    }
1021
1022    fn report_changes_for_buffer(
1023        &mut self,
1024        buffer: &Entity<Buffer>,
1025        cx: &mut Context<Self>,
1026    ) -> BufferSnapshot {
1027        self.register_buffer(buffer, cx);
1028
1029        let registered_buffer = self
1030            .registered_buffers
1031            .get_mut(&buffer.entity_id())
1032            .unwrap();
1033        let new_snapshot = buffer.read(cx).snapshot();
1034
1035        if new_snapshot.version != registered_buffer.snapshot.version {
1036            let old_snapshot = mem::replace(&mut registered_buffer.snapshot, new_snapshot.clone());
1037            self.push_event(Event::BufferChange {
1038                old_snapshot,
1039                new_snapshot: new_snapshot.clone(),
1040                timestamp: Instant::now(),
1041            });
1042        }
1043
1044        new_snapshot
1045    }
1046
1047    fn load_data_collection_choices() -> DataCollectionChoice {
1048        let choice = KEY_VALUE_STORE
1049            .read_kvp(ZED_PREDICT_DATA_COLLECTION_CHOICE)
1050            .log_err()
1051            .flatten();
1052
1053        match choice.as_deref() {
1054            Some("true") => DataCollectionChoice::Enabled,
1055            Some("false") => DataCollectionChoice::Disabled,
1056            Some(_) => {
1057                log::error!("unknown value in '{ZED_PREDICT_DATA_COLLECTION_CHOICE}'");
1058                DataCollectionChoice::NotAnswered
1059            }
1060            None => DataCollectionChoice::NotAnswered,
1061        }
1062    }
1063}
1064
1065struct PerformPredictEditsParams {
1066    pub client: Arc<Client>,
1067    pub llm_token: LlmApiToken,
1068    pub app_version: SemanticVersion,
1069    pub body: PredictEditsBody,
1070}
1071
1072#[derive(Error, Debug)]
1073#[error(
1074    "You must update to Zed version {minimum_version} or higher to continue using edit predictions."
1075)]
1076pub struct ZedUpdateRequiredError {
1077    minimum_version: SemanticVersion,
1078}
1079
1080struct LicenseDetectionWatcher {
1081    is_open_source_rx: watch::Receiver<bool>,
1082    _is_open_source_task: Task<()>,
1083}
1084
1085impl LicenseDetectionWatcher {
1086    pub fn new(worktree: &Worktree, cx: &mut Context<Worktree>) -> Self {
1087        let (mut is_open_source_tx, is_open_source_rx) = watch::channel_with::<bool>(false);
1088
1089        // Check if worktree is a single file, if so we do not need to check for a LICENSE file
1090        let task = if worktree.abs_path().is_file() {
1091            Task::ready(())
1092        } else {
1093            let loaded_files = LICENSE_FILES_TO_CHECK
1094                .iter()
1095                .map(Path::new)
1096                .map(|file| worktree.load_file(file, cx))
1097                .collect::<ArrayVec<_, { LICENSE_FILES_TO_CHECK.len() }>>();
1098
1099            cx.background_spawn(async move {
1100                for loaded_file in loaded_files.into_iter() {
1101                    let Ok(loaded_file) = loaded_file.await else {
1102                        continue;
1103                    };
1104
1105                    let path = &loaded_file.file.path;
1106                    if is_license_eligible_for_data_collection(&loaded_file.text) {
1107                        log::info!("detected '{path:?}' as open source license");
1108                        *is_open_source_tx.borrow_mut() = true;
1109                    } else {
1110                        log::info!("didn't detect '{path:?}' as open source license");
1111                    }
1112
1113                    // stop on the first license that successfully read
1114                    return;
1115                }
1116
1117                log::debug!("didn't find a license file to check, assuming closed source");
1118            })
1119        };
1120
1121        Self {
1122            is_open_source_rx,
1123            _is_open_source_task: task,
1124        }
1125    }
1126
1127    /// Answers false until we find out it's open source
1128    pub fn is_project_open_source(&self) -> bool {
1129        *self.is_open_source_rx.borrow()
1130    }
1131}
1132
1133fn common_prefix<T1: Iterator<Item = char>, T2: Iterator<Item = char>>(a: T1, b: T2) -> usize {
1134    a.zip(b)
1135        .take_while(|(a, b)| a == b)
1136        .map(|(a, _)| a.len_utf8())
1137        .sum()
1138}
1139
1140fn prompt_for_outline(snapshot: &BufferSnapshot) -> String {
1141    let mut input_outline = String::new();
1142
1143    writeln!(
1144        input_outline,
1145        "```{}",
1146        snapshot
1147            .file()
1148            .map_or(Cow::Borrowed("untitled"), |file| file
1149                .path()
1150                .to_string_lossy())
1151    )
1152    .unwrap();
1153
1154    if let Some(outline) = snapshot.outline(None) {
1155        for item in &outline.items {
1156            let spacing = " ".repeat(item.depth);
1157            writeln!(input_outline, "{}{}", spacing, item.text).unwrap();
1158        }
1159    }
1160
1161    writeln!(input_outline, "```").unwrap();
1162
1163    input_outline
1164}
1165
1166fn prompt_for_events(events: &VecDeque<Event>, mut remaining_tokens: usize) -> String {
1167    let mut result = String::new();
1168    for event in events.iter().rev() {
1169        let event_string = event.to_prompt();
1170        let event_tokens = tokens_for_bytes(event_string.len());
1171        if event_tokens > remaining_tokens {
1172            break;
1173        }
1174
1175        if !result.is_empty() {
1176            result.insert_str(0, "\n\n");
1177        }
1178        result.insert_str(0, &event_string);
1179        remaining_tokens -= event_tokens;
1180    }
1181    result
1182}
1183
1184struct RegisteredBuffer {
1185    snapshot: BufferSnapshot,
1186    _subscriptions: [gpui::Subscription; 2],
1187}
1188
1189#[derive(Clone)]
1190enum Event {
1191    BufferChange {
1192        old_snapshot: BufferSnapshot,
1193        new_snapshot: BufferSnapshot,
1194        timestamp: Instant,
1195    },
1196}
1197
1198impl Event {
1199    fn to_prompt(&self) -> String {
1200        match self {
1201            Event::BufferChange {
1202                old_snapshot,
1203                new_snapshot,
1204                ..
1205            } => {
1206                let mut prompt = String::new();
1207
1208                let old_path = old_snapshot
1209                    .file()
1210                    .map(|f| f.path().as_ref())
1211                    .unwrap_or(Path::new("untitled"));
1212                let new_path = new_snapshot
1213                    .file()
1214                    .map(|f| f.path().as_ref())
1215                    .unwrap_or(Path::new("untitled"));
1216                if old_path != new_path {
1217                    writeln!(prompt, "User renamed {:?} to {:?}\n", old_path, new_path).unwrap();
1218                }
1219
1220                let diff = language::unified_diff(&old_snapshot.text(), &new_snapshot.text());
1221                if !diff.is_empty() {
1222                    write!(
1223                        prompt,
1224                        "User edited {:?}:\n```diff\n{}\n```",
1225                        new_path, diff
1226                    )
1227                    .unwrap();
1228                }
1229
1230                prompt
1231            }
1232        }
1233    }
1234}
1235
1236#[derive(Debug, Clone)]
1237struct CurrentInlineCompletion {
1238    buffer_id: EntityId,
1239    completion: InlineCompletion,
1240}
1241
1242impl CurrentInlineCompletion {
1243    fn should_replace_completion(&self, old_completion: &Self, snapshot: &BufferSnapshot) -> bool {
1244        if self.buffer_id != old_completion.buffer_id {
1245            return true;
1246        }
1247
1248        let Some(old_edits) = old_completion.completion.interpolate(&snapshot) else {
1249            return true;
1250        };
1251        let Some(new_edits) = self.completion.interpolate(&snapshot) else {
1252            return false;
1253        };
1254
1255        if old_edits.len() == 1 && new_edits.len() == 1 {
1256            let (old_range, old_text) = &old_edits[0];
1257            let (new_range, new_text) = &new_edits[0];
1258            new_range == old_range && new_text.starts_with(old_text)
1259        } else {
1260            true
1261        }
1262    }
1263}
1264
1265struct PendingCompletion {
1266    id: usize,
1267    _task: Task<()>,
1268}
1269
1270#[derive(Debug, Clone, Copy)]
1271pub enum DataCollectionChoice {
1272    NotAnswered,
1273    Enabled,
1274    Disabled,
1275}
1276
1277impl DataCollectionChoice {
1278    pub fn is_enabled(self) -> bool {
1279        match self {
1280            Self::Enabled => true,
1281            Self::NotAnswered | Self::Disabled => false,
1282        }
1283    }
1284
1285    pub fn is_answered(self) -> bool {
1286        match self {
1287            Self::Enabled | Self::Disabled => true,
1288            Self::NotAnswered => false,
1289        }
1290    }
1291
1292    pub fn toggle(&self) -> DataCollectionChoice {
1293        match self {
1294            Self::Enabled => Self::Disabled,
1295            Self::Disabled => Self::Enabled,
1296            Self::NotAnswered => Self::Enabled,
1297        }
1298    }
1299}
1300
1301impl From<bool> for DataCollectionChoice {
1302    fn from(value: bool) -> Self {
1303        match value {
1304            true => DataCollectionChoice::Enabled,
1305            false => DataCollectionChoice::Disabled,
1306        }
1307    }
1308}
1309
1310pub struct ProviderDataCollection {
1311    /// When set to None, data collection is not possible in the provider buffer
1312    choice: Option<Entity<DataCollectionChoice>>,
1313    license_detection_watcher: Option<Rc<LicenseDetectionWatcher>>,
1314}
1315
1316impl ProviderDataCollection {
1317    pub fn new(zeta: Entity<Zeta>, buffer: Option<Entity<Buffer>>, cx: &mut App) -> Self {
1318        let choice_and_watcher = buffer.and_then(|buffer| {
1319            let file = buffer.read(cx).file()?;
1320
1321            if !file.is_local() || file.is_private() {
1322                return None;
1323            }
1324
1325            let zeta = zeta.read(cx);
1326            let choice = zeta.data_collection_choice.clone();
1327
1328            let license_detection_watcher = zeta
1329                .license_detection_watchers
1330                .get(&file.worktree_id(cx))
1331                .cloned()?;
1332
1333            Some((choice, license_detection_watcher))
1334        });
1335
1336        if let Some((choice, watcher)) = choice_and_watcher {
1337            ProviderDataCollection {
1338                choice: Some(choice),
1339                license_detection_watcher: Some(watcher),
1340            }
1341        } else {
1342            ProviderDataCollection {
1343                choice: None,
1344                license_detection_watcher: None,
1345            }
1346        }
1347    }
1348
1349    pub fn can_collect_data(&self, cx: &App) -> bool {
1350        self.is_data_collection_enabled(cx) && self.is_project_open_source()
1351    }
1352
1353    pub fn is_data_collection_enabled(&self, cx: &App) -> bool {
1354        self.choice
1355            .as_ref()
1356            .is_some_and(|choice| choice.read(cx).is_enabled())
1357    }
1358
1359    fn is_project_open_source(&self) -> bool {
1360        self.license_detection_watcher
1361            .as_ref()
1362            .is_some_and(|watcher| watcher.is_project_open_source())
1363    }
1364
1365    pub fn toggle(&mut self, cx: &mut App) {
1366        if let Some(choice) = self.choice.as_mut() {
1367            let new_choice = choice.update(cx, |choice, _cx| {
1368                let new_choice = choice.toggle();
1369                *choice = new_choice;
1370                new_choice
1371            });
1372
1373            db::write_and_log(cx, move || {
1374                KEY_VALUE_STORE.write_kvp(
1375                    ZED_PREDICT_DATA_COLLECTION_CHOICE.into(),
1376                    new_choice.is_enabled().to_string(),
1377                )
1378            });
1379        }
1380    }
1381}
1382
1383pub struct ZetaInlineCompletionProvider {
1384    zeta: Entity<Zeta>,
1385    pending_completions: ArrayVec<PendingCompletion, 2>,
1386    next_pending_completion_id: usize,
1387    current_completion: Option<CurrentInlineCompletion>,
1388    /// None if this is entirely disabled for this provider
1389    provider_data_collection: ProviderDataCollection,
1390    last_request_timestamp: Instant,
1391}
1392
1393impl ZetaInlineCompletionProvider {
1394    pub const THROTTLE_TIMEOUT: Duration = Duration::from_millis(300);
1395
1396    pub fn new(zeta: Entity<Zeta>, provider_data_collection: ProviderDataCollection) -> Self {
1397        Self {
1398            zeta,
1399            pending_completions: ArrayVec::new(),
1400            next_pending_completion_id: 0,
1401            current_completion: None,
1402            provider_data_collection,
1403            last_request_timestamp: Instant::now(),
1404        }
1405    }
1406}
1407
1408impl inline_completion::EditPredictionProvider for ZetaInlineCompletionProvider {
1409    fn name() -> &'static str {
1410        "zed-predict"
1411    }
1412
1413    fn display_name() -> &'static str {
1414        "Zed's Edit Predictions"
1415    }
1416
1417    fn show_completions_in_menu() -> bool {
1418        true
1419    }
1420
1421    fn show_tab_accept_marker() -> bool {
1422        true
1423    }
1424
1425    fn data_collection_state(&self, cx: &App) -> DataCollectionState {
1426        let is_project_open_source = self.provider_data_collection.is_project_open_source();
1427
1428        if self.provider_data_collection.is_data_collection_enabled(cx) {
1429            DataCollectionState::Enabled {
1430                is_project_open_source,
1431            }
1432        } else {
1433            DataCollectionState::Disabled {
1434                is_project_open_source,
1435            }
1436        }
1437    }
1438
1439    fn toggle_data_collection(&mut self, cx: &mut App) {
1440        self.provider_data_collection.toggle(cx);
1441    }
1442
1443    fn usage(&self, cx: &App) -> Option<EditPredictionUsage> {
1444        self.zeta.read(cx).usage(cx)
1445    }
1446
1447    fn is_enabled(
1448        &self,
1449        _buffer: &Entity<Buffer>,
1450        _cursor_position: language::Anchor,
1451        _cx: &App,
1452    ) -> bool {
1453        true
1454    }
1455
1456    fn needs_terms_acceptance(&self, cx: &App) -> bool {
1457        !self.zeta.read(cx).tos_accepted
1458    }
1459
1460    fn is_refreshing(&self) -> bool {
1461        !self.pending_completions.is_empty()
1462    }
1463
1464    fn refresh(
1465        &mut self,
1466        project: Option<Entity<Project>>,
1467        buffer: Entity<Buffer>,
1468        position: language::Anchor,
1469        _debounce: bool,
1470        cx: &mut Context<Self>,
1471    ) {
1472        if !self.zeta.read(cx).tos_accepted {
1473            return;
1474        }
1475
1476        if self.zeta.read(cx).update_required {
1477            return;
1478        }
1479
1480        if let Some(current_completion) = self.current_completion.as_ref() {
1481            let snapshot = buffer.read(cx).snapshot();
1482            if current_completion
1483                .completion
1484                .interpolate(&snapshot)
1485                .is_some()
1486            {
1487                return;
1488            }
1489        }
1490
1491        let pending_completion_id = self.next_pending_completion_id;
1492        self.next_pending_completion_id += 1;
1493        let can_collect_data = self.provider_data_collection.can_collect_data(cx);
1494        let last_request_timestamp = self.last_request_timestamp;
1495
1496        let task = cx.spawn(async move |this, cx| {
1497            if let Some(timeout) = (last_request_timestamp + Self::THROTTLE_TIMEOUT)
1498                .checked_duration_since(Instant::now())
1499            {
1500                cx.background_executor().timer(timeout).await;
1501            }
1502
1503            let completion_request = this.update(cx, |this, cx| {
1504                this.last_request_timestamp = Instant::now();
1505                this.zeta.update(cx, |zeta, cx| {
1506                    zeta.request_completion(
1507                        project.as_ref(),
1508                        &buffer,
1509                        position,
1510                        can_collect_data,
1511                        cx,
1512                    )
1513                })
1514            });
1515
1516            let completion = match completion_request {
1517                Ok(completion_request) => {
1518                    let completion_request = completion_request.await;
1519                    completion_request.map(|c| {
1520                        c.map(|completion| CurrentInlineCompletion {
1521                            buffer_id: buffer.entity_id(),
1522                            completion,
1523                        })
1524                    })
1525                }
1526                Err(error) => Err(error),
1527            };
1528            let Some(new_completion) = completion
1529                .context("edit prediction failed")
1530                .log_err()
1531                .flatten()
1532            else {
1533                this.update(cx, |this, cx| {
1534                    if this.pending_completions[0].id == pending_completion_id {
1535                        this.pending_completions.remove(0);
1536                    } else {
1537                        this.pending_completions.clear();
1538                    }
1539
1540                    cx.notify();
1541                })
1542                .ok();
1543                return;
1544            };
1545
1546            this.update(cx, |this, cx| {
1547                if this.pending_completions[0].id == pending_completion_id {
1548                    this.pending_completions.remove(0);
1549                } else {
1550                    this.pending_completions.clear();
1551                }
1552
1553                if let Some(old_completion) = this.current_completion.as_ref() {
1554                    let snapshot = buffer.read(cx).snapshot();
1555                    if new_completion.should_replace_completion(&old_completion, &snapshot) {
1556                        this.zeta.update(cx, |zeta, cx| {
1557                            zeta.completion_shown(&new_completion.completion, cx);
1558                        });
1559                        this.current_completion = Some(new_completion);
1560                    }
1561                } else {
1562                    this.zeta.update(cx, |zeta, cx| {
1563                        zeta.completion_shown(&new_completion.completion, cx);
1564                    });
1565                    this.current_completion = Some(new_completion);
1566                }
1567
1568                cx.notify();
1569            })
1570            .ok();
1571        });
1572
1573        // We always maintain at most two pending completions. When we already
1574        // have two, we replace the newest one.
1575        if self.pending_completions.len() <= 1 {
1576            self.pending_completions.push(PendingCompletion {
1577                id: pending_completion_id,
1578                _task: task,
1579            });
1580        } else if self.pending_completions.len() == 2 {
1581            self.pending_completions.pop();
1582            self.pending_completions.push(PendingCompletion {
1583                id: pending_completion_id,
1584                _task: task,
1585            });
1586        }
1587    }
1588
1589    fn cycle(
1590        &mut self,
1591        _buffer: Entity<Buffer>,
1592        _cursor_position: language::Anchor,
1593        _direction: inline_completion::Direction,
1594        _cx: &mut Context<Self>,
1595    ) {
1596        // Right now we don't support cycling.
1597    }
1598
1599    fn accept(&mut self, _cx: &mut Context<Self>) {
1600        self.pending_completions.clear();
1601    }
1602
1603    fn discard(&mut self, _cx: &mut Context<Self>) {
1604        self.pending_completions.clear();
1605        self.current_completion.take();
1606    }
1607
1608    fn suggest(
1609        &mut self,
1610        buffer: &Entity<Buffer>,
1611        cursor_position: language::Anchor,
1612        cx: &mut Context<Self>,
1613    ) -> Option<inline_completion::InlineCompletion> {
1614        let CurrentInlineCompletion {
1615            buffer_id,
1616            completion,
1617            ..
1618        } = self.current_completion.as_mut()?;
1619
1620        // Invalidate previous completion if it was generated for a different buffer.
1621        if *buffer_id != buffer.entity_id() {
1622            self.current_completion.take();
1623            return None;
1624        }
1625
1626        let buffer = buffer.read(cx);
1627        let Some(edits) = completion.interpolate(&buffer.snapshot()) else {
1628            self.current_completion.take();
1629            return None;
1630        };
1631
1632        let cursor_row = cursor_position.to_point(buffer).row;
1633        let (closest_edit_ix, (closest_edit_range, _)) =
1634            edits.iter().enumerate().min_by_key(|(_, (range, _))| {
1635                let distance_from_start = cursor_row.abs_diff(range.start.to_point(buffer).row);
1636                let distance_from_end = cursor_row.abs_diff(range.end.to_point(buffer).row);
1637                cmp::min(distance_from_start, distance_from_end)
1638            })?;
1639
1640        let mut edit_start_ix = closest_edit_ix;
1641        for (range, _) in edits[..edit_start_ix].iter().rev() {
1642            let distance_from_closest_edit =
1643                closest_edit_range.start.to_point(buffer).row - range.end.to_point(buffer).row;
1644            if distance_from_closest_edit <= 1 {
1645                edit_start_ix -= 1;
1646            } else {
1647                break;
1648            }
1649        }
1650
1651        let mut edit_end_ix = closest_edit_ix + 1;
1652        for (range, _) in &edits[edit_end_ix..] {
1653            let distance_from_closest_edit =
1654                range.start.to_point(buffer).row - closest_edit_range.end.to_point(buffer).row;
1655            if distance_from_closest_edit <= 1 {
1656                edit_end_ix += 1;
1657            } else {
1658                break;
1659            }
1660        }
1661
1662        Some(inline_completion::InlineCompletion {
1663            id: Some(completion.id.to_string().into()),
1664            edits: edits[edit_start_ix..edit_end_ix].to_vec(),
1665            edit_preview: Some(completion.edit_preview.clone()),
1666        })
1667    }
1668}
1669
1670fn tokens_for_bytes(bytes: usize) -> usize {
1671    /// Typical number of string bytes per token for the purposes of limiting model input. This is
1672    /// intentionally low to err on the side of underestimating limits.
1673    const BYTES_PER_TOKEN_GUESS: usize = 3;
1674    bytes / BYTES_PER_TOKEN_GUESS
1675}
1676
1677#[cfg(test)]
1678mod tests {
1679    use client::test::FakeServer;
1680    use clock::FakeSystemClock;
1681    use gpui::TestAppContext;
1682    use http_client::FakeHttpClient;
1683    use indoc::indoc;
1684    use language::Point;
1685    use rpc::proto;
1686    use settings::SettingsStore;
1687
1688    use super::*;
1689
1690    #[gpui::test]
1691    async fn test_inline_completion_basic_interpolation(cx: &mut TestAppContext) {
1692        let buffer = cx.new(|cx| Buffer::local("Lorem ipsum dolor", cx));
1693        let edits: Arc<[(Range<Anchor>, String)]> = cx.update(|cx| {
1694            to_completion_edits(
1695                [(2..5, "REM".to_string()), (9..11, "".to_string())],
1696                &buffer,
1697                cx,
1698            )
1699            .into()
1700        });
1701
1702        let edit_preview = cx
1703            .read(|cx| buffer.read(cx).preview_edits(edits.clone(), cx))
1704            .await;
1705
1706        let completion = InlineCompletion {
1707            edits,
1708            edit_preview,
1709            path: Path::new("").into(),
1710            snapshot: cx.read(|cx| buffer.read(cx).snapshot()),
1711            id: InlineCompletionId(Uuid::new_v4()),
1712            excerpt_range: 0..0,
1713            cursor_offset: 0,
1714            input_outline: "".into(),
1715            input_events: "".into(),
1716            input_excerpt: "".into(),
1717            output_excerpt: "".into(),
1718            request_sent_at: Instant::now(),
1719            response_received_at: Instant::now(),
1720        };
1721
1722        cx.update(|cx| {
1723            assert_eq!(
1724                from_completion_edits(
1725                    &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
1726                    &buffer,
1727                    cx
1728                ),
1729                vec![(2..5, "REM".to_string()), (9..11, "".to_string())]
1730            );
1731
1732            buffer.update(cx, |buffer, cx| buffer.edit([(2..5, "")], None, cx));
1733            assert_eq!(
1734                from_completion_edits(
1735                    &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
1736                    &buffer,
1737                    cx
1738                ),
1739                vec![(2..2, "REM".to_string()), (6..8, "".to_string())]
1740            );
1741
1742            buffer.update(cx, |buffer, cx| buffer.undo(cx));
1743            assert_eq!(
1744                from_completion_edits(
1745                    &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
1746                    &buffer,
1747                    cx
1748                ),
1749                vec![(2..5, "REM".to_string()), (9..11, "".to_string())]
1750            );
1751
1752            buffer.update(cx, |buffer, cx| buffer.edit([(2..5, "R")], None, cx));
1753            assert_eq!(
1754                from_completion_edits(
1755                    &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
1756                    &buffer,
1757                    cx
1758                ),
1759                vec![(3..3, "EM".to_string()), (7..9, "".to_string())]
1760            );
1761
1762            buffer.update(cx, |buffer, cx| buffer.edit([(3..3, "E")], None, cx));
1763            assert_eq!(
1764                from_completion_edits(
1765                    &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
1766                    &buffer,
1767                    cx
1768                ),
1769                vec![(4..4, "M".to_string()), (8..10, "".to_string())]
1770            );
1771
1772            buffer.update(cx, |buffer, cx| buffer.edit([(4..4, "M")], None, cx));
1773            assert_eq!(
1774                from_completion_edits(
1775                    &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
1776                    &buffer,
1777                    cx
1778                ),
1779                vec![(9..11, "".to_string())]
1780            );
1781
1782            buffer.update(cx, |buffer, cx| buffer.edit([(4..5, "")], None, cx));
1783            assert_eq!(
1784                from_completion_edits(
1785                    &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
1786                    &buffer,
1787                    cx
1788                ),
1789                vec![(4..4, "M".to_string()), (8..10, "".to_string())]
1790            );
1791
1792            buffer.update(cx, |buffer, cx| buffer.edit([(8..10, "")], None, cx));
1793            assert_eq!(
1794                from_completion_edits(
1795                    &completion.interpolate(&buffer.read(cx).snapshot()).unwrap(),
1796                    &buffer,
1797                    cx
1798                ),
1799                vec![(4..4, "M".to_string())]
1800            );
1801
1802            buffer.update(cx, |buffer, cx| buffer.edit([(4..6, "")], None, cx));
1803            assert_eq!(completion.interpolate(&buffer.read(cx).snapshot()), None);
1804        })
1805    }
1806
1807    #[gpui::test]
1808    async fn test_clean_up_diff(cx: &mut TestAppContext) {
1809        cx.update(|cx| {
1810            let settings_store = SettingsStore::test(cx);
1811            cx.set_global(settings_store);
1812            client::init_settings(cx);
1813        });
1814
1815        let edits = edits_for_prediction(
1816            indoc! {"
1817                fn main() {
1818                    let word_1 = \"lorem\";
1819                    let range = word.len()..word.len();
1820                }
1821            "},
1822            indoc! {"
1823                <|editable_region_start|>
1824                fn main() {
1825                    let word_1 = \"lorem\";
1826                    let range = word_1.len()..word_1.len();
1827                }
1828
1829                <|editable_region_end|>
1830            "},
1831            cx,
1832        )
1833        .await;
1834        assert_eq!(
1835            edits,
1836            [
1837                (Point::new(2, 20)..Point::new(2, 20), "_1".to_string()),
1838                (Point::new(2, 32)..Point::new(2, 32), "_1".to_string()),
1839            ]
1840        );
1841
1842        let edits = edits_for_prediction(
1843            indoc! {"
1844                fn main() {
1845                    let story = \"the quick\"
1846                }
1847            "},
1848            indoc! {"
1849                <|editable_region_start|>
1850                fn main() {
1851                    let story = \"the quick brown fox jumps over the lazy dog\";
1852                }
1853
1854                <|editable_region_end|>
1855            "},
1856            cx,
1857        )
1858        .await;
1859        assert_eq!(
1860            edits,
1861            [
1862                (
1863                    Point::new(1, 26)..Point::new(1, 26),
1864                    " brown fox jumps over the lazy dog".to_string()
1865                ),
1866                (Point::new(1, 27)..Point::new(1, 27), ";".to_string()),
1867            ]
1868        );
1869    }
1870
1871    #[gpui::test]
1872    async fn test_inline_completion_end_of_buffer(cx: &mut TestAppContext) {
1873        cx.update(|cx| {
1874            let settings_store = SettingsStore::test(cx);
1875            cx.set_global(settings_store);
1876            client::init_settings(cx);
1877        });
1878
1879        let buffer_content = "lorem\n";
1880        let completion_response = indoc! {"
1881            ```animals.js
1882            <|start_of_file|>
1883            <|editable_region_start|>
1884            lorem
1885            ipsum
1886            <|editable_region_end|>
1887            ```"};
1888
1889        let http_client = FakeHttpClient::create(move |_| async move {
1890            Ok(http_client::Response::builder()
1891                .status(200)
1892                .body(
1893                    serde_json::to_string(&PredictEditsResponse {
1894                        request_id: Uuid::parse_str("7e86480f-3536-4d2c-9334-8213e3445d45")
1895                            .unwrap(),
1896                        output_excerpt: completion_response.to_string(),
1897                    })
1898                    .unwrap()
1899                    .into(),
1900                )
1901                .unwrap())
1902        });
1903
1904        let client = cx.update(|cx| Client::new(Arc::new(FakeSystemClock::new()), http_client, cx));
1905        cx.update(|cx| {
1906            RefreshLlmTokenListener::register(client.clone(), cx);
1907        });
1908        let server = FakeServer::for_client(42, &client, cx).await;
1909        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1910        let zeta = cx.new(|cx| Zeta::new(None, client, user_store, cx));
1911
1912        let buffer = cx.new(|cx| Buffer::local(buffer_content, cx));
1913        let cursor = buffer.read_with(cx, |buffer, _| buffer.anchor_before(Point::new(1, 0)));
1914        let completion_task = zeta.update(cx, |zeta, cx| {
1915            zeta.request_completion(None, &buffer, cursor, false, cx)
1916        });
1917
1918        server.receive::<proto::GetUsers>().await.unwrap();
1919        let token_request = server.receive::<proto::GetLlmToken>().await.unwrap();
1920        server.respond(
1921            token_request.receipt(),
1922            proto::GetLlmTokenResponse { token: "".into() },
1923        );
1924
1925        let completion = completion_task.await.unwrap().unwrap();
1926        buffer.update(cx, |buffer, cx| {
1927            buffer.edit(completion.edits.iter().cloned(), None, cx)
1928        });
1929        assert_eq!(
1930            buffer.read_with(cx, |buffer, _| buffer.text()),
1931            "lorem\nipsum"
1932        );
1933    }
1934
1935    async fn edits_for_prediction(
1936        buffer_content: &str,
1937        completion_response: &str,
1938        cx: &mut TestAppContext,
1939    ) -> Vec<(Range<Point>, String)> {
1940        let completion_response = completion_response.to_string();
1941        let http_client = FakeHttpClient::create(move |_| {
1942            let completion = completion_response.clone();
1943            async move {
1944                Ok(http_client::Response::builder()
1945                    .status(200)
1946                    .body(
1947                        serde_json::to_string(&PredictEditsResponse {
1948                            request_id: Uuid::new_v4(),
1949                            output_excerpt: completion,
1950                        })
1951                        .unwrap()
1952                        .into(),
1953                    )
1954                    .unwrap())
1955            }
1956        });
1957
1958        let client = cx.update(|cx| Client::new(Arc::new(FakeSystemClock::new()), http_client, cx));
1959        cx.update(|cx| {
1960            RefreshLlmTokenListener::register(client.clone(), cx);
1961        });
1962        let server = FakeServer::for_client(42, &client, cx).await;
1963        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
1964        let zeta = cx.new(|cx| Zeta::new(None, client, user_store, cx));
1965
1966        let buffer = cx.new(|cx| Buffer::local(buffer_content, cx));
1967        let snapshot = buffer.read_with(cx, |buffer, _| buffer.snapshot());
1968        let cursor = buffer.read_with(cx, |buffer, _| buffer.anchor_before(Point::new(1, 0)));
1969        let completion_task = zeta.update(cx, |zeta, cx| {
1970            zeta.request_completion(None, &buffer, cursor, false, cx)
1971        });
1972
1973        server.receive::<proto::GetUsers>().await.unwrap();
1974        let token_request = server.receive::<proto::GetLlmToken>().await.unwrap();
1975        server.respond(
1976            token_request.receipt(),
1977            proto::GetLlmTokenResponse { token: "".into() },
1978        );
1979
1980        let completion = completion_task.await.unwrap().unwrap();
1981        completion
1982            .edits
1983            .into_iter()
1984            .map(|(old_range, new_text)| (old_range.to_point(&snapshot), new_text.clone()))
1985            .collect::<Vec<_>>()
1986    }
1987
1988    fn to_completion_edits(
1989        iterator: impl IntoIterator<Item = (Range<usize>, String)>,
1990        buffer: &Entity<Buffer>,
1991        cx: &App,
1992    ) -> Vec<(Range<Anchor>, String)> {
1993        let buffer = buffer.read(cx);
1994        iterator
1995            .into_iter()
1996            .map(|(range, text)| {
1997                (
1998                    buffer.anchor_after(range.start)..buffer.anchor_before(range.end),
1999                    text,
2000                )
2001            })
2002            .collect()
2003    }
2004
2005    fn from_completion_edits(
2006        editor_edits: &[(Range<Anchor>, String)],
2007        buffer: &Entity<Buffer>,
2008        cx: &App,
2009    ) -> Vec<(Range<usize>, String)> {
2010        let buffer = buffer.read(cx);
2011        editor_edits
2012            .iter()
2013            .map(|(range, text)| {
2014                (
2015                    range.start.to_offset(buffer)..range.end.to_offset(buffer),
2016                    text.clone(),
2017                )
2018            })
2019            .collect()
2020    }
2021
2022    #[ctor::ctor]
2023    fn init_logger() {
2024        if std::env::var("RUST_LOG").is_ok() {
2025            env_logger::init();
2026        }
2027    }
2028}