buffer_codegen.rs

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