buffer_codegen.rs

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