buffer_codegen.rs

   1use crate::context::ContextLoadResult;
   2use crate::inline_prompt_editor::CodegenStatus;
   3use crate::{context::load_context, context_store::ContextStore};
   4use agent_settings::AgentSettings;
   5use anyhow::{Context as _, Result};
   6use client::telemetry::Telemetry;
   7use collections::HashSet;
   8use editor::{Anchor, AnchorRangeExt, MultiBuffer, MultiBufferSnapshot, ToOffset as _, ToPoint};
   9use futures::{
  10    SinkExt, Stream, StreamExt, TryStreamExt as _, channel::mpsc, future::LocalBoxFuture, join,
  11};
  12use gpui::{App, AppContext as _, Context, Entity, EventEmitter, Subscription, Task, WeakEntity};
  13use language::{Buffer, IndentKind, Point, TransactionId, line_diff};
  14use language_model::{
  15    LanguageModel, LanguageModelRegistry, LanguageModelRequest, LanguageModelRequestMessage,
  16    LanguageModelTextStream, Role, report_assistant_event,
  17};
  18use multi_buffer::MultiBufferRow;
  19use parking_lot::Mutex;
  20use project::Project;
  21use prompt_store::PromptBuilder;
  22use prompt_store::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            if self.transformation_transaction_id == Some(*transaction_id) {
 355                self.transformation_transaction_id = None;
 356                self.generation = Task::ready(());
 357                cx.emit(CodegenEvent::Undone);
 358            }
 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| model.stream_completion_text(request.await, &cx).await)
 389                    .boxed_local()
 390            };
 391        self.handle_stream(telemetry_id, provider_id.to_string(), api_key, stream, cx);
 392        Ok(())
 393    }
 394
 395    fn build_request(
 396        &self,
 397        model: &Arc<dyn LanguageModel>,
 398        user_prompt: String,
 399        cx: &mut App,
 400    ) -> Result<Task<LanguageModelRequest>> {
 401        let buffer = self.buffer.read(cx).snapshot(cx);
 402        let language = buffer.language_at(self.range.start);
 403        let language_name = if let Some(language) = language.as_ref() {
 404            if Arc::ptr_eq(language, &language::PLAIN_TEXT) {
 405                None
 406            } else {
 407                Some(language.name())
 408            }
 409        } else {
 410            None
 411        };
 412
 413        let language_name = language_name.as_ref();
 414        let start = buffer.point_to_buffer_offset(self.range.start);
 415        let end = buffer.point_to_buffer_offset(self.range.end);
 416        let (buffer, range) = if let Some((start, end)) = start.zip(end) {
 417            let (start_buffer, start_buffer_offset) = start;
 418            let (end_buffer, end_buffer_offset) = end;
 419            if start_buffer.remote_id() == end_buffer.remote_id() {
 420                (start_buffer.clone(), start_buffer_offset..end_buffer_offset)
 421            } else {
 422                anyhow::bail!("invalid transformation range");
 423            }
 424        } else {
 425            anyhow::bail!("invalid transformation range");
 426        };
 427
 428        let prompt = self
 429            .builder
 430            .generate_inline_transformation_prompt(user_prompt, language_name, buffer, range)
 431            .context("generating content prompt")?;
 432
 433        let context_task = self.context_store.as_ref().map(|context_store| {
 434            if let Some(project) = self.project.upgrade() {
 435                let context = context_store
 436                    .read(cx)
 437                    .context()
 438                    .cloned()
 439                    .collect::<Vec<_>>();
 440                load_context(context, &project, &self.prompt_store, cx)
 441            } else {
 442                Task::ready(ContextLoadResult::default())
 443            }
 444        });
 445
 446        let temperature = AgentSettings::temperature_for_model(&model, cx);
 447
 448        Ok(cx.spawn(async move |_cx| {
 449            let mut request_message = LanguageModelRequestMessage {
 450                role: Role::User,
 451                content: Vec::new(),
 452                cache: false,
 453            };
 454
 455            if let Some(context_task) = context_task {
 456                context_task
 457                    .await
 458                    .loaded_context
 459                    .add_to_request_message(&mut request_message);
 460            }
 461
 462            request_message.content.push(prompt.into());
 463
 464            LanguageModelRequest {
 465                thread_id: None,
 466                prompt_id: None,
 467                mode: None,
 468                tools: Vec::new(),
 469                tool_choice: None,
 470                stop: Vec::new(),
 471                temperature,
 472                messages: vec![request_message],
 473            }
 474        }))
 475    }
 476
 477    pub fn handle_stream(
 478        &mut self,
 479        model_telemetry_id: String,
 480        model_provider_id: String,
 481        model_api_key: Option<String>,
 482        stream: impl 'static + Future<Output = Result<LanguageModelTextStream>>,
 483        cx: &mut Context<Self>,
 484    ) {
 485        let start_time = Instant::now();
 486        let snapshot = self.snapshot.clone();
 487        let selected_text = snapshot
 488            .text_for_range(self.range.start..self.range.end)
 489            .collect::<Rope>();
 490
 491        let selection_start = self.range.start.to_point(&snapshot);
 492
 493        // Start with the indentation of the first line in the selection
 494        let mut suggested_line_indent = snapshot
 495            .suggested_indents(selection_start.row..=selection_start.row, cx)
 496            .into_values()
 497            .next()
 498            .unwrap_or_else(|| snapshot.indent_size_for_line(MultiBufferRow(selection_start.row)));
 499
 500        // If the first line in the selection does not have indentation, check the following lines
 501        if suggested_line_indent.len == 0 && suggested_line_indent.kind == IndentKind::Space {
 502            for row in selection_start.row..=self.range.end.to_point(&snapshot).row {
 503                let line_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
 504                // Prefer tabs if a line in the selection uses tabs as indentation
 505                if line_indent.kind == IndentKind::Tab {
 506                    suggested_line_indent.kind = IndentKind::Tab;
 507                    break;
 508                }
 509            }
 510        }
 511
 512        let http_client = cx.http_client();
 513        let telemetry = self.telemetry.clone();
 514        let language_name = {
 515            let multibuffer = self.buffer.read(cx);
 516            let snapshot = multibuffer.snapshot(cx);
 517            let ranges = snapshot.range_to_buffer_ranges(self.range.clone());
 518            ranges
 519                .first()
 520                .and_then(|(buffer, _, _)| buffer.language())
 521                .map(|language| language.name())
 522        };
 523
 524        self.diff = Diff::default();
 525        self.status = CodegenStatus::Pending;
 526        let mut edit_start = self.range.start.to_offset(&snapshot);
 527        let completion = Arc::new(Mutex::new(String::new()));
 528        let completion_clone = completion.clone();
 529
 530        self.generation = cx.spawn(async move |codegen, cx| {
 531            let stream = stream.await;
 532            let token_usage = stream
 533                .as_ref()
 534                .ok()
 535                .map(|stream| stream.last_token_usage.clone());
 536            let message_id = stream
 537                .as_ref()
 538                .ok()
 539                .and_then(|stream| stream.message_id.clone());
 540            let generate = async {
 541                let model_telemetry_id = model_telemetry_id.clone();
 542                let model_provider_id = model_provider_id.clone();
 543                let (mut diff_tx, mut diff_rx) = mpsc::channel(1);
 544                let executor = cx.background_executor().clone();
 545                let message_id = message_id.clone();
 546                let line_based_stream_diff: Task<anyhow::Result<()>> =
 547                    cx.background_spawn(async move {
 548                        let mut response_latency = None;
 549                        let request_start = Instant::now();
 550                        let diff = async {
 551                            let chunks = StripInvalidSpans::new(
 552                                stream?.stream.map_err(|error| error.into()),
 553                            );
 554                            futures::pin_mut!(chunks);
 555                            let mut diff = StreamingDiff::new(selected_text.to_string());
 556                            let mut line_diff = LineDiff::default();
 557
 558                            let mut new_text = String::new();
 559                            let mut base_indent = None;
 560                            let mut line_indent = None;
 561                            let mut first_line = true;
 562
 563                            while let Some(chunk) = chunks.next().await {
 564                                if response_latency.is_none() {
 565                                    response_latency = Some(request_start.elapsed());
 566                                }
 567                                let chunk = chunk?;
 568                                completion_clone.lock().push_str(&chunk);
 569
 570                                let mut lines = chunk.split('\n').peekable();
 571                                while let Some(line) = lines.next() {
 572                                    new_text.push_str(line);
 573                                    if line_indent.is_none() {
 574                                        if let Some(non_whitespace_ch_ix) =
 575                                            new_text.find(|ch: char| !ch.is_whitespace())
 576                                        {
 577                                            line_indent = Some(non_whitespace_ch_ix);
 578                                            base_indent = base_indent.or(line_indent);
 579
 580                                            let line_indent = line_indent.unwrap();
 581                                            let base_indent = base_indent.unwrap();
 582                                            let indent_delta =
 583                                                line_indent as i32 - base_indent as i32;
 584                                            let mut corrected_indent_len = cmp::max(
 585                                                0,
 586                                                suggested_line_indent.len as i32 + indent_delta,
 587                                            )
 588                                                as usize;
 589                                            if first_line {
 590                                                corrected_indent_len = corrected_indent_len
 591                                                    .saturating_sub(
 592                                                        selection_start.column as usize,
 593                                                    );
 594                                            }
 595
 596                                            let indent_char = suggested_line_indent.char();
 597                                            let mut indent_buffer = [0; 4];
 598                                            let indent_str =
 599                                                indent_char.encode_utf8(&mut indent_buffer);
 600                                            new_text.replace_range(
 601                                                ..line_indent,
 602                                                &indent_str.repeat(corrected_indent_len),
 603                                            );
 604                                        }
 605                                    }
 606
 607                                    if line_indent.is_some() {
 608                                        let char_ops = diff.push_new(&new_text);
 609                                        line_diff.push_char_operations(&char_ops, &selected_text);
 610                                        diff_tx
 611                                            .send((char_ops, line_diff.line_operations()))
 612                                            .await?;
 613                                        new_text.clear();
 614                                    }
 615
 616                                    if lines.peek().is_some() {
 617                                        let char_ops = diff.push_new("\n");
 618                                        line_diff.push_char_operations(&char_ops, &selected_text);
 619                                        diff_tx
 620                                            .send((char_ops, line_diff.line_operations()))
 621                                            .await?;
 622                                        if line_indent.is_none() {
 623                                            // Don't write out the leading indentation in empty lines on the next line
 624                                            // This is the case where the above if statement didn't clear the buffer
 625                                            new_text.clear();
 626                                        }
 627                                        line_indent = None;
 628                                        first_line = false;
 629                                    }
 630                                }
 631                            }
 632
 633                            let mut char_ops = diff.push_new(&new_text);
 634                            char_ops.extend(diff.finish());
 635                            line_diff.push_char_operations(&char_ops, &selected_text);
 636                            line_diff.finish(&selected_text);
 637                            diff_tx
 638                                .send((char_ops, line_diff.line_operations()))
 639                                .await?;
 640
 641                            anyhow::Ok(())
 642                        };
 643
 644                        let result = diff.await;
 645
 646                        let error_message = result.as_ref().err().map(|error| error.to_string());
 647                        report_assistant_event(
 648                            AssistantEventData {
 649                                conversation_id: None,
 650                                message_id,
 651                                kind: AssistantKind::Inline,
 652                                phase: AssistantPhase::Response,
 653                                model: model_telemetry_id,
 654                                model_provider: model_provider_id,
 655                                response_latency,
 656                                error_message,
 657                                language_name: language_name.map(|name| name.to_proto()),
 658                            },
 659                            telemetry,
 660                            http_client,
 661                            model_api_key,
 662                            &executor,
 663                        );
 664
 665                        result?;
 666                        Ok(())
 667                    });
 668
 669                while let Some((char_ops, line_ops)) = diff_rx.next().await {
 670                    codegen.update(cx, |codegen, cx| {
 671                        codegen.last_equal_ranges.clear();
 672
 673                        let edits = char_ops
 674                            .into_iter()
 675                            .filter_map(|operation| match operation {
 676                                CharOperation::Insert { text } => {
 677                                    let edit_start = snapshot.anchor_after(edit_start);
 678                                    Some((edit_start..edit_start, text))
 679                                }
 680                                CharOperation::Delete { bytes } => {
 681                                    let edit_end = edit_start + bytes;
 682                                    let edit_range = snapshot.anchor_after(edit_start)
 683                                        ..snapshot.anchor_before(edit_end);
 684                                    edit_start = edit_end;
 685                                    Some((edit_range, String::new()))
 686                                }
 687                                CharOperation::Keep { bytes } => {
 688                                    let edit_end = edit_start + bytes;
 689                                    let edit_range = snapshot.anchor_after(edit_start)
 690                                        ..snapshot.anchor_before(edit_end);
 691                                    edit_start = edit_end;
 692                                    codegen.last_equal_ranges.push(edit_range);
 693                                    None
 694                                }
 695                            })
 696                            .collect::<Vec<_>>();
 697
 698                        if codegen.active {
 699                            codegen.apply_edits(edits.iter().cloned(), cx);
 700                            codegen.reapply_line_based_diff(line_ops.iter().cloned(), cx);
 701                        }
 702                        codegen.edits.extend(edits);
 703                        codegen.line_operations = line_ops;
 704                        codegen.edit_position = Some(snapshot.anchor_after(edit_start));
 705
 706                        cx.notify();
 707                    })?;
 708                }
 709
 710                // Streaming stopped and we have the new text in the buffer, and a line-based diff applied for the whole new buffer.
 711                // That diff is not what a regular diff is and might look unexpected, ergo apply a regular diff.
 712                // It's fine to apply even if the rest of the line diffing fails, as no more hunks are coming through `diff_rx`.
 713                let batch_diff_task =
 714                    codegen.update(cx, |codegen, cx| codegen.reapply_batch_diff(cx))?;
 715                let (line_based_stream_diff, ()) = join!(line_based_stream_diff, batch_diff_task);
 716                line_based_stream_diff?;
 717
 718                anyhow::Ok(())
 719            };
 720
 721            let result = generate.await;
 722            let elapsed_time = start_time.elapsed().as_secs_f64();
 723
 724            codegen
 725                .update(cx, |this, cx| {
 726                    this.message_id = message_id;
 727                    this.last_equal_ranges.clear();
 728                    if let Err(error) = result {
 729                        this.status = CodegenStatus::Error(error);
 730                    } else {
 731                        this.status = CodegenStatus::Done;
 732                    }
 733                    this.elapsed_time = Some(elapsed_time);
 734                    this.completion = Some(completion.lock().clone());
 735                    if let Some(usage) = token_usage {
 736                        let usage = usage.lock();
 737                        telemetry::event!(
 738                            "Inline Assistant Completion",
 739                            model = model_telemetry_id,
 740                            model_provider = model_provider_id,
 741                            input_tokens = usage.input_tokens,
 742                            output_tokens = usage.output_tokens,
 743                        )
 744                    }
 745                    cx.emit(CodegenEvent::Finished);
 746                    cx.notify();
 747                })
 748                .ok();
 749        });
 750        cx.notify();
 751    }
 752
 753    pub fn stop(&mut self, cx: &mut Context<Self>) {
 754        self.last_equal_ranges.clear();
 755        if self.diff.is_empty() {
 756            self.status = CodegenStatus::Idle;
 757        } else {
 758            self.status = CodegenStatus::Done;
 759        }
 760        self.generation = Task::ready(());
 761        cx.emit(CodegenEvent::Finished);
 762        cx.notify();
 763    }
 764
 765    pub fn undo(&mut self, cx: &mut Context<Self>) {
 766        self.buffer.update(cx, |buffer, cx| {
 767            if let Some(transaction_id) = self.transformation_transaction_id.take() {
 768                buffer.undo_transaction(transaction_id, cx);
 769                buffer.refresh_preview(cx);
 770            }
 771        });
 772    }
 773
 774    fn apply_edits(
 775        &mut self,
 776        edits: impl IntoIterator<Item = (Range<Anchor>, String)>,
 777        cx: &mut Context<CodegenAlternative>,
 778    ) {
 779        let transaction = self.buffer.update(cx, |buffer, cx| {
 780            // Avoid grouping agent edits with user edits.
 781            buffer.finalize_last_transaction(cx);
 782            buffer.start_transaction(cx);
 783            buffer.edit(edits, None, cx);
 784            buffer.end_transaction(cx)
 785        });
 786
 787        if let Some(transaction) = transaction {
 788            if let Some(first_transaction) = self.transformation_transaction_id {
 789                // Group all agent edits into the first transaction.
 790                self.buffer.update(cx, |buffer, cx| {
 791                    buffer.merge_transactions(transaction, first_transaction, cx)
 792                });
 793            } else {
 794                self.transformation_transaction_id = Some(transaction);
 795                self.buffer
 796                    .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
 797            }
 798        }
 799    }
 800
 801    fn reapply_line_based_diff(
 802        &mut self,
 803        line_operations: impl IntoIterator<Item = LineOperation>,
 804        cx: &mut Context<Self>,
 805    ) {
 806        let old_snapshot = self.snapshot.clone();
 807        let old_range = self.range.to_point(&old_snapshot);
 808        let new_snapshot = self.buffer.read(cx).snapshot(cx);
 809        let new_range = self.range.to_point(&new_snapshot);
 810
 811        let mut old_row = old_range.start.row;
 812        let mut new_row = new_range.start.row;
 813
 814        self.diff.deleted_row_ranges.clear();
 815        self.diff.inserted_row_ranges.clear();
 816        for operation in line_operations {
 817            match operation {
 818                LineOperation::Keep { lines } => {
 819                    old_row += lines;
 820                    new_row += lines;
 821                }
 822                LineOperation::Delete { lines } => {
 823                    let old_end_row = old_row + lines - 1;
 824                    let new_row = new_snapshot.anchor_before(Point::new(new_row, 0));
 825
 826                    if let Some((_, last_deleted_row_range)) =
 827                        self.diff.deleted_row_ranges.last_mut()
 828                    {
 829                        if *last_deleted_row_range.end() + 1 == old_row {
 830                            *last_deleted_row_range = *last_deleted_row_range.start()..=old_end_row;
 831                        } else {
 832                            self.diff
 833                                .deleted_row_ranges
 834                                .push((new_row, old_row..=old_end_row));
 835                        }
 836                    } else {
 837                        self.diff
 838                            .deleted_row_ranges
 839                            .push((new_row, old_row..=old_end_row));
 840                    }
 841
 842                    old_row += lines;
 843                }
 844                LineOperation::Insert { lines } => {
 845                    let new_end_row = new_row + lines - 1;
 846                    let start = new_snapshot.anchor_before(Point::new(new_row, 0));
 847                    let end = new_snapshot.anchor_before(Point::new(
 848                        new_end_row,
 849                        new_snapshot.line_len(MultiBufferRow(new_end_row)),
 850                    ));
 851                    self.diff.inserted_row_ranges.push(start..end);
 852                    new_row += lines;
 853                }
 854            }
 855
 856            cx.notify();
 857        }
 858    }
 859
 860    fn reapply_batch_diff(&mut self, cx: &mut Context<Self>) -> Task<()> {
 861        let old_snapshot = self.snapshot.clone();
 862        let old_range = self.range.to_point(&old_snapshot);
 863        let new_snapshot = self.buffer.read(cx).snapshot(cx);
 864        let new_range = self.range.to_point(&new_snapshot);
 865
 866        cx.spawn(async move |codegen, cx| {
 867            let (deleted_row_ranges, inserted_row_ranges) = cx
 868                .background_spawn(async move {
 869                    let old_text = old_snapshot
 870                        .text_for_range(
 871                            Point::new(old_range.start.row, 0)
 872                                ..Point::new(
 873                                    old_range.end.row,
 874                                    old_snapshot.line_len(MultiBufferRow(old_range.end.row)),
 875                                ),
 876                        )
 877                        .collect::<String>();
 878                    let new_text = new_snapshot
 879                        .text_for_range(
 880                            Point::new(new_range.start.row, 0)
 881                                ..Point::new(
 882                                    new_range.end.row,
 883                                    new_snapshot.line_len(MultiBufferRow(new_range.end.row)),
 884                                ),
 885                        )
 886                        .collect::<String>();
 887
 888                    let old_start_row = old_range.start.row;
 889                    let new_start_row = new_range.start.row;
 890                    let mut deleted_row_ranges: Vec<(Anchor, RangeInclusive<u32>)> = Vec::new();
 891                    let mut inserted_row_ranges = Vec::new();
 892                    for (old_rows, new_rows) in line_diff(&old_text, &new_text) {
 893                        let old_rows = old_start_row + old_rows.start..old_start_row + old_rows.end;
 894                        let new_rows = new_start_row + new_rows.start..new_start_row + new_rows.end;
 895                        if !old_rows.is_empty() {
 896                            deleted_row_ranges.push((
 897                                new_snapshot.anchor_before(Point::new(new_rows.start, 0)),
 898                                old_rows.start..=old_rows.end - 1,
 899                            ));
 900                        }
 901                        if !new_rows.is_empty() {
 902                            let start = new_snapshot.anchor_before(Point::new(new_rows.start, 0));
 903                            let new_end_row = new_rows.end - 1;
 904                            let end = new_snapshot.anchor_before(Point::new(
 905                                new_end_row,
 906                                new_snapshot.line_len(MultiBufferRow(new_end_row)),
 907                            ));
 908                            inserted_row_ranges.push(start..end);
 909                        }
 910                    }
 911                    (deleted_row_ranges, inserted_row_ranges)
 912                })
 913                .await;
 914
 915            codegen
 916                .update(cx, |codegen, cx| {
 917                    codegen.diff.deleted_row_ranges = deleted_row_ranges;
 918                    codegen.diff.inserted_row_ranges = inserted_row_ranges;
 919                    cx.notify();
 920                })
 921                .ok();
 922        })
 923    }
 924}
 925
 926#[derive(Copy, Clone, Debug)]
 927pub enum CodegenEvent {
 928    Finished,
 929    Undone,
 930}
 931
 932struct StripInvalidSpans<T> {
 933    stream: T,
 934    stream_done: bool,
 935    buffer: String,
 936    first_line: bool,
 937    line_end: bool,
 938    starts_with_code_block: bool,
 939}
 940
 941impl<T> StripInvalidSpans<T>
 942where
 943    T: Stream<Item = Result<String>>,
 944{
 945    fn new(stream: T) -> Self {
 946        Self {
 947            stream,
 948            stream_done: false,
 949            buffer: String::new(),
 950            first_line: true,
 951            line_end: false,
 952            starts_with_code_block: false,
 953        }
 954    }
 955}
 956
 957impl<T> Stream for StripInvalidSpans<T>
 958where
 959    T: Stream<Item = Result<String>>,
 960{
 961    type Item = Result<String>;
 962
 963    fn poll_next(self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<Option<Self::Item>> {
 964        const CODE_BLOCK_DELIMITER: &str = "```";
 965        const CURSOR_SPAN: &str = "<|CURSOR|>";
 966
 967        let this = unsafe { self.get_unchecked_mut() };
 968        loop {
 969            if !this.stream_done {
 970                let mut stream = unsafe { Pin::new_unchecked(&mut this.stream) };
 971                match stream.as_mut().poll_next(cx) {
 972                    Poll::Ready(Some(Ok(chunk))) => {
 973                        this.buffer.push_str(&chunk);
 974                    }
 975                    Poll::Ready(Some(Err(error))) => return Poll::Ready(Some(Err(error))),
 976                    Poll::Ready(None) => {
 977                        this.stream_done = true;
 978                    }
 979                    Poll::Pending => return Poll::Pending,
 980                }
 981            }
 982
 983            let mut chunk = String::new();
 984            let mut consumed = 0;
 985            if !this.buffer.is_empty() {
 986                let mut lines = this.buffer.split('\n').enumerate().peekable();
 987                while let Some((line_ix, line)) = lines.next() {
 988                    if line_ix > 0 {
 989                        this.first_line = false;
 990                    }
 991
 992                    if this.first_line {
 993                        let trimmed_line = line.trim();
 994                        if lines.peek().is_some() {
 995                            if trimmed_line.starts_with(CODE_BLOCK_DELIMITER) {
 996                                consumed += line.len() + 1;
 997                                this.starts_with_code_block = true;
 998                                continue;
 999                            }
1000                        } else if trimmed_line.is_empty()
1001                            || prefixes(CODE_BLOCK_DELIMITER)
1002                                .any(|prefix| trimmed_line.starts_with(prefix))
1003                        {
1004                            break;
1005                        }
1006                    }
1007
1008                    let line_without_cursor = line.replace(CURSOR_SPAN, "");
1009                    if lines.peek().is_some() {
1010                        if this.line_end {
1011                            chunk.push('\n');
1012                        }
1013
1014                        chunk.push_str(&line_without_cursor);
1015                        this.line_end = true;
1016                        consumed += line.len() + 1;
1017                    } else if this.stream_done {
1018                        if !this.starts_with_code_block
1019                            || !line_without_cursor.trim().ends_with(CODE_BLOCK_DELIMITER)
1020                        {
1021                            if this.line_end {
1022                                chunk.push('\n');
1023                            }
1024
1025                            chunk.push_str(&line);
1026                        }
1027
1028                        consumed += line.len();
1029                    } else {
1030                        let trimmed_line = line.trim();
1031                        if trimmed_line.is_empty()
1032                            || prefixes(CURSOR_SPAN).any(|prefix| trimmed_line.ends_with(prefix))
1033                            || prefixes(CODE_BLOCK_DELIMITER)
1034                                .any(|prefix| trimmed_line.ends_with(prefix))
1035                        {
1036                            break;
1037                        } else {
1038                            if this.line_end {
1039                                chunk.push('\n');
1040                                this.line_end = false;
1041                            }
1042
1043                            chunk.push_str(&line_without_cursor);
1044                            consumed += line.len();
1045                        }
1046                    }
1047                }
1048            }
1049
1050            this.buffer = this.buffer.split_off(consumed);
1051            if !chunk.is_empty() {
1052                return Poll::Ready(Some(Ok(chunk)));
1053            } else if this.stream_done {
1054                return Poll::Ready(None);
1055            }
1056        }
1057    }
1058}
1059
1060fn prefixes(text: &str) -> impl Iterator<Item = &str> {
1061    (0..text.len() - 1).map(|ix| &text[..ix + 1])
1062}
1063
1064#[derive(Default)]
1065pub struct Diff {
1066    pub deleted_row_ranges: Vec<(Anchor, RangeInclusive<u32>)>,
1067    pub inserted_row_ranges: Vec<Range<Anchor>>,
1068}
1069
1070impl Diff {
1071    fn is_empty(&self) -> bool {
1072        self.deleted_row_ranges.is_empty() && self.inserted_row_ranges.is_empty()
1073    }
1074}
1075
1076#[cfg(test)]
1077mod tests {
1078    use super::*;
1079    use fs::FakeFs;
1080    use futures::{
1081        Stream,
1082        stream::{self},
1083    };
1084    use gpui::TestAppContext;
1085    use indoc::indoc;
1086    use language::{
1087        Buffer, Language, LanguageConfig, LanguageMatcher, Point, language_settings,
1088        tree_sitter_rust,
1089    };
1090    use language_model::{LanguageModelRegistry, TokenUsage};
1091    use rand::prelude::*;
1092    use serde::Serialize;
1093    use settings::SettingsStore;
1094    use std::{future, sync::Arc};
1095
1096    #[derive(Serialize)]
1097    pub struct DummyCompletionRequest {
1098        pub name: String,
1099    }
1100
1101    #[gpui::test(iterations = 10)]
1102    async fn test_transform_autoindent(cx: &mut TestAppContext, mut rng: StdRng) {
1103        init_test(cx);
1104
1105        let text = indoc! {"
1106            fn main() {
1107                let x = 0;
1108                for _ in 0..10 {
1109                    x += 1;
1110                }
1111            }
1112        "};
1113        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
1114        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1115        let range = buffer.read_with(cx, |buffer, cx| {
1116            let snapshot = buffer.snapshot(cx);
1117            snapshot.anchor_before(Point::new(1, 0))..snapshot.anchor_after(Point::new(4, 5))
1118        });
1119        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
1120        let fs = FakeFs::new(cx.executor());
1121        let project = Project::test(fs, vec![], cx).await;
1122        let codegen = cx.new(|cx| {
1123            CodegenAlternative::new(
1124                buffer.clone(),
1125                range.clone(),
1126                true,
1127                None,
1128                project.downgrade(),
1129                None,
1130                None,
1131                prompt_builder,
1132                cx,
1133            )
1134        });
1135
1136        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
1137
1138        let mut new_text = concat!(
1139            "       let mut x = 0;\n",
1140            "       while x < 10 {\n",
1141            "           x += 1;\n",
1142            "       }",
1143        );
1144        while !new_text.is_empty() {
1145            let max_len = cmp::min(new_text.len(), 10);
1146            let len = rng.gen_range(1..=max_len);
1147            let (chunk, suffix) = new_text.split_at(len);
1148            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
1149            new_text = suffix;
1150            cx.background_executor.run_until_parked();
1151        }
1152        drop(chunks_tx);
1153        cx.background_executor.run_until_parked();
1154
1155        assert_eq!(
1156            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
1157            indoc! {"
1158                fn main() {
1159                    let mut x = 0;
1160                    while x < 10 {
1161                        x += 1;
1162                    }
1163                }
1164            "}
1165        );
1166    }
1167
1168    #[gpui::test(iterations = 10)]
1169    async fn test_autoindent_when_generating_past_indentation(
1170        cx: &mut TestAppContext,
1171        mut rng: StdRng,
1172    ) {
1173        init_test(cx);
1174
1175        let text = indoc! {"
1176            fn main() {
1177                le
1178            }
1179        "};
1180        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
1181        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1182        let range = buffer.read_with(cx, |buffer, cx| {
1183            let snapshot = buffer.snapshot(cx);
1184            snapshot.anchor_before(Point::new(1, 6))..snapshot.anchor_after(Point::new(1, 6))
1185        });
1186        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
1187        let fs = FakeFs::new(cx.executor());
1188        let project = Project::test(fs, vec![], cx).await;
1189        let codegen = cx.new(|cx| {
1190            CodegenAlternative::new(
1191                buffer.clone(),
1192                range.clone(),
1193                true,
1194                None,
1195                project.downgrade(),
1196                None,
1197                None,
1198                prompt_builder,
1199                cx,
1200            )
1201        });
1202
1203        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
1204
1205        cx.background_executor.run_until_parked();
1206
1207        let mut new_text = concat!(
1208            "t mut x = 0;\n",
1209            "while x < 10 {\n",
1210            "    x += 1;\n",
1211            "}", //
1212        );
1213        while !new_text.is_empty() {
1214            let max_len = cmp::min(new_text.len(), 10);
1215            let len = rng.gen_range(1..=max_len);
1216            let (chunk, suffix) = new_text.split_at(len);
1217            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
1218            new_text = suffix;
1219            cx.background_executor.run_until_parked();
1220        }
1221        drop(chunks_tx);
1222        cx.background_executor.run_until_parked();
1223
1224        assert_eq!(
1225            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
1226            indoc! {"
1227                fn main() {
1228                    let mut x = 0;
1229                    while x < 10 {
1230                        x += 1;
1231                    }
1232                }
1233            "}
1234        );
1235    }
1236
1237    #[gpui::test(iterations = 10)]
1238    async fn test_autoindent_when_generating_before_indentation(
1239        cx: &mut TestAppContext,
1240        mut rng: StdRng,
1241    ) {
1242        init_test(cx);
1243
1244        let text = concat!(
1245            "fn main() {\n",
1246            "  \n",
1247            "}\n" //
1248        );
1249        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
1250        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1251        let range = buffer.read_with(cx, |buffer, cx| {
1252            let snapshot = buffer.snapshot(cx);
1253            snapshot.anchor_before(Point::new(1, 2))..snapshot.anchor_after(Point::new(1, 2))
1254        });
1255        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
1256        let fs = FakeFs::new(cx.executor());
1257        let project = Project::test(fs, vec![], cx).await;
1258        let codegen = cx.new(|cx| {
1259            CodegenAlternative::new(
1260                buffer.clone(),
1261                range.clone(),
1262                true,
1263                None,
1264                project.downgrade(),
1265                None,
1266                None,
1267                prompt_builder,
1268                cx,
1269            )
1270        });
1271
1272        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
1273
1274        cx.background_executor.run_until_parked();
1275
1276        let mut new_text = concat!(
1277            "let mut x = 0;\n",
1278            "while x < 10 {\n",
1279            "    x += 1;\n",
1280            "}", //
1281        );
1282        while !new_text.is_empty() {
1283            let max_len = cmp::min(new_text.len(), 10);
1284            let len = rng.gen_range(1..=max_len);
1285            let (chunk, suffix) = new_text.split_at(len);
1286            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
1287            new_text = suffix;
1288            cx.background_executor.run_until_parked();
1289        }
1290        drop(chunks_tx);
1291        cx.background_executor.run_until_parked();
1292
1293        assert_eq!(
1294            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
1295            indoc! {"
1296                fn main() {
1297                    let mut x = 0;
1298                    while x < 10 {
1299                        x += 1;
1300                    }
1301                }
1302            "}
1303        );
1304    }
1305
1306    #[gpui::test(iterations = 10)]
1307    async fn test_autoindent_respects_tabs_in_selection(cx: &mut TestAppContext) {
1308        init_test(cx);
1309
1310        let text = indoc! {"
1311            func main() {
1312            \tx := 0
1313            \tfor i := 0; i < 10; i++ {
1314            \t\tx++
1315            \t}
1316            }
1317        "};
1318        let buffer = cx.new(|cx| Buffer::local(text, cx));
1319        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1320        let range = buffer.read_with(cx, |buffer, cx| {
1321            let snapshot = buffer.snapshot(cx);
1322            snapshot.anchor_before(Point::new(0, 0))..snapshot.anchor_after(Point::new(4, 2))
1323        });
1324        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
1325        let fs = FakeFs::new(cx.executor());
1326        let project = Project::test(fs, vec![], cx).await;
1327        let codegen = cx.new(|cx| {
1328            CodegenAlternative::new(
1329                buffer.clone(),
1330                range.clone(),
1331                true,
1332                None,
1333                project.downgrade(),
1334                None,
1335                None,
1336                prompt_builder,
1337                cx,
1338            )
1339        });
1340
1341        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
1342        let new_text = concat!(
1343            "func main() {\n",
1344            "\tx := 0\n",
1345            "\tfor x < 10 {\n",
1346            "\t\tx++\n",
1347            "\t}", //
1348        );
1349        chunks_tx.unbounded_send(new_text.to_string()).unwrap();
1350        drop(chunks_tx);
1351        cx.background_executor.run_until_parked();
1352
1353        assert_eq!(
1354            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
1355            indoc! {"
1356                func main() {
1357                \tx := 0
1358                \tfor x < 10 {
1359                \t\tx++
1360                \t}
1361                }
1362            "}
1363        );
1364    }
1365
1366    #[gpui::test]
1367    async fn test_inactive_codegen_alternative(cx: &mut TestAppContext) {
1368        init_test(cx);
1369
1370        let text = indoc! {"
1371            fn main() {
1372                let x = 0;
1373            }
1374        "};
1375        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
1376        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
1377        let range = buffer.read_with(cx, |buffer, cx| {
1378            let snapshot = buffer.snapshot(cx);
1379            snapshot.anchor_before(Point::new(1, 0))..snapshot.anchor_after(Point::new(1, 14))
1380        });
1381        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
1382        let fs = FakeFs::new(cx.executor());
1383        let project = Project::test(fs, vec![], cx).await;
1384        let codegen = cx.new(|cx| {
1385            CodegenAlternative::new(
1386                buffer.clone(),
1387                range.clone(),
1388                false,
1389                None,
1390                project.downgrade(),
1391                None,
1392                None,
1393                prompt_builder,
1394                cx,
1395            )
1396        });
1397
1398        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
1399        chunks_tx
1400            .unbounded_send("let mut x = 0;\nx += 1;".to_string())
1401            .unwrap();
1402        drop(chunks_tx);
1403        cx.run_until_parked();
1404
1405        // The codegen is inactive, so the buffer doesn't get modified.
1406        assert_eq!(
1407            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
1408            text
1409        );
1410
1411        // Activating the codegen applies the changes.
1412        codegen.update(cx, |codegen, cx| codegen.set_active(true, cx));
1413        assert_eq!(
1414            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
1415            indoc! {"
1416                fn main() {
1417                    let mut x = 0;
1418                    x += 1;
1419                }
1420            "}
1421        );
1422
1423        // Deactivating the codegen undoes the changes.
1424        codegen.update(cx, |codegen, cx| codegen.set_active(false, cx));
1425        cx.run_until_parked();
1426        assert_eq!(
1427            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
1428            text
1429        );
1430    }
1431
1432    #[gpui::test]
1433    async fn test_strip_invalid_spans_from_codeblock() {
1434        assert_chunks("Lorem ipsum dolor", "Lorem ipsum dolor").await;
1435        assert_chunks("```\nLorem ipsum dolor", "Lorem ipsum dolor").await;
1436        assert_chunks("```\nLorem ipsum dolor\n```", "Lorem ipsum dolor").await;
1437        assert_chunks(
1438            "```html\n```js\nLorem ipsum dolor\n```\n```",
1439            "```js\nLorem ipsum dolor\n```",
1440        )
1441        .await;
1442        assert_chunks("``\nLorem ipsum dolor\n```", "``\nLorem ipsum dolor\n```").await;
1443        assert_chunks("Lorem<|CURSOR|> ipsum", "Lorem ipsum").await;
1444        assert_chunks("Lorem ipsum", "Lorem ipsum").await;
1445        assert_chunks("```\n<|CURSOR|>Lorem ipsum\n```", "Lorem ipsum").await;
1446
1447        async fn assert_chunks(text: &str, expected_text: &str) {
1448            for chunk_size in 1..=text.len() {
1449                let actual_text = StripInvalidSpans::new(chunks(text, chunk_size))
1450                    .map(|chunk| chunk.unwrap())
1451                    .collect::<String>()
1452                    .await;
1453                assert_eq!(
1454                    actual_text, expected_text,
1455                    "failed to strip invalid spans, chunk size: {}",
1456                    chunk_size
1457                );
1458            }
1459        }
1460
1461        fn chunks(text: &str, size: usize) -> impl Stream<Item = Result<String>> {
1462            stream::iter(
1463                text.chars()
1464                    .collect::<Vec<_>>()
1465                    .chunks(size)
1466                    .map(|chunk| Ok(chunk.iter().collect::<String>()))
1467                    .collect::<Vec<_>>(),
1468            )
1469        }
1470    }
1471
1472    fn init_test(cx: &mut TestAppContext) {
1473        cx.update(LanguageModelRegistry::test);
1474        cx.set_global(cx.update(SettingsStore::test));
1475        cx.update(Project::init_settings);
1476        cx.update(language_settings::init);
1477    }
1478
1479    fn simulate_response_stream(
1480        codegen: Entity<CodegenAlternative>,
1481        cx: &mut TestAppContext,
1482    ) -> mpsc::UnboundedSender<String> {
1483        let (chunks_tx, chunks_rx) = mpsc::unbounded();
1484        codegen.update(cx, |codegen, cx| {
1485            codegen.handle_stream(
1486                String::new(),
1487                String::new(),
1488                None,
1489                future::ready(Ok(LanguageModelTextStream {
1490                    message_id: None,
1491                    stream: chunks_rx.map(Ok).boxed(),
1492                    last_token_usage: Arc::new(Mutex::new(TokenUsage::default())),
1493                })),
1494                cx,
1495            );
1496        });
1497        chunks_tx
1498    }
1499
1500    fn rust_lang() -> Language {
1501        Language::new(
1502            LanguageConfig {
1503                name: "Rust".into(),
1504                matcher: LanguageMatcher {
1505                    path_suffixes: vec!["rs".to_string()],
1506                    ..Default::default()
1507                },
1508                ..Default::default()
1509            },
1510            Some(tree_sitter_rust::LANGUAGE.into()),
1511        )
1512        .with_indents_query(
1513            r#"
1514            (call_expression) @indent
1515            (field_expression) @indent
1516            (_ "(" ")" @end) @indent
1517            (_ "{" "}" @end) @indent
1518            "#,
1519        )
1520        .unwrap()
1521    }
1522}