buffer_codegen.rs

   1use crate::{
   2    context::load_context, context_store::ContextStore, inline_prompt_editor::CodegenStatus,
   3};
   4use agent_settings::AgentSettings;
   5use anyhow::{Context as _, Result};
   6use client::telemetry::Telemetry;
   7use cloud_llm_client::CompletionIntent;
   8use collections::HashSet;
   9use editor::{Anchor, AnchorRangeExt, MultiBuffer, MultiBufferSnapshot, ToOffset as _, ToPoint};
  10use futures::{
  11    SinkExt, Stream, StreamExt, TryStreamExt as _, channel::mpsc, future::LocalBoxFuture, join,
  12};
  13use gpui::{App, AppContext as _, Context, Entity, EventEmitter, Subscription, Task, WeakEntity};
  14use language::{Buffer, IndentKind, Point, TransactionId, line_diff};
  15use language_model::{
  16    LanguageModel, LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage,
  17    LanguageModelTextStream, Role, report_assistant_event,
  18};
  19use multi_buffer::MultiBufferRow;
  20use parking_lot::Mutex;
  21use project::Project;
  22use prompt_store::{PromptBuilder, PromptStore};
  23use rope::Rope;
  24use smol::future::FutureExt;
  25use std::{
  26    cmp,
  27    future::Future,
  28    iter,
  29    ops::{Range, RangeInclusive},
  30    pin::Pin,
  31    sync::Arc,
  32    task::{self, Poll},
  33    time::Instant,
  34};
  35use streaming_diff::{CharOperation, LineDiff, LineOperation, StreamingDiff};
  36use telemetry_events::{AssistantEventData, AssistantKind, AssistantPhase};
  37
  38pub struct BufferCodegen {
  39    alternatives: Vec<Entity<CodegenAlternative>>,
  40    pub active_alternative: usize,
  41    seen_alternatives: HashSet<usize>,
  42    subscriptions: Vec<Subscription>,
  43    buffer: Entity<MultiBuffer>,
  44    range: Range<Anchor>,
  45    initial_transaction_id: Option<TransactionId>,
  46    context_store: Entity<ContextStore>,
  47    project: WeakEntity<Project>,
  48    prompt_store: Option<Entity<PromptStore>>,
  49    telemetry: Arc<Telemetry>,
  50    builder: Arc<PromptBuilder>,
  51    pub is_insertion: bool,
  52}
  53
  54impl BufferCodegen {
  55    pub fn new(
  56        buffer: Entity<MultiBuffer>,
  57        range: Range<Anchor>,
  58        initial_transaction_id: Option<TransactionId>,
  59        context_store: Entity<ContextStore>,
  60        project: WeakEntity<Project>,
  61        prompt_store: Option<Entity<PromptStore>>,
  62        telemetry: Arc<Telemetry>,
  63        builder: Arc<PromptBuilder>,
  64        cx: &mut Context<Self>,
  65    ) -> Self {
  66        let codegen = cx.new(|cx| {
  67            CodegenAlternative::new(
  68                buffer.clone(),
  69                range.clone(),
  70                false,
  71                Some(context_store.clone()),
  72                project.clone(),
  73                prompt_store.clone(),
  74                Some(telemetry.clone()),
  75                builder.clone(),
  76                cx,
  77            )
  78        });
  79        let mut this = Self {
  80            is_insertion: range.to_offset(&buffer.read(cx).snapshot(cx)).is_empty(),
  81            alternatives: vec![codegen],
  82            active_alternative: 0,
  83            seen_alternatives: HashSet::default(),
  84            subscriptions: Vec::new(),
  85            buffer,
  86            range,
  87            initial_transaction_id,
  88            context_store,
  89            project,
  90            prompt_store,
  91            telemetry,
  92            builder,
  93        };
  94        this.activate(0, cx);
  95        this
  96    }
  97
  98    fn subscribe_to_alternative(&mut self, cx: &mut Context<Self>) {
  99        let codegen = self.active_alternative().clone();
 100        self.subscriptions.clear();
 101        self.subscriptions
 102            .push(cx.observe(&codegen, |_, _, cx| cx.notify()));
 103        self.subscriptions
 104            .push(cx.subscribe(&codegen, |_, _, event, cx| cx.emit(*event)));
 105    }
 106
 107    pub fn active_alternative(&self) -> &Entity<CodegenAlternative> {
 108        &self.alternatives[self.active_alternative]
 109    }
 110
 111    pub fn status<'a>(&self, cx: &'a App) -> &'a CodegenStatus {
 112        &self.active_alternative().read(cx).status
 113    }
 114
 115    pub fn alternative_count(&self, cx: &App) -> usize {
 116        LanguageModelRegistry::read_global(cx)
 117            .inline_alternative_models()
 118            .len()
 119            + 1
 120    }
 121
 122    pub fn cycle_prev(&mut self, cx: &mut Context<Self>) {
 123        let next_active_ix = if self.active_alternative == 0 {
 124            self.alternatives.len() - 1
 125        } else {
 126            self.active_alternative - 1
 127        };
 128        self.activate(next_active_ix, cx);
 129    }
 130
 131    pub fn cycle_next(&mut self, cx: &mut Context<Self>) {
 132        let next_active_ix = (self.active_alternative + 1) % self.alternatives.len();
 133        self.activate(next_active_ix, cx);
 134    }
 135
 136    fn activate(&mut self, index: usize, cx: &mut Context<Self>) {
 137        self.active_alternative()
 138            .update(cx, |codegen, cx| codegen.set_active(false, cx));
 139        self.seen_alternatives.insert(index);
 140        self.active_alternative = index;
 141        self.active_alternative()
 142            .update(cx, |codegen, cx| codegen.set_active(true, cx));
 143        self.subscribe_to_alternative(cx);
 144        cx.notify();
 145    }
 146
 147    pub fn start(
 148        &mut self,
 149        primary_model: Arc<dyn LanguageModel>,
 150        user_prompt: String,
 151        cx: &mut Context<Self>,
 152    ) -> Result<()> {
 153        let alternative_models = LanguageModelRegistry::read_global(cx)
 154            .inline_alternative_models()
 155            .to_vec();
 156
 157        self.active_alternative()
 158            .update(cx, |alternative, cx| alternative.undo(cx));
 159        self.activate(0, cx);
 160        self.alternatives.truncate(1);
 161
 162        for _ in 0..alternative_models.len() {
 163            self.alternatives.push(cx.new(|cx| {
 164                CodegenAlternative::new(
 165                    self.buffer.clone(),
 166                    self.range.clone(),
 167                    false,
 168                    Some(self.context_store.clone()),
 169                    self.project.clone(),
 170                    self.prompt_store.clone(),
 171                    Some(self.telemetry.clone()),
 172                    self.builder.clone(),
 173                    cx,
 174                )
 175            }));
 176        }
 177
 178        for (model, alternative) in iter::once(primary_model)
 179            .chain(alternative_models)
 180            .zip(&self.alternatives)
 181        {
 182            alternative.update(cx, |alternative, cx| {
 183                alternative.start(user_prompt.clone(), model.clone(), cx)
 184            })?;
 185        }
 186
 187        Ok(())
 188    }
 189
 190    pub fn stop(&mut self, cx: &mut Context<Self>) {
 191        for codegen in &self.alternatives {
 192            codegen.update(cx, |codegen, cx| codegen.stop(cx));
 193        }
 194    }
 195
 196    pub fn undo(&mut self, cx: &mut Context<Self>) {
 197        self.active_alternative()
 198            .update(cx, |codegen, cx| codegen.undo(cx));
 199
 200        self.buffer.update(cx, |buffer, cx| {
 201            if let Some(transaction_id) = self.initial_transaction_id.take() {
 202                buffer.undo_transaction(transaction_id, cx);
 203                buffer.refresh_preview(cx);
 204            }
 205        });
 206    }
 207
 208    pub fn buffer(&self, cx: &App) -> Entity<MultiBuffer> {
 209        self.active_alternative().read(cx).buffer.clone()
 210    }
 211
 212    pub fn old_buffer(&self, cx: &App) -> Entity<Buffer> {
 213        self.active_alternative().read(cx).old_buffer.clone()
 214    }
 215
 216    pub fn snapshot(&self, cx: &App) -> MultiBufferSnapshot {
 217        self.active_alternative().read(cx).snapshot.clone()
 218    }
 219
 220    pub fn edit_position(&self, cx: &App) -> Option<Anchor> {
 221        self.active_alternative().read(cx).edit_position
 222    }
 223
 224    pub fn diff<'a>(&self, cx: &'a App) -> &'a Diff {
 225        &self.active_alternative().read(cx).diff
 226    }
 227
 228    pub fn last_equal_ranges<'a>(&self, cx: &'a App) -> &'a [Range<Anchor>] {
 229        self.active_alternative().read(cx).last_equal_ranges()
 230    }
 231}
 232
 233impl EventEmitter<CodegenEvent> for BufferCodegen {}
 234
 235pub struct CodegenAlternative {
 236    buffer: Entity<MultiBuffer>,
 237    old_buffer: Entity<Buffer>,
 238    snapshot: MultiBufferSnapshot,
 239    edit_position: Option<Anchor>,
 240    range: Range<Anchor>,
 241    last_equal_ranges: Vec<Range<Anchor>>,
 242    transformation_transaction_id: Option<TransactionId>,
 243    status: CodegenStatus,
 244    generation: Task<()>,
 245    diff: Diff,
 246    context_store: Option<Entity<ContextStore>>,
 247    project: WeakEntity<Project>,
 248    prompt_store: Option<Entity<PromptStore>>,
 249    telemetry: Option<Arc<Telemetry>>,
 250    _subscription: gpui::Subscription,
 251    builder: Arc<PromptBuilder>,
 252    active: bool,
 253    edits: Vec<(Range<Anchor>, String)>,
 254    line_operations: Vec<LineOperation>,
 255    elapsed_time: Option<f64>,
 256    completion: Option<String>,
 257    pub message_id: Option<String>,
 258}
 259
 260impl EventEmitter<CodegenEvent> for CodegenAlternative {}
 261
 262impl CodegenAlternative {
 263    pub fn new(
 264        buffer: Entity<MultiBuffer>,
 265        range: Range<Anchor>,
 266        active: bool,
 267        context_store: Option<Entity<ContextStore>>,
 268        project: WeakEntity<Project>,
 269        prompt_store: Option<Entity<PromptStore>>,
 270        telemetry: Option<Arc<Telemetry>>,
 271        builder: Arc<PromptBuilder>,
 272        cx: &mut Context<Self>,
 273    ) -> Self {
 274        let snapshot = buffer.read(cx).snapshot(cx);
 275
 276        let (old_buffer, _, _) = snapshot
 277            .range_to_buffer_ranges(range.clone())
 278            .pop()
 279            .unwrap();
 280        let old_buffer = cx.new(|cx| {
 281            let text = old_buffer.as_rope().clone();
 282            let line_ending = old_buffer.line_ending();
 283            let language = old_buffer.language().cloned();
 284            let language_registry = buffer
 285                .read(cx)
 286                .buffer(old_buffer.remote_id())
 287                .unwrap()
 288                .read(cx)
 289                .language_registry();
 290
 291            let mut buffer = Buffer::local_normalized(text, line_ending, cx);
 292            buffer.set_language(language, cx);
 293            if let Some(language_registry) = language_registry {
 294                buffer.set_language_registry(language_registry)
 295            }
 296            buffer
 297        });
 298
 299        Self {
 300            buffer: buffer.clone(),
 301            old_buffer,
 302            edit_position: None,
 303            message_id: None,
 304            snapshot,
 305            last_equal_ranges: Default::default(),
 306            transformation_transaction_id: None,
 307            status: CodegenStatus::Idle,
 308            generation: Task::ready(()),
 309            diff: Diff::default(),
 310            context_store,
 311            project,
 312            prompt_store,
 313            telemetry,
 314            _subscription: cx.subscribe(&buffer, Self::handle_buffer_event),
 315            builder,
 316            active,
 317            edits: Vec::new(),
 318            line_operations: Vec::new(),
 319            range,
 320            elapsed_time: None,
 321            completion: None,
 322        }
 323    }
 324
 325    pub fn set_active(&mut self, active: bool, cx: &mut Context<Self>) {
 326        if active != self.active {
 327            self.active = active;
 328
 329            if self.active {
 330                let edits = self.edits.clone();
 331                self.apply_edits(edits, cx);
 332                if matches!(self.status, CodegenStatus::Pending) {
 333                    let line_operations = self.line_operations.clone();
 334                    self.reapply_line_based_diff(line_operations, cx);
 335                } else {
 336                    self.reapply_batch_diff(cx).detach();
 337                }
 338            } else if let Some(transaction_id) = self.transformation_transaction_id.take() {
 339                self.buffer.update(cx, |buffer, cx| {
 340                    buffer.undo_transaction(transaction_id, cx);
 341                    buffer.forget_transaction(transaction_id, cx);
 342                });
 343            }
 344        }
 345    }
 346
 347    fn handle_buffer_event(
 348        &mut self,
 349        _buffer: Entity<MultiBuffer>,
 350        event: &multi_buffer::Event,
 351        cx: &mut Context<Self>,
 352    ) {
 353        if let multi_buffer::Event::TransactionUndone { transaction_id } = event
 354            && self.transformation_transaction_id == Some(*transaction_id)
 355        {
 356            self.transformation_transaction_id = None;
 357            self.generation = Task::ready(());
 358            cx.emit(CodegenEvent::Undone);
 359        }
 360    }
 361
 362    pub fn last_equal_ranges(&self) -> &[Range<Anchor>] {
 363        &self.last_equal_ranges
 364    }
 365
 366    pub fn start(
 367        &mut self,
 368        user_prompt: String,
 369        model: Arc<dyn LanguageModel>,
 370        cx: &mut Context<Self>,
 371    ) -> Result<()> {
 372        if let Some(transformation_transaction_id) = self.transformation_transaction_id.take() {
 373            self.buffer.update(cx, |buffer, cx| {
 374                buffer.undo_transaction(transformation_transaction_id, cx);
 375            });
 376        }
 377
 378        self.edit_position = Some(self.range.start.bias_right(&self.snapshot));
 379
 380        let api_key = model.api_key(cx);
 381        let telemetry_id = model.telemetry_id();
 382        let provider_id = model.provider_id();
 383        let stream: LocalBoxFuture<Result<LanguageModelTextStream>> =
 384            if user_prompt.trim().to_lowercase() == "delete" {
 385                async { Ok(LanguageModelTextStream::default()) }.boxed_local()
 386            } else {
 387                let request = self.build_request(&model, user_prompt, cx)?;
 388                cx.spawn(async move |_, cx| {
 389                    Ok(model.stream_completion_text(request.await, cx).await?)
 390                })
 391                .boxed_local()
 392            };
 393        self.handle_stream(telemetry_id, provider_id.to_string(), api_key, stream, cx);
 394        Ok(())
 395    }
 396
 397    fn build_request(
 398        &self,
 399        model: &Arc<dyn LanguageModel>,
 400        user_prompt: String,
 401        cx: &mut App,
 402    ) -> Result<Task<LanguageModelRequest>> {
 403        let buffer = self.buffer.read(cx).snapshot(cx);
 404        let language = buffer.language_at(self.range.start);
 405        let language_name = if let Some(language) = language.as_ref() {
 406            if Arc::ptr_eq(language, &language::PLAIN_TEXT) {
 407                None
 408            } else {
 409                Some(language.name())
 410            }
 411        } else {
 412            None
 413        };
 414
 415        let language_name = language_name.as_ref();
 416        let start = buffer.point_to_buffer_offset(self.range.start);
 417        let end = buffer.point_to_buffer_offset(self.range.end);
 418        let (buffer, range) = if let Some((start, end)) = start.zip(end) {
 419            let (start_buffer, start_buffer_offset) = start;
 420            let (end_buffer, end_buffer_offset) = end;
 421            if start_buffer.remote_id() == end_buffer.remote_id() {
 422                (start_buffer.clone(), start_buffer_offset..end_buffer_offset)
 423            } else {
 424                anyhow::bail!("invalid transformation range");
 425            }
 426        } else {
 427            anyhow::bail!("invalid transformation range");
 428        };
 429
 430        let prompt = self
 431            .builder
 432            .generate_inline_transformation_prompt(
 433                user_prompt,
 434                language_name,
 435                buffer,
 436                range.start.0..range.end.0,
 437            )
 438            .context("generating content prompt")?;
 439
 440        let context_task = self.context_store.as_ref().and_then(|context_store| {
 441            if let Some(project) = self.project.upgrade() {
 442                let context = context_store
 443                    .read(cx)
 444                    .context()
 445                    .cloned()
 446                    .collect::<Vec<_>>();
 447                Some(load_context(context, &project, &self.prompt_store, cx))
 448            } else {
 449                None
 450            }
 451        });
 452
 453        let temperature = AgentSettings::temperature_for_model(model, cx);
 454
 455        Ok(cx.spawn(async move |_cx| {
 456            let mut request_message = LanguageModelRequestMessage {
 457                role: Role::User,
 458                content: Vec::new(),
 459                cache: false,
 460            };
 461
 462            if let Some(context_task) = context_task {
 463                context_task
 464                    .await
 465                    .add_to_request_message(&mut request_message);
 466            }
 467
 468            request_message.content.push(prompt.into());
 469
 470            LanguageModelRequest {
 471                thread_id: None,
 472                prompt_id: None,
 473                intent: Some(CompletionIntent::InlineAssist),
 474                mode: None,
 475                tools: Vec::new(),
 476                tool_choice: None,
 477                stop: Vec::new(),
 478                temperature,
 479                messages: vec![request_message],
 480                thinking_allowed: false,
 481            }
 482        }))
 483    }
 484
 485    pub fn handle_stream(
 486        &mut self,
 487        model_telemetry_id: String,
 488        model_provider_id: String,
 489        model_api_key: Option<String>,
 490        stream: impl 'static + Future<Output = Result<LanguageModelTextStream>>,
 491        cx: &mut Context<Self>,
 492    ) {
 493        let start_time = Instant::now();
 494        let snapshot = self.snapshot.clone();
 495        let selected_text = snapshot
 496            .text_for_range(self.range.start..self.range.end)
 497            .collect::<Rope>();
 498
 499        let selection_start = self.range.start.to_point(&snapshot);
 500
 501        // Start with the indentation of the first line in the selection
 502        let mut suggested_line_indent = snapshot
 503            .suggested_indents(selection_start.row..=selection_start.row, cx)
 504            .into_values()
 505            .next()
 506            .unwrap_or_else(|| snapshot.indent_size_for_line(MultiBufferRow(selection_start.row)));
 507
 508        // If the first line in the selection does not have indentation, check the following lines
 509        if suggested_line_indent.len == 0 && suggested_line_indent.kind == IndentKind::Space {
 510            for row in selection_start.row..=self.range.end.to_point(&snapshot).row {
 511                let line_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 512                // Prefer tabs if a line in the selection uses tabs as indentation
 513                if line_indent.kind == IndentKind::Tab {
 514                    suggested_line_indent.kind = IndentKind::Tab;
 515                    break;
 516                }
 517            }
 518        }
 519
 520        let http_client = cx.http_client();
 521        let telemetry = self.telemetry.clone();
 522        let language_name = {
 523            let multibuffer = self.buffer.read(cx);
 524            let snapshot = multibuffer.snapshot(cx);
 525            let ranges = snapshot.range_to_buffer_ranges(self.range.clone());
 526            ranges
 527                .first()
 528                .and_then(|(buffer, _, _)| buffer.language())
 529                .map(|language| language.name())
 530        };
 531
 532        self.diff = Diff::default();
 533        self.status = CodegenStatus::Pending;
 534        let mut edit_start = self.range.start.to_offset(&snapshot);
 535        let completion = Arc::new(Mutex::new(String::new()));
 536        let completion_clone = completion.clone();
 537
 538        self.generation = cx.spawn(async move |codegen, cx| {
 539            let stream = stream.await;
 540            let token_usage = stream
 541                .as_ref()
 542                .ok()
 543                .map(|stream| stream.last_token_usage.clone());
 544            let message_id = stream
 545                .as_ref()
 546                .ok()
 547                .and_then(|stream| stream.message_id.clone());
 548            let generate = async {
 549                let model_telemetry_id = model_telemetry_id.clone();
 550                let model_provider_id = model_provider_id.clone();
 551                let (mut diff_tx, mut diff_rx) = mpsc::channel(1);
 552                let executor = cx.background_executor().clone();
 553                let message_id = message_id.clone();
 554                let line_based_stream_diff: Task<anyhow::Result<()>> =
 555                    cx.background_spawn(async move {
 556                        let mut response_latency = None;
 557                        let request_start = Instant::now();
 558                        let diff = async {
 559                            let chunks = StripInvalidSpans::new(
 560                                stream?.stream.map_err(|error| error.into()),
 561                            );
 562                            futures::pin_mut!(chunks);
 563                            let mut diff = StreamingDiff::new(selected_text.to_string());
 564                            let mut line_diff = LineDiff::default();
 565
 566                            let mut new_text = String::new();
 567                            let mut base_indent = None;
 568                            let mut line_indent = None;
 569                            let mut first_line = true;
 570
 571                            while let Some(chunk) = chunks.next().await {
 572                                if response_latency.is_none() {
 573                                    response_latency = Some(request_start.elapsed());
 574                                }
 575                                let chunk = chunk?;
 576                                completion_clone.lock().push_str(&chunk);
 577
 578                                let mut lines = chunk.split('\n').peekable();
 579                                while let Some(line) = lines.next() {
 580                                    new_text.push_str(line);
 581                                    if line_indent.is_none()
 582                                        && let Some(non_whitespace_ch_ix) =
 583                                            new_text.find(|ch: char| !ch.is_whitespace())
 584                                    {
 585                                        line_indent = Some(non_whitespace_ch_ix);
 586                                        base_indent = base_indent.or(line_indent);
 587
 588                                        let line_indent = line_indent.unwrap();
 589                                        let base_indent = base_indent.unwrap();
 590                                        let indent_delta = line_indent as i32 - base_indent as i32;
 591                                        let mut corrected_indent_len = cmp::max(
 592                                            0,
 593                                            suggested_line_indent.len as i32 + indent_delta,
 594                                        )
 595                                            as usize;
 596                                        if first_line {
 597                                            corrected_indent_len = corrected_indent_len
 598                                                .saturating_sub(selection_start.column as usize);
 599                                        }
 600
 601                                        let indent_char = suggested_line_indent.char();
 602                                        let mut indent_buffer = [0; 4];
 603                                        let indent_str =
 604                                            indent_char.encode_utf8(&mut indent_buffer);
 605                                        new_text.replace_range(
 606                                            ..line_indent,
 607                                            &indent_str.repeat(corrected_indent_len),
 608                                        );
 609                                    }
 610
 611                                    if line_indent.is_some() {
 612                                        let char_ops = diff.push_new(&new_text);
 613                                        line_diff.push_char_operations(&char_ops, &selected_text);
 614                                        diff_tx
 615                                            .send((char_ops, line_diff.line_operations()))
 616                                            .await?;
 617                                        new_text.clear();
 618                                    }
 619
 620                                    if lines.peek().is_some() {
 621                                        let char_ops = diff.push_new("\n");
 622                                        line_diff.push_char_operations(&char_ops, &selected_text);
 623                                        diff_tx
 624                                            .send((char_ops, line_diff.line_operations()))
 625                                            .await?;
 626                                        if line_indent.is_none() {
 627                                            // Don't write out the leading indentation in empty lines on the next line
 628                                            // This is the case where the above if statement didn't clear the buffer
 629                                            new_text.clear();
 630                                        }
 631                                        line_indent = None;
 632                                        first_line = false;
 633                                    }
 634                                }
 635                            }
 636
 637                            let mut char_ops = diff.push_new(&new_text);
 638                            char_ops.extend(diff.finish());
 639                            line_diff.push_char_operations(&char_ops, &selected_text);
 640                            line_diff.finish(&selected_text);
 641                            diff_tx
 642                                .send((char_ops, line_diff.line_operations()))
 643                                .await?;
 644
 645                            anyhow::Ok(())
 646                        };
 647
 648                        let result = diff.await;
 649
 650                        let error_message = result.as_ref().err().map(|error| error.to_string());
 651                        report_assistant_event(
 652                            AssistantEventData {
 653                                conversation_id: None,
 654                                message_id,
 655                                kind: AssistantKind::Inline,
 656                                phase: AssistantPhase::Response,
 657                                model: model_telemetry_id,
 658                                model_provider: model_provider_id,
 659                                response_latency,
 660                                error_message,
 661                                language_name: language_name.map(|name| name.to_proto()),
 662                            },
 663                            telemetry,
 664                            http_client,
 665                            model_api_key,
 666                            &executor,
 667                        );
 668
 669                        result?;
 670                        Ok(())
 671                    });
 672
 673                while let Some((char_ops, line_ops)) = diff_rx.next().await {
 674                    codegen.update(cx, |codegen, cx| {
 675                        codegen.last_equal_ranges.clear();
 676
 677                        let edits = char_ops
 678                            .into_iter()
 679                            .filter_map(|operation| match operation {
 680                                CharOperation::Insert { text } => {
 681                                    let edit_start = snapshot.anchor_after(edit_start);
 682                                    Some((edit_start..edit_start, text))
 683                                }
 684                                CharOperation::Delete { bytes } => {
 685                                    let edit_end = edit_start + bytes;
 686                                    let edit_range = snapshot.anchor_after(edit_start)
 687                                        ..snapshot.anchor_before(edit_end);
 688                                    edit_start = edit_end;
 689                                    Some((edit_range, String::new()))
 690                                }
 691                                CharOperation::Keep { bytes } => {
 692                                    let edit_end = edit_start + bytes;
 693                                    let edit_range = snapshot.anchor_after(edit_start)
 694                                        ..snapshot.anchor_before(edit_end);
 695                                    edit_start = edit_end;
 696                                    codegen.last_equal_ranges.push(edit_range);
 697                                    None
 698                                }
 699                            })
 700                            .collect::<Vec<_>>();
 701
 702                        if codegen.active {
 703                            codegen.apply_edits(edits.iter().cloned(), cx);
 704                            codegen.reapply_line_based_diff(line_ops.iter().cloned(), cx);
 705                        }
 706                        codegen.edits.extend(edits);
 707                        codegen.line_operations = line_ops;
 708                        codegen.edit_position = Some(snapshot.anchor_after(edit_start));
 709
 710                        cx.notify();
 711                    })?;
 712                }
 713
 714                // Streaming stopped and we have the new text in the buffer, and a line-based diff applied for the whole new buffer.
 715                // That diff is not what a regular diff is and might look unexpected, ergo apply a regular diff.
 716                // It's fine to apply even if the rest of the line diffing fails, as no more hunks are coming through `diff_rx`.
 717                let batch_diff_task =
 718                    codegen.update(cx, |codegen, cx| codegen.reapply_batch_diff(cx))?;
 719                let (line_based_stream_diff, ()) = join!(line_based_stream_diff, batch_diff_task);
 720                line_based_stream_diff?;
 721
 722                anyhow::Ok(())
 723            };
 724
 725            let result = generate.await;
 726            let elapsed_time = start_time.elapsed().as_secs_f64();
 727
 728            codegen
 729                .update(cx, |this, cx| {
 730                    this.message_id = message_id;
 731                    this.last_equal_ranges.clear();
 732                    if let Err(error) = result {
 733                        this.status = CodegenStatus::Error(error);
 734                    } else {
 735                        this.status = CodegenStatus::Done;
 736                    }
 737                    this.elapsed_time = Some(elapsed_time);
 738                    this.completion = Some(completion.lock().clone());
 739                    if let Some(usage) = token_usage {
 740                        let usage = usage.lock();
 741                        telemetry::event!(
 742                            "Inline Assistant Completion",
 743                            model = model_telemetry_id,
 744                            model_provider = model_provider_id,
 745                            input_tokens = usage.input_tokens,
 746                            output_tokens = usage.output_tokens,
 747                        )
 748                    }
 749                    cx.emit(CodegenEvent::Finished);
 750                    cx.notify();
 751                })
 752                .ok();
 753        });
 754        cx.notify();
 755    }
 756
 757    pub fn stop(&mut self, cx: &mut Context<Self>) {
 758        self.last_equal_ranges.clear();
 759        if self.diff.is_empty() {
 760            self.status = CodegenStatus::Idle;
 761        } else {
 762            self.status = CodegenStatus::Done;
 763        }
 764        self.generation = Task::ready(());
 765        cx.emit(CodegenEvent::Finished);
 766        cx.notify();
 767    }
 768
 769    pub fn undo(&mut self, cx: &mut Context<Self>) {
 770        self.buffer.update(cx, |buffer, cx| {
 771            if let Some(transaction_id) = self.transformation_transaction_id.take() {
 772                buffer.undo_transaction(transaction_id, cx);
 773                buffer.refresh_preview(cx);
 774            }
 775        });
 776    }
 777
 778    fn apply_edits(
 779        &mut self,
 780        edits: impl IntoIterator<Item = (Range<Anchor>, String)>,
 781        cx: &mut Context<CodegenAlternative>,
 782    ) {
 783        let transaction = self.buffer.update(cx, |buffer, cx| {
 784            // Avoid grouping agent edits with user edits.
 785            buffer.finalize_last_transaction(cx);
 786            buffer.start_transaction(cx);
 787            buffer.edit(edits, None, cx);
 788            buffer.end_transaction(cx)
 789        });
 790
 791        if let Some(transaction) = transaction {
 792            if let Some(first_transaction) = self.transformation_transaction_id {
 793                // Group all agent edits into the first transaction.
 794                self.buffer.update(cx, |buffer, cx| {
 795                    buffer.merge_transactions(transaction, first_transaction, cx)
 796                });
 797            } else {
 798                self.transformation_transaction_id = Some(transaction);
 799                self.buffer
 800                    .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 801            }
 802        }
 803    }
 804
 805    fn reapply_line_based_diff(
 806        &mut self,
 807        line_operations: impl IntoIterator<Item = LineOperation>,
 808        cx: &mut Context<Self>,
 809    ) {
 810        let old_snapshot = self.snapshot.clone();
 811        let old_range = self.range.to_point(&old_snapshot);
 812        let new_snapshot = self.buffer.read(cx).snapshot(cx);
 813        let new_range = self.range.to_point(&new_snapshot);
 814
 815        let mut old_row = old_range.start.row;
 816        let mut new_row = new_range.start.row;
 817
 818        self.diff.deleted_row_ranges.clear();
 819        self.diff.inserted_row_ranges.clear();
 820        for operation in line_operations {
 821            match operation {
 822                LineOperation::Keep { lines } => {
 823                    old_row += lines;
 824                    new_row += lines;
 825                }
 826                LineOperation::Delete { lines } => {
 827                    let old_end_row = old_row + lines - 1;
 828                    let new_row = new_snapshot.anchor_before(Point::new(new_row, 0));
 829
 830                    if let Some((_, last_deleted_row_range)) =
 831                        self.diff.deleted_row_ranges.last_mut()
 832                    {
 833                        if *last_deleted_row_range.end() + 1 == old_row {
 834                            *last_deleted_row_range = *last_deleted_row_range.start()..=old_end_row;
 835                        } else {
 836                            self.diff
 837                                .deleted_row_ranges
 838                                .push((new_row, old_row..=old_end_row));
 839                        }
 840                    } else {
 841                        self.diff
 842                            .deleted_row_ranges
 843                            .push((new_row, old_row..=old_end_row));
 844                    }
 845
 846                    old_row += lines;
 847                }
 848                LineOperation::Insert { lines } => {
 849                    let new_end_row = new_row + lines - 1;
 850                    let start = new_snapshot.anchor_before(Point::new(new_row, 0));
 851                    let end = new_snapshot.anchor_before(Point::new(
 852                        new_end_row,
 853                        new_snapshot.line_len(MultiBufferRow(new_end_row)),
 854                    ));
 855                    self.diff.inserted_row_ranges.push(start..end);
 856                    new_row += lines;
 857                }
 858            }
 859
 860            cx.notify();
 861        }
 862    }
 863
 864    fn reapply_batch_diff(&mut self, cx: &mut Context<Self>) -> Task<()> {
 865        let old_snapshot = self.snapshot.clone();
 866        let old_range = self.range.to_point(&old_snapshot);
 867        let new_snapshot = self.buffer.read(cx).snapshot(cx);
 868        let new_range = self.range.to_point(&new_snapshot);
 869
 870        cx.spawn(async move |codegen, cx| {
 871            let (deleted_row_ranges, inserted_row_ranges) = cx
 872                .background_spawn(async move {
 873                    let old_text = old_snapshot
 874                        .text_for_range(
 875                            Point::new(old_range.start.row, 0)
 876                                ..Point::new(
 877                                    old_range.end.row,
 878                                    old_snapshot.line_len(MultiBufferRow(old_range.end.row)),
 879                                ),
 880                        )
 881                        .collect::<String>();
 882                    let new_text = new_snapshot
 883                        .text_for_range(
 884                            Point::new(new_range.start.row, 0)
 885                                ..Point::new(
 886                                    new_range.end.row,
 887                                    new_snapshot.line_len(MultiBufferRow(new_range.end.row)),
 888                                ),
 889                        )
 890                        .collect::<String>();
 891
 892                    let old_start_row = old_range.start.row;
 893                    let new_start_row = new_range.start.row;
 894                    let mut deleted_row_ranges: Vec<(Anchor, RangeInclusive<u32>)> = Vec::new();
 895                    let mut inserted_row_ranges = Vec::new();
 896                    for (old_rows, new_rows) in line_diff(&old_text, &new_text) {
 897                        let old_rows = old_start_row + old_rows.start..old_start_row + old_rows.end;
 898                        let new_rows = new_start_row + new_rows.start..new_start_row + new_rows.end;
 899                        if !old_rows.is_empty() {
 900                            deleted_row_ranges.push((
 901                                new_snapshot.anchor_before(Point::new(new_rows.start, 0)),
 902                                old_rows.start..=old_rows.end - 1,
 903                            ));
 904                        }
 905                        if !new_rows.is_empty() {
 906                            let start = new_snapshot.anchor_before(Point::new(new_rows.start, 0));
 907                            let new_end_row = new_rows.end - 1;
 908                            let end = new_snapshot.anchor_before(Point::new(
 909                                new_end_row,
 910                                new_snapshot.line_len(MultiBufferRow(new_end_row)),
 911                            ));
 912                            inserted_row_ranges.push(start..end);
 913                        }
 914                    }
 915                    (deleted_row_ranges, inserted_row_ranges)
 916                })
 917                .await;
 918
 919            codegen
 920                .update(cx, |codegen, cx| {
 921                    codegen.diff.deleted_row_ranges = deleted_row_ranges;
 922                    codegen.diff.inserted_row_ranges = inserted_row_ranges;
 923                    cx.notify();
 924                })
 925                .ok();
 926        })
 927    }
 928}
 929
 930#[derive(Copy, Clone, Debug)]
 931pub enum CodegenEvent {
 932    Finished,
 933    Undone,
 934}
 935
 936struct StripInvalidSpans<T> {
 937    stream: T,
 938    stream_done: bool,
 939    buffer: String,
 940    first_line: bool,
 941    line_end: bool,
 942    starts_with_code_block: bool,
 943}
 944
 945impl<T> StripInvalidSpans<T>
 946where
 947    T: Stream<Item = Result<String>>,
 948{
 949    fn new(stream: T) -> Self {
 950        Self {
 951            stream,
 952            stream_done: false,
 953            buffer: String::new(),
 954            first_line: true,
 955            line_end: false,
 956            starts_with_code_block: false,
 957        }
 958    }
 959}
 960
 961impl<T> Stream for StripInvalidSpans<T>
 962where
 963    T: Stream<Item = Result<String>>,
 964{
 965    type Item = Result<String>;
 966
 967    fn poll_next(self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<Option<Self::Item>> {
 968        const CODE_BLOCK_DELIMITER: &str = "```";
 969        const CURSOR_SPAN: &str = "<|CURSOR|>";
 970
 971        let this = unsafe { self.get_unchecked_mut() };
 972        loop {
 973            if !this.stream_done {
 974                let mut stream = unsafe { Pin::new_unchecked(&mut this.stream) };
 975                match stream.as_mut().poll_next(cx) {
 976                    Poll::Ready(Some(Ok(chunk))) => {
 977                        this.buffer.push_str(&chunk);
 978                    }
 979                    Poll::Ready(Some(Err(error))) => return Poll::Ready(Some(Err(error))),
 980                    Poll::Ready(None) => {
 981                        this.stream_done = true;
 982                    }
 983                    Poll::Pending => return Poll::Pending,
 984                }
 985            }
 986
 987            let mut chunk = String::new();
 988            let mut consumed = 0;
 989            if !this.buffer.is_empty() {
 990                let mut lines = this.buffer.split('\n').enumerate().peekable();
 991                while let Some((line_ix, line)) = lines.next() {
 992                    if line_ix > 0 {
 993                        this.first_line = false;
 994                    }
 995
 996                    if this.first_line {
 997                        let trimmed_line = line.trim();
 998                        if lines.peek().is_some() {
 999                            if trimmed_line.starts_with(CODE_BLOCK_DELIMITER) {
1000                                consumed += line.len() + 1;
1001                                this.starts_with_code_block = true;
1002                                continue;
1003                            }
1004                        } else if trimmed_line.is_empty()
1005                            || prefixes(CODE_BLOCK_DELIMITER)
1006                                .any(|prefix| trimmed_line.starts_with(prefix))
1007                        {
1008                            break;
1009                        }
1010                    }
1011
1012                    let line_without_cursor = line.replace(CURSOR_SPAN, "");
1013                    if lines.peek().is_some() {
1014                        if this.line_end {
1015                            chunk.push('\n');
1016                        }
1017
1018                        chunk.push_str(&line_without_cursor);
1019                        this.line_end = true;
1020                        consumed += line.len() + 1;
1021                    } else if this.stream_done {
1022                        if !this.starts_with_code_block
1023                            || !line_without_cursor.trim().ends_with(CODE_BLOCK_DELIMITER)
1024                        {
1025                            if this.line_end {
1026                                chunk.push('\n');
1027                            }
1028
1029                            chunk.push_str(line);
1030                        }
1031
1032                        consumed += line.len();
1033                    } else {
1034                        let trimmed_line = line.trim();
1035                        if trimmed_line.is_empty()
1036                            || prefixes(CURSOR_SPAN).any(|prefix| trimmed_line.ends_with(prefix))
1037                            || prefixes(CODE_BLOCK_DELIMITER)
1038                                .any(|prefix| trimmed_line.ends_with(prefix))
1039                        {
1040                            break;
1041                        } else {
1042                            if this.line_end {
1043                                chunk.push('\n');
1044                                this.line_end = false;
1045                            }
1046
1047                            chunk.push_str(&line_without_cursor);
1048                            consumed += line.len();
1049                        }
1050                    }
1051                }
1052            }
1053
1054            this.buffer = this.buffer.split_off(consumed);
1055            if !chunk.is_empty() {
1056                return Poll::Ready(Some(Ok(chunk)));
1057            } else if this.stream_done {
1058                return Poll::Ready(None);
1059            }
1060        }
1061    }
1062}
1063
1064fn prefixes(text: &str) -> impl Iterator<Item = &str> {
1065    (0..text.len() - 1).map(|ix| &text[..ix + 1])
1066}
1067
1068#[derive(Default)]
1069pub struct Diff {
1070    pub deleted_row_ranges: Vec<(Anchor, RangeInclusive<u32>)>,
1071    pub inserted_row_ranges: Vec<Range<Anchor>>,
1072}
1073
1074impl Diff {
1075    fn is_empty(&self) -> bool {
1076        self.deleted_row_ranges.is_empty() && self.inserted_row_ranges.is_empty()
1077    }
1078}
1079
1080#[cfg(test)]
1081mod tests {
1082    use super::*;
1083    use fs::FakeFs;
1084    use futures::{
1085        Stream,
1086        stream::{self},
1087    };
1088    use gpui::TestAppContext;
1089    use indoc::indoc;
1090    use language::{Buffer, Language, LanguageConfig, LanguageMatcher, Point, tree_sitter_rust};
1091    use language_model::{LanguageModelRegistry, TokenUsage};
1092    use rand::prelude::*;
1093    use settings::SettingsStore;
1094    use std::{future, sync::Arc};
1095
1096    #[gpui::test(iterations = 10)]
1097    async fn test_transform_autoindent(cx: &mut TestAppContext, mut rng: StdRng) {
1098        init_test(cx);
1099
1100        let text = indoc! {"
1101            fn main() {
1102                let x = 0;
1103                for _ in 0..10 {
1104                    x += 1;
1105                }
1106            }
1107        "};
1108        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
1109        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1110        let range = buffer.read_with(cx, |buffer, cx| {
1111            let snapshot = buffer.snapshot(cx);
1112            snapshot.anchor_before(Point::new(1, 0))..snapshot.anchor_after(Point::new(4, 5))
1113        });
1114        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
1115        let fs = FakeFs::new(cx.executor());
1116        let project = Project::test(fs, vec![], cx).await;
1117        let codegen = cx.new(|cx| {
1118            CodegenAlternative::new(
1119                buffer.clone(),
1120                range.clone(),
1121                true,
1122                None,
1123                project.downgrade(),
1124                None,
1125                None,
1126                prompt_builder,
1127                cx,
1128            )
1129        });
1130
1131        let chunks_tx = simulate_response_stream(&codegen, cx);
1132
1133        let mut new_text = concat!(
1134            "       let mut x = 0;\n",
1135            "       while x < 10 {\n",
1136            "           x += 1;\n",
1137            "       }",
1138        );
1139        while !new_text.is_empty() {
1140            let max_len = cmp::min(new_text.len(), 10);
1141            let len = rng.random_range(1..=max_len);
1142            let (chunk, suffix) = new_text.split_at(len);
1143            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
1144            new_text = suffix;
1145            cx.background_executor.run_until_parked();
1146        }
1147        drop(chunks_tx);
1148        cx.background_executor.run_until_parked();
1149
1150        assert_eq!(
1151            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
1152            indoc! {"
1153                fn main() {
1154                    let mut x = 0;
1155                    while x < 10 {
1156                        x += 1;
1157                    }
1158                }
1159            "}
1160        );
1161    }
1162
1163    #[gpui::test(iterations = 10)]
1164    async fn test_autoindent_when_generating_past_indentation(
1165        cx: &mut TestAppContext,
1166        mut rng: StdRng,
1167    ) {
1168        init_test(cx);
1169
1170        let text = indoc! {"
1171            fn main() {
1172                le
1173            }
1174        "};
1175        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
1176        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1177        let range = buffer.read_with(cx, |buffer, cx| {
1178            let snapshot = buffer.snapshot(cx);
1179            snapshot.anchor_before(Point::new(1, 6))..snapshot.anchor_after(Point::new(1, 6))
1180        });
1181        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
1182        let fs = FakeFs::new(cx.executor());
1183        let project = Project::test(fs, vec![], cx).await;
1184        let codegen = cx.new(|cx| {
1185            CodegenAlternative::new(
1186                buffer.clone(),
1187                range.clone(),
1188                true,
1189                None,
1190                project.downgrade(),
1191                None,
1192                None,
1193                prompt_builder,
1194                cx,
1195            )
1196        });
1197
1198        let chunks_tx = simulate_response_stream(&codegen, cx);
1199
1200        cx.background_executor.run_until_parked();
1201
1202        let mut new_text = concat!(
1203            "t mut x = 0;\n",
1204            "while x < 10 {\n",
1205            "    x += 1;\n",
1206            "}", //
1207        );
1208        while !new_text.is_empty() {
1209            let max_len = cmp::min(new_text.len(), 10);
1210            let len = rng.random_range(1..=max_len);
1211            let (chunk, suffix) = new_text.split_at(len);
1212            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
1213            new_text = suffix;
1214            cx.background_executor.run_until_parked();
1215        }
1216        drop(chunks_tx);
1217        cx.background_executor.run_until_parked();
1218
1219        assert_eq!(
1220            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
1221            indoc! {"
1222                fn main() {
1223                    let mut x = 0;
1224                    while x < 10 {
1225                        x += 1;
1226                    }
1227                }
1228            "}
1229        );
1230    }
1231
1232    #[gpui::test(iterations = 10)]
1233    async fn test_autoindent_when_generating_before_indentation(
1234        cx: &mut TestAppContext,
1235        mut rng: StdRng,
1236    ) {
1237        init_test(cx);
1238
1239        let text = concat!(
1240            "fn main() {\n",
1241            "  \n",
1242            "}\n" //
1243        );
1244        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
1245        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1246        let range = buffer.read_with(cx, |buffer, cx| {
1247            let snapshot = buffer.snapshot(cx);
1248            snapshot.anchor_before(Point::new(1, 2))..snapshot.anchor_after(Point::new(1, 2))
1249        });
1250        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
1251        let fs = FakeFs::new(cx.executor());
1252        let project = Project::test(fs, vec![], cx).await;
1253        let codegen = cx.new(|cx| {
1254            CodegenAlternative::new(
1255                buffer.clone(),
1256                range.clone(),
1257                true,
1258                None,
1259                project.downgrade(),
1260                None,
1261                None,
1262                prompt_builder,
1263                cx,
1264            )
1265        });
1266
1267        let chunks_tx = simulate_response_stream(&codegen, cx);
1268
1269        cx.background_executor.run_until_parked();
1270
1271        let mut new_text = concat!(
1272            "let mut x = 0;\n",
1273            "while x < 10 {\n",
1274            "    x += 1;\n",
1275            "}", //
1276        );
1277        while !new_text.is_empty() {
1278            let max_len = cmp::min(new_text.len(), 10);
1279            let len = rng.random_range(1..=max_len);
1280            let (chunk, suffix) = new_text.split_at(len);
1281            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
1282            new_text = suffix;
1283            cx.background_executor.run_until_parked();
1284        }
1285        drop(chunks_tx);
1286        cx.background_executor.run_until_parked();
1287
1288        assert_eq!(
1289            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
1290            indoc! {"
1291                fn main() {
1292                    let mut x = 0;
1293                    while x < 10 {
1294                        x += 1;
1295                    }
1296                }
1297            "}
1298        );
1299    }
1300
1301    #[gpui::test(iterations = 10)]
1302    async fn test_autoindent_respects_tabs_in_selection(cx: &mut TestAppContext) {
1303        init_test(cx);
1304
1305        let text = indoc! {"
1306            func main() {
1307            \tx := 0
1308            \tfor i := 0; i < 10; i++ {
1309            \t\tx++
1310            \t}
1311            }
1312        "};
1313        let buffer = cx.new(|cx| Buffer::local(text, cx));
1314        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1315        let range = buffer.read_with(cx, |buffer, cx| {
1316            let snapshot = buffer.snapshot(cx);
1317            snapshot.anchor_before(Point::new(0, 0))..snapshot.anchor_after(Point::new(4, 2))
1318        });
1319        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
1320        let fs = FakeFs::new(cx.executor());
1321        let project = Project::test(fs, vec![], cx).await;
1322        let codegen = cx.new(|cx| {
1323            CodegenAlternative::new(
1324                buffer.clone(),
1325                range.clone(),
1326                true,
1327                None,
1328                project.downgrade(),
1329                None,
1330                None,
1331                prompt_builder,
1332                cx,
1333            )
1334        });
1335
1336        let chunks_tx = simulate_response_stream(&codegen, cx);
1337        let new_text = concat!(
1338            "func main() {\n",
1339            "\tx := 0\n",
1340            "\tfor x < 10 {\n",
1341            "\t\tx++\n",
1342            "\t}", //
1343        );
1344        chunks_tx.unbounded_send(new_text.to_string()).unwrap();
1345        drop(chunks_tx);
1346        cx.background_executor.run_until_parked();
1347
1348        assert_eq!(
1349            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
1350            indoc! {"
1351                func main() {
1352                \tx := 0
1353                \tfor x < 10 {
1354                \t\tx++
1355                \t}
1356                }
1357            "}
1358        );
1359    }
1360
1361    #[gpui::test]
1362    async fn test_inactive_codegen_alternative(cx: &mut TestAppContext) {
1363        init_test(cx);
1364
1365        let text = indoc! {"
1366            fn main() {
1367                let x = 0;
1368            }
1369        "};
1370        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
1371        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1372        let range = buffer.read_with(cx, |buffer, cx| {
1373            let snapshot = buffer.snapshot(cx);
1374            snapshot.anchor_before(Point::new(1, 0))..snapshot.anchor_after(Point::new(1, 14))
1375        });
1376        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
1377        let fs = FakeFs::new(cx.executor());
1378        let project = Project::test(fs, vec![], cx).await;
1379        let codegen = cx.new(|cx| {
1380            CodegenAlternative::new(
1381                buffer.clone(),
1382                range.clone(),
1383                false,
1384                None,
1385                project.downgrade(),
1386                None,
1387                None,
1388                prompt_builder,
1389                cx,
1390            )
1391        });
1392
1393        let chunks_tx = simulate_response_stream(&codegen, cx);
1394        chunks_tx
1395            .unbounded_send("let mut x = 0;\nx += 1;".to_string())
1396            .unwrap();
1397        drop(chunks_tx);
1398        cx.run_until_parked();
1399
1400        // The codegen is inactive, so the buffer doesn't get modified.
1401        assert_eq!(
1402            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
1403            text
1404        );
1405
1406        // Activating the codegen applies the changes.
1407        codegen.update(cx, |codegen, cx| codegen.set_active(true, cx));
1408        assert_eq!(
1409            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
1410            indoc! {"
1411                fn main() {
1412                    let mut x = 0;
1413                    x += 1;
1414                }
1415            "}
1416        );
1417
1418        // Deactivating the codegen undoes the changes.
1419        codegen.update(cx, |codegen, cx| codegen.set_active(false, cx));
1420        cx.run_until_parked();
1421        assert_eq!(
1422            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
1423            text
1424        );
1425    }
1426
1427    #[gpui::test]
1428    async fn test_strip_invalid_spans_from_codeblock() {
1429        assert_chunks("Lorem ipsum dolor", "Lorem ipsum dolor").await;
1430        assert_chunks("```\nLorem ipsum dolor", "Lorem ipsum dolor").await;
1431        assert_chunks("```\nLorem ipsum dolor\n```", "Lorem ipsum dolor").await;
1432        assert_chunks(
1433            "```html\n```js\nLorem ipsum dolor\n```\n```",
1434            "```js\nLorem ipsum dolor\n```",
1435        )
1436        .await;
1437        assert_chunks("``\nLorem ipsum dolor\n```", "``\nLorem ipsum dolor\n```").await;
1438        assert_chunks("Lorem<|CURSOR|> ipsum", "Lorem ipsum").await;
1439        assert_chunks("Lorem ipsum", "Lorem ipsum").await;
1440        assert_chunks("```\n<|CURSOR|>Lorem ipsum\n```", "Lorem ipsum").await;
1441
1442        async fn assert_chunks(text: &str, expected_text: &str) {
1443            for chunk_size in 1..=text.len() {
1444                let actual_text = StripInvalidSpans::new(chunks(text, chunk_size))
1445                    .map(|chunk| chunk.unwrap())
1446                    .collect::<String>()
1447                    .await;
1448                assert_eq!(
1449                    actual_text, expected_text,
1450                    "failed to strip invalid spans, chunk size: {}",
1451                    chunk_size
1452                );
1453            }
1454        }
1455
1456        fn chunks(text: &str, size: usize) -> impl Stream<Item = Result<String>> {
1457            stream::iter(
1458                text.chars()
1459                    .collect::<Vec<_>>()
1460                    .chunks(size)
1461                    .map(|chunk| Ok(chunk.iter().collect::<String>()))
1462                    .collect::<Vec<_>>(),
1463            )
1464        }
1465    }
1466
1467    fn init_test(cx: &mut TestAppContext) {
1468        cx.update(LanguageModelRegistry::test);
1469        cx.set_global(cx.update(SettingsStore::test));
1470    }
1471
1472    fn simulate_response_stream(
1473        codegen: &Entity<CodegenAlternative>,
1474        cx: &mut TestAppContext,
1475    ) -> mpsc::UnboundedSender<String> {
1476        let (chunks_tx, chunks_rx) = mpsc::unbounded();
1477        codegen.update(cx, |codegen, cx| {
1478            codegen.handle_stream(
1479                String::new(),
1480                String::new(),
1481                None,
1482                future::ready(Ok(LanguageModelTextStream {
1483                    message_id: None,
1484                    stream: chunks_rx.map(Ok).boxed(),
1485                    last_token_usage: Arc::new(Mutex::new(TokenUsage::default())),
1486                })),
1487                cx,
1488            );
1489        });
1490        chunks_tx
1491    }
1492
1493    fn rust_lang() -> Language {
1494        Language::new(
1495            LanguageConfig {
1496                name: "Rust".into(),
1497                matcher: LanguageMatcher {
1498                    path_suffixes: vec!["rs".to_string()],
1499                    ..Default::default()
1500                },
1501                ..Default::default()
1502            },
1503            Some(tree_sitter_rust::LANGUAGE.into()),
1504        )
1505        .with_indents_query(
1506            r#"
1507            (call_expression) @indent
1508            (field_expression) @indent
1509            (_ "(" ")" @end) @indent
1510            (_ "{" "}" @end) @indent
1511            "#,
1512        )
1513        .unwrap()
1514    }
1515}