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