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