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 excerpt_ranges: None,
223 preferred_model: None,
224 in_open_source_repo: false,
225 };
226
227 send_started_event(
228 &debug_tx,
229 &buffer,
230 inputs.position,
231 serde_json::to_string(&request_body).unwrap_or_default(),
232 );
233
234 let request = http_client::Request::builder()
235 .uri(SWEEP_API_URL)
236 .header("Content-Type", "application/json")
237 .header("Authorization", format!("Bearer {}", api_token))
238 .header("Connection", "keep-alive")
239 .header("Content-Encoding", "br")
240 .method(Method::POST)
241 .body(body)?;
242
243 let mut response = http_client.send(request).await?;
244
245 let mut body = String::new();
246 response.body_mut().read_to_string(&mut body).await?;
247
248 let response_received_at = Instant::now();
249 if !response.status().is_success() {
250 let message = format!(
251 "Request failed with status: {:?}\nBody: {}",
252 response.status(),
253 body,
254 );
255 send_finished_event(&debug_tx, &buffer, inputs.position, message.clone());
256 bail!(message);
257 };
258
259 let response: AutocompleteResponse = serde_json::from_str(&body)?;
260
261 send_finished_event(&debug_tx, &buffer, inputs.position, body);
262
263 let old_text = inputs
264 .snapshot
265 .text_for_range(response.start_index..response.end_index)
266 .collect::<String>();
267 let edits = language::text_diff(&old_text, &response.completion)
268 .into_iter()
269 .map(|(range, text)| {
270 (
271 inputs
272 .snapshot
273 .anchor_after(response.start_index + range.start)
274 ..inputs
275 .snapshot
276 .anchor_before(response.start_index + range.end),
277 text,
278 )
279 })
280 .collect::<Vec<_>>();
281
282 anyhow::Ok((
283 response.autocomplete_id,
284 edits,
285 inputs.snapshot,
286 response_received_at,
287 ep_inputs,
288 ))
289 });
290
291 let buffer = inputs.buffer.clone();
292
293 cx.spawn(async move |cx| {
294 let (id, edits, old_snapshot, response_received_at, inputs) = result.await?;
295 anyhow::Ok(Some(
296 EditPredictionResult::new(
297 EditPredictionId(id.into()),
298 &buffer,
299 &old_snapshot,
300 edits.into(),
301 None,
302 buffer_snapshotted_at,
303 response_received_at,
304 inputs,
305 cx,
306 )
307 .await,
308 ))
309 })
310 }
311}
312
313fn send_started_event(
314 debug_tx: &Option<mpsc::UnboundedSender<DebugEvent>>,
315 buffer: &Entity<Buffer>,
316 position: Anchor,
317 prompt: String,
318) {
319 if let Some(debug_tx) = debug_tx {
320 _ = debug_tx.unbounded_send(DebugEvent::EditPredictionStarted(
321 EditPredictionStartedDebugEvent {
322 buffer: buffer.downgrade(),
323 position,
324 prompt: Some(prompt),
325 },
326 ));
327 }
328}
329
330fn send_finished_event(
331 debug_tx: &Option<mpsc::UnboundedSender<DebugEvent>>,
332 buffer: &Entity<Buffer>,
333 position: Anchor,
334 model_output: String,
335) {
336 if let Some(debug_tx) = debug_tx {
337 _ = debug_tx.unbounded_send(DebugEvent::EditPredictionFinished(
338 EditPredictionFinishedDebugEvent {
339 buffer: buffer.downgrade(),
340 position,
341 model_output: Some(model_output),
342 },
343 ));
344 }
345}
346
347pub const SWEEP_CREDENTIALS_URL: SharedString =
348 SharedString::new_static("https://autocomplete.sweep.dev");
349pub const SWEEP_CREDENTIALS_USERNAME: &str = "sweep-api-token";
350pub static SWEEP_AI_TOKEN_ENV_VAR: std::sync::LazyLock<EnvVar> = env_var!("SWEEP_AI_TOKEN");
351
352struct GlobalSweepApiKey(Entity<ApiKeyState>);
353
354impl Global for GlobalSweepApiKey {}
355
356pub fn sweep_api_token(cx: &mut App) -> Entity<ApiKeyState> {
357 if let Some(global) = cx.try_global::<GlobalSweepApiKey>() {
358 return global.0.clone();
359 }
360 let entity =
361 cx.new(|_| ApiKeyState::new(SWEEP_CREDENTIALS_URL, SWEEP_AI_TOKEN_ENV_VAR.clone()));
362 cx.set_global(GlobalSweepApiKey(entity.clone()));
363 entity
364}
365
366pub fn load_sweep_api_token(cx: &mut App) -> Task<Result<(), language_model::AuthenticateError>> {
367 sweep_api_token(cx).update(cx, |key_state, cx| {
368 key_state.load_if_needed(SWEEP_CREDENTIALS_URL, |s| s, cx)
369 })
370}
371
372#[derive(Debug, Clone, Serialize)]
373struct AutocompleteRequest {
374 pub debug_info: Arc<str>,
375 pub repo_name: String,
376 pub branch: Option<String>,
377 pub file_path: Arc<Path>,
378 pub file_contents: String,
379 pub recent_changes: String,
380 pub cursor_position: usize,
381 pub original_file_contents: String,
382 pub file_chunks: Vec<FileChunk>,
383 pub retrieval_chunks: Vec<FileChunk>,
384 pub recent_user_actions: Vec<UserAction>,
385 pub multiple_suggestions: bool,
386 pub privacy_mode_enabled: bool,
387 pub changes_above_cursor: bool,
388 pub use_bytes: bool,
389}
390
391#[derive(Debug, Clone, Serialize)]
392struct FileChunk {
393 pub file_path: String,
394 pub start_line: usize,
395 pub end_line: usize,
396 pub content: String,
397 pub timestamp: Option<u64>,
398}
399
400#[derive(Debug, Clone, Serialize)]
401struct UserAction {
402 pub action_type: ActionType,
403 pub line_number: usize,
404 pub offset: usize,
405 pub file_path: String,
406 pub timestamp: u64,
407}
408
409#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
410#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
411enum ActionType {
412 CursorMovement,
413 InsertChar,
414 DeleteChar,
415 InsertSelection,
416 DeleteSelection,
417}
418
419fn to_sweep_user_action(record: &UserActionRecord, file_path: &str) -> UserAction {
420 UserAction {
421 action_type: match record.action_type {
422 UserActionType::InsertChar => ActionType::InsertChar,
423 UserActionType::InsertSelection => ActionType::InsertSelection,
424 UserActionType::DeleteChar => ActionType::DeleteChar,
425 UserActionType::DeleteSelection => ActionType::DeleteSelection,
426 UserActionType::CursorMovement => ActionType::CursorMovement,
427 },
428 line_number: record.line_number as usize,
429 offset: record.offset,
430 file_path: file_path.to_string(),
431 timestamp: record.timestamp_epoch_ms,
432 }
433}
434
435#[derive(Debug, Clone, Deserialize)]
436struct AutocompleteResponse {
437 pub autocomplete_id: String,
438 pub start_index: usize,
439 pub end_index: usize,
440 pub completion: String,
441 #[allow(dead_code)]
442 pub confidence: f64,
443 #[allow(dead_code)]
444 pub logprobs: Option<serde_json::Value>,
445 #[allow(dead_code)]
446 pub finish_reason: Option<String>,
447 #[allow(dead_code)]
448 pub elapsed_time_ms: u64,
449 #[allow(dead_code)]
450 #[serde(default, rename = "completions")]
451 pub additional_completions: Vec<AdditionalCompletion>,
452}
453
454#[allow(dead_code)]
455#[derive(Debug, Clone, Deserialize)]
456struct AdditionalCompletion {
457 pub start_index: usize,
458 pub end_index: usize,
459 pub completion: String,
460 pub confidence: f64,
461 pub autocomplete_id: String,
462 pub logprobs: Option<serde_json::Value>,
463 pub finish_reason: Option<String>,
464}
465
466fn write_event(event: &zeta_prompt::Event, f: &mut impl fmt::Write) -> fmt::Result {
467 match event {
468 zeta_prompt::Event::BufferChange {
469 old_path,
470 path,
471 diff,
472 ..
473 } => {
474 if old_path != path {
475 // TODO confirm how to do this for sweep
476 // writeln!(f, "User renamed {:?} to {:?}\n", old_path, new_path)?;
477 }
478
479 if !diff.is_empty() {
480 write!(f, "File: {}:\n{}\n", path.display(), diff)?
481 }
482
483 fmt::Result::Ok(())
484 }
485 }
486}
487
488fn debug_info(cx: &gpui::App) -> Arc<str> {
489 format!(
490 "Zed v{version} ({sha}) - OS: {os} - Zed v{version}",
491 version = release_channel::AppVersion::global(cx),
492 sha = release_channel::AppCommitSha::try_global(cx)
493 .map_or("unknown".to_string(), |sha| sha.full()),
494 os = client::telemetry::os_name(),
495 )
496 .into()
497}
498
499#[derive(Debug, Clone, Copy, Serialize)]
500#[serde(rename_all = "snake_case")]
501pub enum SweepEventType {
502 AutocompleteSuggestionShown,
503 AutocompleteSuggestionAccepted,
504}
505
506#[derive(Debug, Clone, Copy, Serialize)]
507#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
508pub enum SweepSuggestionType {
509 GhostText,
510 Popup,
511 JumpToEdit,
512}
513
514#[derive(Debug, Clone, Serialize)]
515struct AutocompleteMetricsRequest {
516 event_type: SweepEventType,
517 suggestion_type: SweepSuggestionType,
518 additions: u32,
519 deletions: u32,
520 autocomplete_id: String,
521 edit_tracking: String,
522 edit_tracking_line: Option<u32>,
523 lifespan: Option<u64>,
524 debug_info: Arc<str>,
525 device_id: String,
526 privacy_mode_enabled: bool,
527}
528
529fn send_autocomplete_metrics_request(
530 cx: &App,
531 client: Arc<Client>,
532 api_token: Arc<str>,
533 request_body: AutocompleteMetricsRequest,
534) {
535 let http_client = client.http_client();
536 cx.background_spawn(async move {
537 let body: AsyncBody = serde_json::to_string(&request_body)?.into();
538
539 let request = http_client::Request::builder()
540 .uri(SWEEP_METRICS_URL)
541 .header("Content-Type", "application/json")
542 .header("Authorization", format!("Bearer {}", api_token))
543 .method(Method::POST)
544 .body(body)?;
545
546 let mut response = http_client.send(request).await?;
547
548 if !response.status().is_success() {
549 let mut body = String::new();
550 response.body_mut().read_to_string(&mut body).await?;
551 anyhow::bail!(
552 "Failed to send autocomplete metrics for sweep_ai: {:?}\nBody: {}",
553 response.status(),
554 body,
555 );
556 }
557
558 Ok(())
559 })
560 .detach_and_log_err(cx);
561}
562
563pub(crate) fn edit_prediction_accepted(
564 store: &EditPredictionStore,
565 current_prediction: CurrentEditPrediction,
566 cx: &App,
567) {
568 let Some(api_token) = store
569 .sweep_ai
570 .api_token
571 .read(cx)
572 .key(&SWEEP_CREDENTIALS_URL)
573 else {
574 return;
575 };
576 let debug_info = store.sweep_ai.debug_info.clone();
577
578 let prediction = current_prediction.prediction;
579
580 let (additions, deletions) = compute_edit_metrics(&prediction.edits, &prediction.snapshot);
581 let autocomplete_id = prediction.id.to_string();
582
583 let device_id = store
584 .client
585 .user_id()
586 .as_ref()
587 .map(ToString::to_string)
588 .unwrap_or_default();
589
590 let suggestion_type = match current_prediction.shown_with {
591 Some(SuggestionDisplayType::DiffPopover) => SweepSuggestionType::Popup,
592 Some(SuggestionDisplayType::Jump) => return, // should'nt happen
593 Some(SuggestionDisplayType::GhostText) | None => SweepSuggestionType::GhostText,
594 };
595
596 let request_body = AutocompleteMetricsRequest {
597 event_type: SweepEventType::AutocompleteSuggestionAccepted,
598 suggestion_type,
599 additions,
600 deletions,
601 autocomplete_id,
602 edit_tracking: String::new(),
603 edit_tracking_line: None,
604 lifespan: None,
605 debug_info,
606 device_id,
607 privacy_mode_enabled: false,
608 };
609
610 send_autocomplete_metrics_request(cx, store.client.clone(), api_token, request_body);
611}
612
613pub fn edit_prediction_shown(
614 sweep_ai: &SweepAi,
615 client: Arc<Client>,
616 prediction: &EditPrediction,
617 display_type: SuggestionDisplayType,
618 cx: &App,
619) {
620 let Some(api_token) = sweep_ai.api_token.read(cx).key(&SWEEP_CREDENTIALS_URL) else {
621 return;
622 };
623 let debug_info = sweep_ai.debug_info.clone();
624
625 let (additions, deletions) = compute_edit_metrics(&prediction.edits, &prediction.snapshot);
626 let autocomplete_id = prediction.id.to_string();
627
628 let suggestion_type = match display_type {
629 SuggestionDisplayType::GhostText => SweepSuggestionType::GhostText,
630 SuggestionDisplayType::DiffPopover => SweepSuggestionType::Popup,
631 SuggestionDisplayType::Jump => SweepSuggestionType::JumpToEdit,
632 };
633
634 let request_body = AutocompleteMetricsRequest {
635 event_type: SweepEventType::AutocompleteSuggestionShown,
636 suggestion_type,
637 additions,
638 deletions,
639 autocomplete_id,
640 edit_tracking: String::new(),
641 edit_tracking_line: None,
642 lifespan: None,
643 debug_info,
644 device_id: String::new(),
645 privacy_mode_enabled: false,
646 };
647
648 send_autocomplete_metrics_request(cx, client, api_token, request_body);
649}
650
651fn compute_edit_metrics(
652 edits: &[(Range<Anchor>, Arc<str>)],
653 snapshot: &BufferSnapshot,
654) -> (u32, u32) {
655 let mut additions = 0u32;
656 let mut deletions = 0u32;
657
658 for (range, new_text) in edits {
659 let old_text = snapshot.text_for_range(range.clone());
660 deletions += old_text
661 .map(|chunk| chunk.lines().count())
662 .sum::<usize>()
663 .max(1) as u32;
664 additions += new_text.lines().count().max(1) as u32;
665 }
666
667 (additions, deletions)
668}