buffer_codegen.rs

   1use crate::inline_prompt_editor::CodegenStatus;
   2use agent::{
   3    ContextStore,
   4    context::{ContextLoadResult, load_context},
   5};
   6use agent_settings::AgentSettings;
   7use anyhow::{Context as _, Result};
   8use client::telemetry::Telemetry;
   9use cloud_llm_client::CompletionIntent;
  10use collections::HashSet;
  11use editor::{Anchor, AnchorRangeExt, MultiBuffer, MultiBufferSnapshot, ToOffset as _, ToPoint};
  12use futures::{
  13    SinkExt, Stream, StreamExt, TryStreamExt as _, channel::mpsc, future::LocalBoxFuture, join,
  14};
  15use gpui::{App, AppContext as _, Context, Entity, EventEmitter, Subscription, Task, WeakEntity};
  16use language::{Buffer, IndentKind, Point, TransactionId, line_diff};
  17use language_model::{
  18    LanguageModel, LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage,
  19    LanguageModelTextStream, Role, report_assistant_event,
  20};
  21use multi_buffer::MultiBufferRow;
  22use parking_lot::Mutex;
  23use project::Project;
  24use prompt_store::{PromptBuilder, PromptStore};
  25use rope::Rope;
  26use smol::future::FutureExt;
  27use std::{
  28    cmp,
  29    future::Future,
  30    iter,
  31    ops::{Range, RangeInclusive},
  32    pin::Pin,
  33    sync::Arc,
  34    task::{self, Poll},
  35    time::Instant,
  36};
  37use streaming_diff::{CharOperation, LineDiff, LineOperation, StreamingDiff};
  38use telemetry_events::{AssistantEventData, AssistantKind, AssistantPhase};
  39
  40pub struct BufferCodegen {
  41    alternatives: Vec<Entity<CodegenAlternative>>,
  42    pub active_alternative: usize,
  43    seen_alternatives: HashSet<usize>,
  44    subscriptions: Vec<Subscription>,
  45    buffer: Entity<MultiBuffer>,
  46    range: Range<Anchor>,
  47    initial_transaction_id: Option<TransactionId>,
  48    context_store: Entity<ContextStore>,
  49    project: WeakEntity<Project>,
  50    prompt_store: Option<Entity<PromptStore>>,
  51    telemetry: Arc<Telemetry>,
  52    builder: Arc<PromptBuilder>,
  53    pub is_insertion: bool,
  54}
  55
  56impl BufferCodegen {
  57    pub fn new(
  58        buffer: Entity<MultiBuffer>,
  59        range: Range<Anchor>,
  60        initial_transaction_id: Option<TransactionId>,
  61        context_store: Entity<ContextStore>,
  62        project: WeakEntity<Project>,
  63        prompt_store: Option<Entity<PromptStore>>,
  64        telemetry: Arc<Telemetry>,
  65        builder: Arc<PromptBuilder>,
  66        cx: &mut Context<Self>,
  67    ) -> Self {
  68        let codegen = cx.new(|cx| {
  69            CodegenAlternative::new(
  70                buffer.clone(),
  71                range.clone(),
  72                false,
  73                Some(context_store.clone()),
  74                project.clone(),
  75                prompt_store.clone(),
  76                Some(telemetry.clone()),
  77                builder.clone(),
  78                cx,
  79            )
  80        });
  81        let mut this = Self {
  82            is_insertion: range.to_offset(&buffer.read(cx).snapshot(cx)).is_empty(),
  83            alternatives: vec![codegen],
  84            active_alternative: 0,
  85            seen_alternatives: HashSet::default(),
  86            subscriptions: Vec::new(),
  87            buffer,
  88            range,
  89            initial_transaction_id,
  90            context_store,
  91            project,
  92            prompt_store,
  93            telemetry,
  94            builder,
  95        };
  96        this.activate(0, cx);
  97        this
  98    }
  99
 100    fn subscribe_to_alternative(&mut self, cx: &mut Context<Self>) {
 101        let codegen = self.active_alternative().clone();
 102        self.subscriptions.clear();
 103        self.subscriptions
 104            .push(cx.observe(&codegen, |_, _, cx| cx.notify()));
 105        self.subscriptions
 106            .push(cx.subscribe(&codegen, |_, _, event, cx| cx.emit(*event)));
 107    }
 108
 109    pub fn active_alternative(&self) -> &Entity<CodegenAlternative> {
 110        &self.alternatives[self.active_alternative]
 111    }
 112
 113    pub fn status<'a>(&self, cx: &'a App) -> &'a CodegenStatus {
 114        &self.active_alternative().read(cx).status
 115    }
 116
 117    pub fn alternative_count(&self, cx: &App) -> usize {
 118        LanguageModelRegistry::read_global(cx)
 119            .inline_alternative_models()
 120            .len()
 121            + 1
 122    }
 123
 124    pub fn cycle_prev(&mut self, cx: &mut Context<Self>) {
 125        let next_active_ix = if self.active_alternative == 0 {
 126            self.alternatives.len() - 1
 127        } else {
 128            self.active_alternative - 1
 129        };
 130        self.activate(next_active_ix, cx);
 131    }
 132
 133    pub fn cycle_next(&mut self, cx: &mut Context<Self>) {
 134        let next_active_ix = (self.active_alternative + 1) % self.alternatives.len();
 135        self.activate(next_active_ix, cx);
 136    }
 137
 138    fn activate(&mut self, index: usize, cx: &mut Context<Self>) {
 139        self.active_alternative()
 140            .update(cx, |codegen, cx| codegen.set_active(false, cx));
 141        self.seen_alternatives.insert(index);
 142        self.active_alternative = index;
 143        self.active_alternative()
 144            .update(cx, |codegen, cx| codegen.set_active(true, cx));
 145        self.subscribe_to_alternative(cx);
 146        cx.notify();
 147    }
 148
 149    pub fn start(
 150        &mut self,
 151        primary_model: Arc<dyn LanguageModel>,
 152        user_prompt: String,
 153        cx: &mut Context<Self>,
 154    ) -> Result<()> {
 155        let alternative_models = LanguageModelRegistry::read_global(cx)
 156            .inline_alternative_models()
 157            .to_vec();
 158
 159        self.active_alternative()
 160            .update(cx, |alternative, cx| alternative.undo(cx));
 161        self.activate(0, cx);
 162        self.alternatives.truncate(1);
 163
 164        for _ in 0..alternative_models.len() {
 165            self.alternatives.push(cx.new(|cx| {
 166                CodegenAlternative::new(
 167                    self.buffer.clone(),
 168                    self.range.clone(),
 169                    false,
 170                    Some(self.context_store.clone()),
 171                    self.project.clone(),
 172                    self.prompt_store.clone(),
 173                    Some(self.telemetry.clone()),
 174                    self.builder.clone(),
 175                    cx,
 176                )
 177            }));
 178        }
 179
 180        for (model, alternative) in iter::once(primary_model)
 181            .chain(alternative_models)
 182            .zip(&self.alternatives)
 183        {
 184            alternative.update(cx, |alternative, cx| {
 185                alternative.start(user_prompt.clone(), model.clone(), cx)
 186            })?;
 187        }
 188
 189        Ok(())
 190    }
 191
 192    pub fn stop(&mut self, cx: &mut Context<Self>) {
 193        for codegen in &self.alternatives {
 194            codegen.update(cx, |codegen, cx| codegen.stop(cx));
 195        }
 196    }
 197
 198    pub fn undo(&mut self, cx: &mut Context<Self>) {
 199        self.active_alternative()
 200            .update(cx, |codegen, cx| codegen.undo(cx));
 201
 202        self.buffer.update(cx, |buffer, cx| {
 203            if let Some(transaction_id) = self.initial_transaction_id.take() {
 204                buffer.undo_transaction(transaction_id, cx);
 205                buffer.refresh_preview(cx);
 206            }
 207        });
 208    }
 209
 210    pub fn buffer(&self, cx: &App) -> Entity<MultiBuffer> {
 211        self.active_alternative().read(cx).buffer.clone()
 212    }
 213
 214    pub fn old_buffer(&self, cx: &App) -> Entity<Buffer> {
 215        self.active_alternative().read(cx).old_buffer.clone()
 216    }
 217
 218    pub fn snapshot(&self, cx: &App) -> MultiBufferSnapshot {
 219        self.active_alternative().read(cx).snapshot.clone()
 220    }
 221
 222    pub fn edit_position(&self, cx: &App) -> Option<Anchor> {
 223        self.active_alternative().read(cx).edit_position
 224    }
 225
 226    pub fn diff<'a>(&self, cx: &'a App) -> &'a Diff {
 227        &self.active_alternative().read(cx).diff
 228    }
 229
 230    pub fn last_equal_ranges<'a>(&self, cx: &'a App) -> &'a [Range<Anchor>] {
 231        self.active_alternative().read(cx).last_equal_ranges()
 232    }
 233}
 234
 235impl EventEmitter<CodegenEvent> for BufferCodegen {}
 236
 237pub struct CodegenAlternative {
 238    buffer: Entity<MultiBuffer>,
 239    old_buffer: Entity<Buffer>,
 240    snapshot: MultiBufferSnapshot,
 241    edit_position: Option<Anchor>,
 242    range: Range<Anchor>,
 243    last_equal_ranges: Vec<Range<Anchor>>,
 244    transformation_transaction_id: Option<TransactionId>,
 245    status: CodegenStatus,
 246    generation: Task<()>,
 247    diff: Diff,
 248    context_store: Option<Entity<ContextStore>>,
 249    project: WeakEntity<Project>,
 250    prompt_store: Option<Entity<PromptStore>>,
 251    telemetry: Option<Arc<Telemetry>>,
 252    _subscription: gpui::Subscription,
 253    builder: Arc<PromptBuilder>,
 254    active: bool,
 255    edits: Vec<(Range<Anchor>, String)>,
 256    line_operations: Vec<LineOperation>,
 257    elapsed_time: Option<f64>,
 258    completion: Option<String>,
 259    pub message_id: Option<String>,
 260}
 261
 262impl EventEmitter<CodegenEvent> for CodegenAlternative {}
 263
 264impl CodegenAlternative {
 265    pub fn new(
 266        buffer: Entity<MultiBuffer>,
 267        range: Range<Anchor>,
 268        active: bool,
 269        context_store: Option<Entity<ContextStore>>,
 270        project: WeakEntity<Project>,
 271        prompt_store: Option<Entity<PromptStore>>,
 272        telemetry: Option<Arc<Telemetry>>,
 273        builder: Arc<PromptBuilder>,
 274        cx: &mut Context<Self>,
 275    ) -> Self {
 276        let snapshot = buffer.read(cx).snapshot(cx);
 277
 278        let (old_buffer, _, _) = snapshot
 279            .range_to_buffer_ranges(range.clone())
 280            .pop()
 281            .unwrap();
 282        let old_buffer = cx.new(|cx| {
 283            let text = old_buffer.as_rope().clone();
 284            let line_ending = old_buffer.line_ending();
 285            let language = old_buffer.language().cloned();
 286            let language_registry = buffer
 287                .read(cx)
 288                .buffer(old_buffer.remote_id())
 289                .unwrap()
 290                .read(cx)
 291                .language_registry();
 292
 293            let mut buffer = Buffer::local_normalized(text, line_ending, cx);
 294            buffer.set_language(language, cx);
 295            if let Some(language_registry) = language_registry {
 296                buffer.set_language_registry(language_registry)
 297            }
 298            buffer
 299        });
 300
 301        Self {
 302            buffer: buffer.clone(),
 303            old_buffer,
 304            edit_position: None,
 305            message_id: None,
 306            snapshot,
 307            last_equal_ranges: Default::default(),
 308            transformation_transaction_id: None,
 309            status: CodegenStatus::Idle,
 310            generation: Task::ready(()),
 311            diff: Diff::default(),
 312            context_store,
 313            project,
 314            prompt_store,
 315            telemetry,
 316            _subscription: cx.subscribe(&buffer, Self::handle_buffer_event),
 317            builder,
 318            active,
 319            edits: Vec::new(),
 320            line_operations: Vec::new(),
 321            range,
 322            elapsed_time: None,
 323            completion: None,
 324        }
 325    }
 326
 327    pub fn set_active(&mut self, active: bool, cx: &mut Context<Self>) {
 328        if active != self.active {
 329            self.active = active;
 330
 331            if self.active {
 332                let edits = self.edits.clone();
 333                self.apply_edits(edits, cx);
 334                if matches!(self.status, CodegenStatus::Pending) {
 335                    let line_operations = self.line_operations.clone();
 336                    self.reapply_line_based_diff(line_operations, cx);
 337                } else {
 338                    self.reapply_batch_diff(cx).detach();
 339                }
 340            } else if let Some(transaction_id) = self.transformation_transaction_id.take() {
 341                self.buffer.update(cx, |buffer, cx| {
 342                    buffer.undo_transaction(transaction_id, cx);
 343                    buffer.forget_transaction(transaction_id, cx);
 344                });
 345            }
 346        }
 347    }
 348
 349    fn handle_buffer_event(
 350        &mut self,
 351        _buffer: Entity<MultiBuffer>,
 352        event: &multi_buffer::Event,
 353        cx: &mut Context<Self>,
 354    ) {
 355        if let multi_buffer::Event::TransactionUndone { transaction_id } = event
 356            && self.transformation_transaction_id == Some(*transaction_id) {
 357                self.transformation_transaction_id = None;
 358                self.generation = Task::ready(());
 359                cx.emit(CodegenEvent::Undone);
 360            }
 361    }
 362
 363    pub fn last_equal_ranges(&self) -> &[Range<Anchor>] {
 364        &self.last_equal_ranges
 365    }
 366
 367    pub fn start(
 368        &mut self,
 369        user_prompt: String,
 370        model: Arc<dyn LanguageModel>,
 371        cx: &mut Context<Self>,
 372    ) -> Result<()> {
 373        if let Some(transformation_transaction_id) = self.transformation_transaction_id.take() {
 374            self.buffer.update(cx, |buffer, cx| {
 375                buffer.undo_transaction(transformation_transaction_id, cx);
 376            });
 377        }
 378
 379        self.edit_position = Some(self.range.start.bias_right(&self.snapshot));
 380
 381        let api_key = model.api_key(cx);
 382        let telemetry_id = model.telemetry_id();
 383        let provider_id = model.provider_id();
 384        let stream: LocalBoxFuture<Result<LanguageModelTextStream>> =
 385            if user_prompt.trim().to_lowercase() == "delete" {
 386                async { Ok(LanguageModelTextStream::default()) }.boxed_local()
 387            } else {
 388                let request = self.build_request(&model, user_prompt, cx)?;
 389                cx.spawn(async move |_, cx| {
 390                    Ok(model.stream_completion_text(request.await, cx).await?)
 391                })
 392                .boxed_local()
 393            };
 394        self.handle_stream(telemetry_id, provider_id.to_string(), api_key, stream, cx);
 395        Ok(())
 396    }
 397
 398    fn build_request(
 399        &self,
 400        model: &Arc<dyn LanguageModel>,
 401        user_prompt: String,
 402        cx: &mut App,
 403    ) -> Result<Task<LanguageModelRequest>> {
 404        let buffer = self.buffer.read(cx).snapshot(cx);
 405        let language = buffer.language_at(self.range.start);
 406        let language_name = if let Some(language) = language.as_ref() {
 407            if Arc::ptr_eq(language, &language::PLAIN_TEXT) {
 408                None
 409            } else {
 410                Some(language.name())
 411            }
 412        } else {
 413            None
 414        };
 415
 416        let language_name = language_name.as_ref();
 417        let start = buffer.point_to_buffer_offset(self.range.start);
 418        let end = buffer.point_to_buffer_offset(self.range.end);
 419        let (buffer, range) = if let Some((start, end)) = start.zip(end) {
 420            let (start_buffer, start_buffer_offset) = start;
 421            let (end_buffer, end_buffer_offset) = end;
 422            if start_buffer.remote_id() == end_buffer.remote_id() {
 423                (start_buffer.clone(), start_buffer_offset..end_buffer_offset)
 424            } else {
 425                anyhow::bail!("invalid transformation range");
 426            }
 427        } else {
 428            anyhow::bail!("invalid transformation range");
 429        };
 430
 431        let prompt = self
 432            .builder
 433            .generate_inline_transformation_prompt(user_prompt, language_name, buffer, range)
 434            .context("generating content prompt")?;
 435
 436        let context_task = self.context_store.as_ref().map(|context_store| {
 437            if let Some(project) = self.project.upgrade() {
 438                let context = context_store
 439                    .read(cx)
 440                    .context()
 441                    .cloned()
 442                    .collect::<Vec<_>>();
 443                load_context(context, &project, &self.prompt_store, cx)
 444            } else {
 445                Task::ready(ContextLoadResult::default())
 446            }
 447        });
 448
 449        let temperature = AgentSettings::temperature_for_model(model, cx);
 450
 451        Ok(cx.spawn(async move |_cx| {
 452            let mut request_message = LanguageModelRequestMessage {
 453                role: Role::User,
 454                content: Vec::new(),
 455                cache: false,
 456            };
 457
 458            if let Some(context_task) = context_task {
 459                context_task
 460                    .await
 461                    .loaded_context
 462                    .add_to_request_message(&mut request_message);
 463            }
 464
 465            request_message.content.push(prompt.into());
 466
 467            LanguageModelRequest {
 468                thread_id: None,
 469                prompt_id: None,
 470                intent: Some(CompletionIntent::InlineAssist),
 471                mode: None,
 472                tools: Vec::new(),
 473                tool_choice: None,
 474                stop: Vec::new(),
 475                temperature,
 476                messages: vec![request_message],
 477                thinking_allowed: false,
 478            }
 479        }))
 480    }
 481
 482    pub fn handle_stream(
 483        &mut self,
 484        model_telemetry_id: String,
 485        model_provider_id: String,
 486        model_api_key: Option<String>,
 487        stream: impl 'static + Future<Output = Result<LanguageModelTextStream>>,
 488        cx: &mut Context<Self>,
 489    ) {
 490        let start_time = Instant::now();
 491        let snapshot = self.snapshot.clone();
 492        let selected_text = snapshot
 493            .text_for_range(self.range.start..self.range.end)
 494            .collect::<Rope>();
 495
 496        let selection_start = self.range.start.to_point(&snapshot);
 497
 498        // Start with the indentation of the first line in the selection
 499        let mut suggested_line_indent = snapshot
 500            .suggested_indents(selection_start.row..=selection_start.row, cx)
 501            .into_values()
 502            .next()
 503            .unwrap_or_else(|| snapshot.indent_size_for_line(MultiBufferRow(selection_start.row)));
 504
 505        // If the first line in the selection does not have indentation, check the following lines
 506        if suggested_line_indent.len == 0 && suggested_line_indent.kind == IndentKind::Space {
 507            for row in selection_start.row..=self.range.end.to_point(&snapshot).row {
 508                let line_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 509                // Prefer tabs if a line in the selection uses tabs as indentation
 510                if line_indent.kind == IndentKind::Tab {
 511                    suggested_line_indent.kind = IndentKind::Tab;
 512                    break;
 513                }
 514            }
 515        }
 516
 517        let http_client = cx.http_client();
 518        let telemetry = self.telemetry.clone();
 519        let language_name = {
 520            let multibuffer = self.buffer.read(cx);
 521            let snapshot = multibuffer.snapshot(cx);
 522            let ranges = snapshot.range_to_buffer_ranges(self.range.clone());
 523            ranges
 524                .first()
 525                .and_then(|(buffer, _, _)| buffer.language())
 526                .map(|language| language.name())
 527        };
 528
 529        self.diff = Diff::default();
 530        self.status = CodegenStatus::Pending;
 531        let mut edit_start = self.range.start.to_offset(&snapshot);
 532        let completion = Arc::new(Mutex::new(String::new()));
 533        let completion_clone = completion.clone();
 534
 535        self.generation = cx.spawn(async move |codegen, cx| {
 536            let stream = stream.await;
 537            let token_usage = stream
 538                .as_ref()
 539                .ok()
 540                .map(|stream| stream.last_token_usage.clone());
 541            let message_id = stream
 542                .as_ref()
 543                .ok()
 544                .and_then(|stream| stream.message_id.clone());
 545            let generate = async {
 546                let model_telemetry_id = model_telemetry_id.clone();
 547                let model_provider_id = model_provider_id.clone();
 548                let (mut diff_tx, mut diff_rx) = mpsc::channel(1);
 549                let executor = cx.background_executor().clone();
 550                let message_id = message_id.clone();
 551                let line_based_stream_diff: Task<anyhow::Result<()>> =
 552                    cx.background_spawn(async move {
 553                        let mut response_latency = None;
 554                        let request_start = Instant::now();
 555                        let diff = async {
 556                            let chunks = StripInvalidSpans::new(
 557                                stream?.stream.map_err(|error| error.into()),
 558                            );
 559                            futures::pin_mut!(chunks);
 560                            let mut diff = StreamingDiff::new(selected_text.to_string());
 561                            let mut line_diff = LineDiff::default();
 562
 563                            let mut new_text = String::new();
 564                            let mut base_indent = None;
 565                            let mut line_indent = None;
 566                            let mut first_line = true;
 567
 568                            while let Some(chunk) = chunks.next().await {
 569                                if response_latency.is_none() {
 570                                    response_latency = Some(request_start.elapsed());
 571                                }
 572                                let chunk = chunk?;
 573                                completion_clone.lock().push_str(&chunk);
 574
 575                                let mut lines = chunk.split('\n').peekable();
 576                                while let Some(line) = lines.next() {
 577                                    new_text.push_str(line);
 578                                    if line_indent.is_none()
 579                                        && let Some(non_whitespace_ch_ix) =
 580                                            new_text.find(|ch: char| !ch.is_whitespace())
 581                                        {
 582                                            line_indent = Some(non_whitespace_ch_ix);
 583                                            base_indent = base_indent.or(line_indent);
 584
 585                                            let line_indent = line_indent.unwrap();
 586                                            let base_indent = base_indent.unwrap();
 587                                            let indent_delta =
 588                                                line_indent as i32 - base_indent as i32;
 589                                            let mut corrected_indent_len = cmp::max(
 590                                                0,
 591                                                suggested_line_indent.len as i32 + indent_delta,
 592                                            )
 593                                                as usize;
 594                                            if first_line {
 595                                                corrected_indent_len = corrected_indent_len
 596                                                    .saturating_sub(
 597                                                        selection_start.column as usize,
 598                                                    );
 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::{
1091        Buffer, Language, LanguageConfig, LanguageMatcher, Point, language_settings,
1092        tree_sitter_rust,
1093    };
1094    use language_model::{LanguageModelRegistry, TokenUsage};
1095    use rand::prelude::*;
1096    use settings::SettingsStore;
1097    use std::{future, sync::Arc};
1098
1099    #[gpui::test(iterations = 10)]
1100    async fn test_transform_autoindent(cx: &mut TestAppContext, mut rng: StdRng) {
1101        init_test(cx);
1102
1103        let text = indoc! {"
1104            fn main() {
1105                let x = 0;
1106                for _ in 0..10 {
1107                    x += 1;
1108                }
1109            }
1110        "};
1111        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
1112        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1113        let range = buffer.read_with(cx, |buffer, cx| {
1114            let snapshot = buffer.snapshot(cx);
1115            snapshot.anchor_before(Point::new(1, 0))..snapshot.anchor_after(Point::new(4, 5))
1116        });
1117        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
1118        let fs = FakeFs::new(cx.executor());
1119        let project = Project::test(fs, vec![], cx).await;
1120        let codegen = cx.new(|cx| {
1121            CodegenAlternative::new(
1122                buffer.clone(),
1123                range.clone(),
1124                true,
1125                None,
1126                project.downgrade(),
1127                None,
1128                None,
1129                prompt_builder,
1130                cx,
1131            )
1132        });
1133
1134        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
1135
1136        let mut new_text = concat!(
1137            "       let mut x = 0;\n",
1138            "       while x < 10 {\n",
1139            "           x += 1;\n",
1140            "       }",
1141        );
1142        while !new_text.is_empty() {
1143            let max_len = cmp::min(new_text.len(), 10);
1144            let len = rng.gen_range(1..=max_len);
1145            let (chunk, suffix) = new_text.split_at(len);
1146            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
1147            new_text = suffix;
1148            cx.background_executor.run_until_parked();
1149        }
1150        drop(chunks_tx);
1151        cx.background_executor.run_until_parked();
1152
1153        assert_eq!(
1154            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
1155            indoc! {"
1156                fn main() {
1157                    let mut x = 0;
1158                    while x < 10 {
1159                        x += 1;
1160                    }
1161                }
1162            "}
1163        );
1164    }
1165
1166    #[gpui::test(iterations = 10)]
1167    async fn test_autoindent_when_generating_past_indentation(
1168        cx: &mut TestAppContext,
1169        mut rng: StdRng,
1170    ) {
1171        init_test(cx);
1172
1173        let text = indoc! {"
1174            fn main() {
1175                le
1176            }
1177        "};
1178        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
1179        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1180        let range = buffer.read_with(cx, |buffer, cx| {
1181            let snapshot = buffer.snapshot(cx);
1182            snapshot.anchor_before(Point::new(1, 6))..snapshot.anchor_after(Point::new(1, 6))
1183        });
1184        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
1185        let fs = FakeFs::new(cx.executor());
1186        let project = Project::test(fs, vec![], cx).await;
1187        let codegen = cx.new(|cx| {
1188            CodegenAlternative::new(
1189                buffer.clone(),
1190                range.clone(),
1191                true,
1192                None,
1193                project.downgrade(),
1194                None,
1195                None,
1196                prompt_builder,
1197                cx,
1198            )
1199        });
1200
1201        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
1202
1203        cx.background_executor.run_until_parked();
1204
1205        let mut new_text = concat!(
1206            "t mut x = 0;\n",
1207            "while x < 10 {\n",
1208            "    x += 1;\n",
1209            "}", //
1210        );
1211        while !new_text.is_empty() {
1212            let max_len = cmp::min(new_text.len(), 10);
1213            let len = rng.gen_range(1..=max_len);
1214            let (chunk, suffix) = new_text.split_at(len);
1215            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
1216            new_text = suffix;
1217            cx.background_executor.run_until_parked();
1218        }
1219        drop(chunks_tx);
1220        cx.background_executor.run_until_parked();
1221
1222        assert_eq!(
1223            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
1224            indoc! {"
1225                fn main() {
1226                    let mut x = 0;
1227                    while x < 10 {
1228                        x += 1;
1229                    }
1230                }
1231            "}
1232        );
1233    }
1234
1235    #[gpui::test(iterations = 10)]
1236    async fn test_autoindent_when_generating_before_indentation(
1237        cx: &mut TestAppContext,
1238        mut rng: StdRng,
1239    ) {
1240        init_test(cx);
1241
1242        let text = concat!(
1243            "fn main() {\n",
1244            "  \n",
1245            "}\n" //
1246        );
1247        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
1248        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1249        let range = buffer.read_with(cx, |buffer, cx| {
1250            let snapshot = buffer.snapshot(cx);
1251            snapshot.anchor_before(Point::new(1, 2))..snapshot.anchor_after(Point::new(1, 2))
1252        });
1253        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
1254        let fs = FakeFs::new(cx.executor());
1255        let project = Project::test(fs, vec![], cx).await;
1256        let codegen = cx.new(|cx| {
1257            CodegenAlternative::new(
1258                buffer.clone(),
1259                range.clone(),
1260                true,
1261                None,
1262                project.downgrade(),
1263                None,
1264                None,
1265                prompt_builder,
1266                cx,
1267            )
1268        });
1269
1270        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
1271
1272        cx.background_executor.run_until_parked();
1273
1274        let mut new_text = concat!(
1275            "let mut x = 0;\n",
1276            "while x < 10 {\n",
1277            "    x += 1;\n",
1278            "}", //
1279        );
1280        while !new_text.is_empty() {
1281            let max_len = cmp::min(new_text.len(), 10);
1282            let len = rng.gen_range(1..=max_len);
1283            let (chunk, suffix) = new_text.split_at(len);
1284            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
1285            new_text = suffix;
1286            cx.background_executor.run_until_parked();
1287        }
1288        drop(chunks_tx);
1289        cx.background_executor.run_until_parked();
1290
1291        assert_eq!(
1292            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
1293            indoc! {"
1294                fn main() {
1295                    let mut x = 0;
1296                    while x < 10 {
1297                        x += 1;
1298                    }
1299                }
1300            "}
1301        );
1302    }
1303
1304    #[gpui::test(iterations = 10)]
1305    async fn test_autoindent_respects_tabs_in_selection(cx: &mut TestAppContext) {
1306        init_test(cx);
1307
1308        let text = indoc! {"
1309            func main() {
1310            \tx := 0
1311            \tfor i := 0; i < 10; i++ {
1312            \t\tx++
1313            \t}
1314            }
1315        "};
1316        let buffer = cx.new(|cx| Buffer::local(text, cx));
1317        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1318        let range = buffer.read_with(cx, |buffer, cx| {
1319            let snapshot = buffer.snapshot(cx);
1320            snapshot.anchor_before(Point::new(0, 0))..snapshot.anchor_after(Point::new(4, 2))
1321        });
1322        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
1323        let fs = FakeFs::new(cx.executor());
1324        let project = Project::test(fs, vec![], cx).await;
1325        let codegen = cx.new(|cx| {
1326            CodegenAlternative::new(
1327                buffer.clone(),
1328                range.clone(),
1329                true,
1330                None,
1331                project.downgrade(),
1332                None,
1333                None,
1334                prompt_builder,
1335                cx,
1336            )
1337        });
1338
1339        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
1340        let new_text = concat!(
1341            "func main() {\n",
1342            "\tx := 0\n",
1343            "\tfor x < 10 {\n",
1344            "\t\tx++\n",
1345            "\t}", //
1346        );
1347        chunks_tx.unbounded_send(new_text.to_string()).unwrap();
1348        drop(chunks_tx);
1349        cx.background_executor.run_until_parked();
1350
1351        assert_eq!(
1352            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
1353            indoc! {"
1354                func main() {
1355                \tx := 0
1356                \tfor x < 10 {
1357                \t\tx++
1358                \t}
1359                }
1360            "}
1361        );
1362    }
1363
1364    #[gpui::test]
1365    async fn test_inactive_codegen_alternative(cx: &mut TestAppContext) {
1366        init_test(cx);
1367
1368        let text = indoc! {"
1369            fn main() {
1370                let x = 0;
1371            }
1372        "};
1373        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
1374        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1375        let range = buffer.read_with(cx, |buffer, cx| {
1376            let snapshot = buffer.snapshot(cx);
1377            snapshot.anchor_before(Point::new(1, 0))..snapshot.anchor_after(Point::new(1, 14))
1378        });
1379        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
1380        let fs = FakeFs::new(cx.executor());
1381        let project = Project::test(fs, vec![], cx).await;
1382        let codegen = cx.new(|cx| {
1383            CodegenAlternative::new(
1384                buffer.clone(),
1385                range.clone(),
1386                false,
1387                None,
1388                project.downgrade(),
1389                None,
1390                None,
1391                prompt_builder,
1392                cx,
1393            )
1394        });
1395
1396        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
1397        chunks_tx
1398            .unbounded_send("let mut x = 0;\nx += 1;".to_string())
1399            .unwrap();
1400        drop(chunks_tx);
1401        cx.run_until_parked();
1402
1403        // The codegen is inactive, so the buffer doesn't get modified.
1404        assert_eq!(
1405            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
1406            text
1407        );
1408
1409        // Activating the codegen applies the changes.
1410        codegen.update(cx, |codegen, cx| codegen.set_active(true, cx));
1411        assert_eq!(
1412            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
1413            indoc! {"
1414                fn main() {
1415                    let mut x = 0;
1416                    x += 1;
1417                }
1418            "}
1419        );
1420
1421        // Deactivating the codegen undoes the changes.
1422        codegen.update(cx, |codegen, cx| codegen.set_active(false, cx));
1423        cx.run_until_parked();
1424        assert_eq!(
1425            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
1426            text
1427        );
1428    }
1429
1430    #[gpui::test]
1431    async fn test_strip_invalid_spans_from_codeblock() {
1432        assert_chunks("Lorem ipsum dolor", "Lorem ipsum dolor").await;
1433        assert_chunks("```\nLorem ipsum dolor", "Lorem ipsum dolor").await;
1434        assert_chunks("```\nLorem ipsum dolor\n```", "Lorem ipsum dolor").await;
1435        assert_chunks(
1436            "```html\n```js\nLorem ipsum dolor\n```\n```",
1437            "```js\nLorem ipsum dolor\n```",
1438        )
1439        .await;
1440        assert_chunks("``\nLorem ipsum dolor\n```", "``\nLorem ipsum dolor\n```").await;
1441        assert_chunks("Lorem<|CURSOR|> ipsum", "Lorem ipsum").await;
1442        assert_chunks("Lorem ipsum", "Lorem ipsum").await;
1443        assert_chunks("```\n<|CURSOR|>Lorem ipsum\n```", "Lorem ipsum").await;
1444
1445        async fn assert_chunks(text: &str, expected_text: &str) {
1446            for chunk_size in 1..=text.len() {
1447                let actual_text = StripInvalidSpans::new(chunks(text, chunk_size))
1448                    .map(|chunk| chunk.unwrap())
1449                    .collect::<String>()
1450                    .await;
1451                assert_eq!(
1452                    actual_text, expected_text,
1453                    "failed to strip invalid spans, chunk size: {}",
1454                    chunk_size
1455                );
1456            }
1457        }
1458
1459        fn chunks(text: &str, size: usize) -> impl Stream<Item = Result<String>> {
1460            stream::iter(
1461                text.chars()
1462                    .collect::<Vec<_>>()
1463                    .chunks(size)
1464                    .map(|chunk| Ok(chunk.iter().collect::<String>()))
1465                    .collect::<Vec<_>>(),
1466            )
1467        }
1468    }
1469
1470    fn init_test(cx: &mut TestAppContext) {
1471        cx.update(LanguageModelRegistry::test);
1472        cx.set_global(cx.update(SettingsStore::test));
1473        cx.update(Project::init_settings);
1474        cx.update(language_settings::init);
1475    }
1476
1477    fn simulate_response_stream(
1478        codegen: Entity<CodegenAlternative>,
1479        cx: &mut TestAppContext,
1480    ) -> mpsc::UnboundedSender<String> {
1481        let (chunks_tx, chunks_rx) = mpsc::unbounded();
1482        codegen.update(cx, |codegen, cx| {
1483            codegen.handle_stream(
1484                String::new(),
1485                String::new(),
1486                None,
1487                future::ready(Ok(LanguageModelTextStream {
1488                    message_id: None,
1489                    stream: chunks_rx.map(Ok).boxed(),
1490                    last_token_usage: Arc::new(Mutex::new(TokenUsage::default())),
1491                })),
1492                cx,
1493            );
1494        });
1495        chunks_tx
1496    }
1497
1498    fn rust_lang() -> Language {
1499        Language::new(
1500            LanguageConfig {
1501                name: "Rust".into(),
1502                matcher: LanguageMatcher {
1503                    path_suffixes: vec!["rs".to_string()],
1504                    ..Default::default()
1505                },
1506                ..Default::default()
1507            },
1508            Some(tree_sitter_rust::LANGUAGE.into()),
1509        )
1510        .with_indents_query(
1511            r#"
1512            (call_expression) @indent
1513            (field_expression) @indent
1514            (_ "(" ")" @end) @indent
1515            (_ "{" "}" @end) @indent
1516            "#,
1517        )
1518        .unwrap()
1519    }
1520}