sweep_ai.rs

  1use crate::{
  2    CurrentEditPrediction, DebugEvent, EditPrediction, EditPredictionFinishedDebugEvent,
  3    EditPredictionId, EditPredictionModelInput, EditPredictionStartedDebugEvent,
  4    EditPredictionStore, UserActionRecord, UserActionType, prediction::EditPredictionResult,
  5};
  6use anyhow::{Result, bail};
  7use client::Client;
  8use edit_prediction_types::SuggestionDisplayType;
  9use futures::{AsyncReadExt as _, channel::mpsc};
 10use gpui::{
 11    App, AppContext as _, Entity, Global, SharedString, Task,
 12    http_client::{self, AsyncBody, Method},
 13};
 14use language::language_settings::all_language_settings;
 15use language::{Anchor, Buffer, BufferSnapshot, Point, ToOffset as _};
 16use language_model::{ApiKeyState, EnvVar, env_var};
 17use lsp::DiagnosticSeverity;
 18use serde::{Deserialize, Serialize};
 19use std::{
 20    fmt::{self, Write as _},
 21    ops::Range,
 22    path::Path,
 23    sync::Arc,
 24    time::Instant,
 25};
 26
 27const SWEEP_API_URL: &str = "https://autocomplete.sweep.dev/backend/next_edit_autocomplete";
 28const SWEEP_METRICS_URL: &str = "https://backend.app.sweep.dev/backend/track_autocomplete_metrics";
 29
 30pub struct SweepAi {
 31    pub api_token: Entity<ApiKeyState>,
 32    pub debug_info: Arc<str>,
 33}
 34
 35impl SweepAi {
 36    pub fn new(cx: &mut App) -> Self {
 37        SweepAi {
 38            api_token: sweep_api_token(cx),
 39            debug_info: debug_info(cx),
 40        }
 41    }
 42
 43    pub fn request_prediction_with_sweep(
 44        &self,
 45        inputs: EditPredictionModelInput,
 46        cx: &mut App,
 47    ) -> Task<Result<Option<EditPredictionResult>>> {
 48        let privacy_mode_enabled = all_language_settings(None, cx)
 49            .edit_predictions
 50            .sweep
 51            .privacy_mode;
 52        let debug_info = self.debug_info.clone();
 53        self.api_token.update(cx, |key_state, cx| {
 54            _ = key_state.load_if_needed(SWEEP_CREDENTIALS_URL, |s| s, cx);
 55        });
 56
 57        let buffer = inputs.buffer.clone();
 58        let debug_tx = inputs.debug_tx.clone();
 59
 60        let Some(api_token) = self.api_token.read(cx).key(&SWEEP_CREDENTIALS_URL) else {
 61            return Task::ready(Ok(None));
 62        };
 63        let full_path: Arc<Path> = inputs
 64            .snapshot
 65            .file()
 66            .map(|file| file.full_path(cx))
 67            .unwrap_or_else(|| "untitled".into())
 68            .into();
 69
 70        let project_file = project::File::from_dyn(inputs.snapshot.file());
 71        let repo_name = project_file
 72            .map(|file| file.worktree.read(cx).root_name_str())
 73            .unwrap_or("untitled")
 74            .into();
 75        let offset = inputs.position.to_offset(&inputs.snapshot);
 76        let buffer_entity_id = inputs.buffer.entity_id();
 77
 78        let recent_buffers = inputs.recent_paths.iter().cloned();
 79        let http_client = cx.http_client();
 80
 81        let recent_buffer_snapshots = recent_buffers
 82            .filter_map(|project_path| {
 83                let buffer = inputs.project.read(cx).get_open_buffer(&project_path, cx)?;
 84                if inputs.buffer == buffer {
 85                    None
 86                } else {
 87                    Some(buffer.read(cx).snapshot())
 88                }
 89            })
 90            .take(3)
 91            .collect::<Vec<_>>();
 92
 93        let buffer_snapshotted_at = Instant::now();
 94
 95        let result = cx.background_spawn(async move {
 96            let text = inputs.snapshot.text();
 97
 98            let mut recent_changes = String::new();
 99            for event in &inputs.events {
100                write_event(event.as_ref(), &mut recent_changes).unwrap();
101            }
102
103            let file_chunks = recent_buffer_snapshots
104                .into_iter()
105                .map(|snapshot| {
106                    let end_point = Point::new(30, 0).min(snapshot.max_point());
107                    FileChunk {
108                        content: snapshot.text_for_range(Point::zero()..end_point).collect(),
109                        file_path: snapshot
110                            .file()
111                            .map(|f| f.path().as_unix_str())
112                            .unwrap_or("untitled")
113                            .to_string(),
114                        start_line: 0,
115                        end_line: end_point.row as usize,
116                        timestamp: snapshot.file().and_then(|file| {
117                            Some(
118                                file.disk_state()
119                                    .mtime()?
120                                    .to_seconds_and_nanos_for_persistence()?
121                                    .0,
122                            )
123                        }),
124                    }
125                })
126                .collect::<Vec<_>>();
127
128            let mut retrieval_chunks: Vec<FileChunk> = inputs
129                .related_files
130                .iter()
131                .flat_map(|related_file| {
132                    related_file.excerpts.iter().map(|excerpt| FileChunk {
133                        file_path: related_file.path.to_string_lossy().to_string(),
134                        start_line: excerpt.row_range.start as usize,
135                        end_line: excerpt.row_range.end as usize,
136                        content: excerpt.text.to_string(),
137                        timestamp: None,
138                    })
139                })
140                .collect();
141
142            let diagnostic_entries = inputs
143                .snapshot
144                .diagnostics_in_range(inputs.diagnostic_search_range, false);
145            let mut diagnostic_content = String::new();
146            let mut diagnostic_count = 0;
147
148            for entry in diagnostic_entries {
149                let start_point: Point = entry.range.start;
150
151                let severity = match entry.diagnostic.severity {
152                    DiagnosticSeverity::ERROR => "error",
153                    DiagnosticSeverity::WARNING => "warning",
154                    DiagnosticSeverity::INFORMATION => "info",
155                    DiagnosticSeverity::HINT => "hint",
156                    _ => continue,
157                };
158
159                diagnostic_count += 1;
160
161                writeln!(
162                    &mut diagnostic_content,
163                    "{}:{}:{}: {}: {}",
164                    full_path.display(),
165                    start_point.row + 1,
166                    start_point.column + 1,
167                    severity,
168                    entry.diagnostic.message
169                )?;
170            }
171
172            if !diagnostic_content.is_empty() {
173                retrieval_chunks.push(FileChunk {
174                    file_path: "diagnostics".to_string(),
175                    start_line: 1,
176                    end_line: diagnostic_count,
177                    content: diagnostic_content,
178                    timestamp: None,
179                });
180            }
181
182            let file_path_str = full_path.display().to_string();
183            let recent_user_actions = inputs
184                .user_actions
185                .iter()
186                .filter(|r| r.buffer_id == buffer_entity_id)
187                .map(|r| to_sweep_user_action(r, &file_path_str))
188                .collect();
189
190            let request_body = AutocompleteRequest {
191                debug_info,
192                repo_name,
193                file_path: full_path.clone(),
194                file_contents: text.clone(),
195                original_file_contents: text,
196                cursor_position: offset,
197                recent_changes: recent_changes.clone(),
198                changes_above_cursor: true,
199                multiple_suggestions: false,
200                branch: None,
201                file_chunks,
202                retrieval_chunks,
203                recent_user_actions,
204                use_bytes: true,
205                privacy_mode_enabled,
206            };
207
208            let mut buf: Vec<u8> = Vec::new();
209            let writer = brotli::CompressorWriter::new(&mut buf, 4096, 1, 22);
210            serde_json::to_writer(writer, &request_body)?;
211            let body: AsyncBody = buf.into();
212
213            let ep_inputs = zeta_prompt::ZetaPromptInput {
214                events: inputs.events,
215                related_files: inputs.related_files.clone(),
216                cursor_path: full_path.clone(),
217                cursor_excerpt: request_body.file_contents.clone().into(),
218                // we actually don't know
219                editable_range_in_excerpt: 0..inputs.snapshot.len(),
220                cursor_offset_in_excerpt: request_body.cursor_position,
221                excerpt_start_row: Some(0),
222            };
223
224            send_started_event(
225                &debug_tx,
226                &buffer,
227                inputs.position,
228                serde_json::to_string(&request_body).unwrap_or_default(),
229            );
230
231            let request = http_client::Request::builder()
232                .uri(SWEEP_API_URL)
233                .header("Content-Type", "application/json")
234                .header("Authorization", format!("Bearer {}", api_token))
235                .header("Connection", "keep-alive")
236                .header("Content-Encoding", "br")
237                .method(Method::POST)
238                .body(body)?;
239
240            let mut response = http_client.send(request).await?;
241
242            let mut body = String::new();
243            response.body_mut().read_to_string(&mut body).await?;
244
245            let response_received_at = Instant::now();
246            if !response.status().is_success() {
247                let message = format!(
248                    "Request failed with status: {:?}\nBody: {}",
249                    response.status(),
250                    body,
251                );
252                send_finished_event(&debug_tx, &buffer, inputs.position, message.clone());
253                bail!(message);
254            };
255
256            let response: AutocompleteResponse = serde_json::from_str(&body)?;
257
258            send_finished_event(&debug_tx, &buffer, inputs.position, body);
259
260            let old_text = inputs
261                .snapshot
262                .text_for_range(response.start_index..response.end_index)
263                .collect::<String>();
264            let edits = language::text_diff(&old_text, &response.completion)
265                .into_iter()
266                .map(|(range, text)| {
267                    (
268                        inputs
269                            .snapshot
270                            .anchor_after(response.start_index + range.start)
271                            ..inputs
272                                .snapshot
273                                .anchor_before(response.start_index + range.end),
274                        text,
275                    )
276                })
277                .collect::<Vec<_>>();
278
279            anyhow::Ok((
280                response.autocomplete_id,
281                edits,
282                inputs.snapshot,
283                response_received_at,
284                ep_inputs,
285            ))
286        });
287
288        let buffer = inputs.buffer.clone();
289
290        cx.spawn(async move |cx| {
291            let (id, edits, old_snapshot, response_received_at, inputs) = result.await?;
292            anyhow::Ok(Some(
293                EditPredictionResult::new(
294                    EditPredictionId(id.into()),
295                    &buffer,
296                    &old_snapshot,
297                    edits.into(),
298                    None,
299                    buffer_snapshotted_at,
300                    response_received_at,
301                    inputs,
302                    cx,
303                )
304                .await,
305            ))
306        })
307    }
308}
309
310fn send_started_event(
311    debug_tx: &Option<mpsc::UnboundedSender<DebugEvent>>,
312    buffer: &Entity<Buffer>,
313    position: Anchor,
314    prompt: String,
315) {
316    if let Some(debug_tx) = debug_tx {
317        _ = debug_tx.unbounded_send(DebugEvent::EditPredictionStarted(
318            EditPredictionStartedDebugEvent {
319                buffer: buffer.downgrade(),
320                position,
321                prompt: Some(prompt),
322            },
323        ));
324    }
325}
326
327fn send_finished_event(
328    debug_tx: &Option<mpsc::UnboundedSender<DebugEvent>>,
329    buffer: &Entity<Buffer>,
330    position: Anchor,
331    model_output: String,
332) {
333    if let Some(debug_tx) = debug_tx {
334        _ = debug_tx.unbounded_send(DebugEvent::EditPredictionFinished(
335            EditPredictionFinishedDebugEvent {
336                buffer: buffer.downgrade(),
337                position,
338                model_output: Some(model_output),
339            },
340        ));
341    }
342}
343
344pub const SWEEP_CREDENTIALS_URL: SharedString =
345    SharedString::new_static("https://autocomplete.sweep.dev");
346pub const SWEEP_CREDENTIALS_USERNAME: &str = "sweep-api-token";
347pub static SWEEP_AI_TOKEN_ENV_VAR: std::sync::LazyLock<EnvVar> = env_var!("SWEEP_AI_TOKEN");
348
349struct GlobalSweepApiKey(Entity<ApiKeyState>);
350
351impl Global for GlobalSweepApiKey {}
352
353pub fn sweep_api_token(cx: &mut App) -> Entity<ApiKeyState> {
354    if let Some(global) = cx.try_global::<GlobalSweepApiKey>() {
355        return global.0.clone();
356    }
357    let entity =
358        cx.new(|_| ApiKeyState::new(SWEEP_CREDENTIALS_URL, SWEEP_AI_TOKEN_ENV_VAR.clone()));
359    cx.set_global(GlobalSweepApiKey(entity.clone()));
360    entity
361}
362
363pub fn load_sweep_api_token(cx: &mut App) -> Task<Result<(), language_model::AuthenticateError>> {
364    sweep_api_token(cx).update(cx, |key_state, cx| {
365        key_state.load_if_needed(SWEEP_CREDENTIALS_URL, |s| s, cx)
366    })
367}
368
369#[derive(Debug, Clone, Serialize)]
370struct AutocompleteRequest {
371    pub debug_info: Arc<str>,
372    pub repo_name: String,
373    pub branch: Option<String>,
374    pub file_path: Arc<Path>,
375    pub file_contents: String,
376    pub recent_changes: String,
377    pub cursor_position: usize,
378    pub original_file_contents: String,
379    pub file_chunks: Vec<FileChunk>,
380    pub retrieval_chunks: Vec<FileChunk>,
381    pub recent_user_actions: Vec<UserAction>,
382    pub multiple_suggestions: bool,
383    pub privacy_mode_enabled: bool,
384    pub changes_above_cursor: bool,
385    pub use_bytes: bool,
386}
387
388#[derive(Debug, Clone, Serialize)]
389struct FileChunk {
390    pub file_path: String,
391    pub start_line: usize,
392    pub end_line: usize,
393    pub content: String,
394    pub timestamp: Option<u64>,
395}
396
397#[derive(Debug, Clone, Serialize)]
398struct UserAction {
399    pub action_type: ActionType,
400    pub line_number: usize,
401    pub offset: usize,
402    pub file_path: String,
403    pub timestamp: u64,
404}
405
406#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
407#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
408enum ActionType {
409    CursorMovement,
410    InsertChar,
411    DeleteChar,
412    InsertSelection,
413    DeleteSelection,
414}
415
416fn to_sweep_user_action(record: &UserActionRecord, file_path: &str) -> UserAction {
417    UserAction {
418        action_type: match record.action_type {
419            UserActionType::InsertChar => ActionType::InsertChar,
420            UserActionType::InsertSelection => ActionType::InsertSelection,
421            UserActionType::DeleteChar => ActionType::DeleteChar,
422            UserActionType::DeleteSelection => ActionType::DeleteSelection,
423            UserActionType::CursorMovement => ActionType::CursorMovement,
424        },
425        line_number: record.line_number as usize,
426        offset: record.offset,
427        file_path: file_path.to_string(),
428        timestamp: record.timestamp_epoch_ms,
429    }
430}
431
432#[derive(Debug, Clone, Deserialize)]
433struct AutocompleteResponse {
434    pub autocomplete_id: String,
435    pub start_index: usize,
436    pub end_index: usize,
437    pub completion: String,
438    #[allow(dead_code)]
439    pub confidence: f64,
440    #[allow(dead_code)]
441    pub logprobs: Option<serde_json::Value>,
442    #[allow(dead_code)]
443    pub finish_reason: Option<String>,
444    #[allow(dead_code)]
445    pub elapsed_time_ms: u64,
446    #[allow(dead_code)]
447    #[serde(default, rename = "completions")]
448    pub additional_completions: Vec<AdditionalCompletion>,
449}
450
451#[allow(dead_code)]
452#[derive(Debug, Clone, Deserialize)]
453struct AdditionalCompletion {
454    pub start_index: usize,
455    pub end_index: usize,
456    pub completion: String,
457    pub confidence: f64,
458    pub autocomplete_id: String,
459    pub logprobs: Option<serde_json::Value>,
460    pub finish_reason: Option<String>,
461}
462
463fn write_event(event: &zeta_prompt::Event, f: &mut impl fmt::Write) -> fmt::Result {
464    match event {
465        zeta_prompt::Event::BufferChange {
466            old_path,
467            path,
468            diff,
469            ..
470        } => {
471            if old_path != path {
472                // TODO confirm how to do this for sweep
473                // writeln!(f, "User renamed {:?} to {:?}\n", old_path, new_path)?;
474            }
475
476            if !diff.is_empty() {
477                write!(f, "File: {}:\n{}\n", path.display(), diff)?
478            }
479
480            fmt::Result::Ok(())
481        }
482    }
483}
484
485fn debug_info(cx: &gpui::App) -> Arc<str> {
486    format!(
487        "Zed v{version} ({sha}) - OS: {os} - Zed v{version}",
488        version = release_channel::AppVersion::global(cx),
489        sha = release_channel::AppCommitSha::try_global(cx)
490            .map_or("unknown".to_string(), |sha| sha.full()),
491        os = client::telemetry::os_name(),
492    )
493    .into()
494}
495
496#[derive(Debug, Clone, Copy, Serialize)]
497#[serde(rename_all = "snake_case")]
498pub enum SweepEventType {
499    AutocompleteSuggestionShown,
500    AutocompleteSuggestionAccepted,
501}
502
503#[derive(Debug, Clone, Copy, Serialize)]
504#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
505pub enum SweepSuggestionType {
506    GhostText,
507    Popup,
508    JumpToEdit,
509}
510
511#[derive(Debug, Clone, Serialize)]
512struct AutocompleteMetricsRequest {
513    event_type: SweepEventType,
514    suggestion_type: SweepSuggestionType,
515    additions: u32,
516    deletions: u32,
517    autocomplete_id: String,
518    edit_tracking: String,
519    edit_tracking_line: Option<u32>,
520    lifespan: Option<u64>,
521    debug_info: Arc<str>,
522    device_id: String,
523    privacy_mode_enabled: bool,
524}
525
526fn send_autocomplete_metrics_request(
527    cx: &App,
528    client: Arc<Client>,
529    api_token: Arc<str>,
530    request_body: AutocompleteMetricsRequest,
531) {
532    let http_client = client.http_client();
533    cx.background_spawn(async move {
534        let body: AsyncBody = serde_json::to_string(&request_body)?.into();
535
536        let request = http_client::Request::builder()
537            .uri(SWEEP_METRICS_URL)
538            .header("Content-Type", "application/json")
539            .header("Authorization", format!("Bearer {}", api_token))
540            .method(Method::POST)
541            .body(body)?;
542
543        let mut response = http_client.send(request).await?;
544
545        if !response.status().is_success() {
546            let mut body = String::new();
547            response.body_mut().read_to_string(&mut body).await?;
548            anyhow::bail!(
549                "Failed to send autocomplete metrics for sweep_ai: {:?}\nBody: {}",
550                response.status(),
551                body,
552            );
553        }
554
555        Ok(())
556    })
557    .detach_and_log_err(cx);
558}
559
560pub(crate) fn edit_prediction_accepted(
561    store: &EditPredictionStore,
562    current_prediction: CurrentEditPrediction,
563    cx: &App,
564) {
565    let Some(api_token) = store
566        .sweep_ai
567        .api_token
568        .read(cx)
569        .key(&SWEEP_CREDENTIALS_URL)
570    else {
571        return;
572    };
573    let debug_info = store.sweep_ai.debug_info.clone();
574
575    let prediction = current_prediction.prediction;
576
577    let (additions, deletions) = compute_edit_metrics(&prediction.edits, &prediction.snapshot);
578    let autocomplete_id = prediction.id.to_string();
579
580    let device_id = store
581        .client
582        .user_id()
583        .as_ref()
584        .map(ToString::to_string)
585        .unwrap_or_default();
586
587    let suggestion_type = match current_prediction.shown_with {
588        Some(SuggestionDisplayType::DiffPopover) => SweepSuggestionType::Popup,
589        Some(SuggestionDisplayType::Jump) => return, // should'nt happen
590        Some(SuggestionDisplayType::GhostText) | None => SweepSuggestionType::GhostText,
591    };
592
593    let request_body = AutocompleteMetricsRequest {
594        event_type: SweepEventType::AutocompleteSuggestionAccepted,
595        suggestion_type,
596        additions,
597        deletions,
598        autocomplete_id,
599        edit_tracking: String::new(),
600        edit_tracking_line: None,
601        lifespan: None,
602        debug_info,
603        device_id,
604        privacy_mode_enabled: false,
605    };
606
607    send_autocomplete_metrics_request(cx, store.client.clone(), api_token, request_body);
608}
609
610pub fn edit_prediction_shown(
611    sweep_ai: &SweepAi,
612    client: Arc<Client>,
613    prediction: &EditPrediction,
614    display_type: SuggestionDisplayType,
615    cx: &App,
616) {
617    let Some(api_token) = sweep_ai.api_token.read(cx).key(&SWEEP_CREDENTIALS_URL) else {
618        return;
619    };
620    let debug_info = sweep_ai.debug_info.clone();
621
622    let (additions, deletions) = compute_edit_metrics(&prediction.edits, &prediction.snapshot);
623    let autocomplete_id = prediction.id.to_string();
624
625    let suggestion_type = match display_type {
626        SuggestionDisplayType::GhostText => SweepSuggestionType::GhostText,
627        SuggestionDisplayType::DiffPopover => SweepSuggestionType::Popup,
628        SuggestionDisplayType::Jump => SweepSuggestionType::JumpToEdit,
629    };
630
631    let request_body = AutocompleteMetricsRequest {
632        event_type: SweepEventType::AutocompleteSuggestionShown,
633        suggestion_type,
634        additions,
635        deletions,
636        autocomplete_id,
637        edit_tracking: String::new(),
638        edit_tracking_line: None,
639        lifespan: None,
640        debug_info,
641        device_id: String::new(),
642        privacy_mode_enabled: false,
643    };
644
645    send_autocomplete_metrics_request(cx, client, api_token, request_body);
646}
647
648fn compute_edit_metrics(
649    edits: &[(Range<Anchor>, Arc<str>)],
650    snapshot: &BufferSnapshot,
651) -> (u32, u32) {
652    let mut additions = 0u32;
653    let mut deletions = 0u32;
654
655    for (range, new_text) in edits {
656        let old_text = snapshot.text_for_range(range.clone());
657        deletions += old_text
658            .map(|chunk| chunk.lines().count())
659            .sum::<usize>()
660            .max(1) as u32;
661        additions += new_text.lines().count().max(1) as u32;
662    }
663
664    (additions, deletions)
665}