buffer_codegen.rs

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