inline_assistant.rs

   1use crate::{
   2    Assistant, AssistantPanel, AssistantPanelEvent, CycleNextInlineAssist,
   3    CyclePreviousInlineAssist,
   4};
   5use anyhow::{Context as _, Result, anyhow};
   6use assistant_context_editor::{RequestType, humanize_token_count};
   7use assistant_settings::AssistantSettings;
   8use client::{ErrorExt, telemetry::Telemetry};
   9use collections::{HashMap, HashSet, VecDeque, hash_map};
  10use editor::{
  11    Anchor, AnchorRangeExt, CodeActionProvider, Editor, EditorElement, EditorEvent, EditorMode,
  12    EditorStyle, ExcerptId, ExcerptRange, GutterDimensions, MultiBuffer, MultiBufferSnapshot,
  13    ToOffset as _, ToPoint,
  14    actions::{MoveDown, MoveUp, SelectAll},
  15    display_map::{
  16        BlockContext, BlockPlacement, BlockProperties, BlockStyle, CustomBlockId, RenderBlock,
  17        ToDisplayPoint,
  18    },
  19};
  20use feature_flags::{
  21    Assistant2FeatureFlag, FeatureFlagAppExt as _, FeatureFlagViewExt as _, ZedPro,
  22};
  23use fs::Fs;
  24use futures::{
  25    SinkExt, Stream, StreamExt,
  26    channel::mpsc,
  27    future::{BoxFuture, LocalBoxFuture},
  28    join,
  29};
  30use gpui::{
  31    AnyElement, App, ClickEvent, Context, CursorStyle, Entity, EventEmitter, FocusHandle,
  32    Focusable, FontWeight, Global, HighlightStyle, Subscription, Task, TextStyle, UpdateGlobal,
  33    WeakEntity, Window, anchored, deferred, point,
  34};
  35use language::{Buffer, IndentKind, Point, Selection, TransactionId, line_diff};
  36use language_model::{
  37    ConfiguredModel, LanguageModel, LanguageModelRegistry, LanguageModelRequest,
  38    LanguageModelRequestMessage, LanguageModelTextStream, Role, report_assistant_event,
  39};
  40use language_model_selector::{LanguageModelSelector, LanguageModelSelectorPopoverMenu};
  41use multi_buffer::MultiBufferRow;
  42use parking_lot::Mutex;
  43use project::{CodeAction, LspAction, ProjectTransaction};
  44use prompt_store::PromptBuilder;
  45use rope::Rope;
  46use settings::{Settings, SettingsStore, update_settings_file};
  47use smol::future::FutureExt;
  48use std::{
  49    cmp,
  50    future::{self, Future},
  51    iter, mem,
  52    ops::{Range, RangeInclusive},
  53    pin::Pin,
  54    rc::Rc,
  55    sync::Arc,
  56    task::{self, Poll},
  57    time::{Duration, Instant},
  58};
  59use streaming_diff::{CharOperation, LineDiff, LineOperation, StreamingDiff};
  60use telemetry_events::{AssistantEventData, AssistantKind, AssistantPhase};
  61use terminal_view::terminal_panel::TerminalPanel;
  62use text::{OffsetRangeExt, ToPoint as _};
  63use theme::ThemeSettings;
  64use ui::{
  65    CheckboxWithLabel, IconButtonShape, KeyBinding, Popover, Tooltip, prelude::*, text_for_action,
  66};
  67use util::{RangeExt, ResultExt};
  68use workspace::{ItemHandle, Toast, Workspace, notifications::NotificationId};
  69
  70pub fn init(
  71    fs: Arc<dyn Fs>,
  72    prompt_builder: Arc<PromptBuilder>,
  73    telemetry: Arc<Telemetry>,
  74    cx: &mut App,
  75) {
  76    cx.set_global(InlineAssistant::new(fs, prompt_builder, telemetry));
  77    cx.observe_new(|_, window, cx| {
  78        let Some(window) = window else {
  79            return;
  80        };
  81        let workspace = cx.entity().clone();
  82        InlineAssistant::update_global(cx, |inline_assistant, cx| {
  83            inline_assistant.register_workspace(&workspace, window, cx)
  84        });
  85
  86        cx.observe_flag::<Assistant2FeatureFlag, _>(window, {
  87            |is_assistant2_enabled, _workspace, _window, cx| {
  88                InlineAssistant::update_global(cx, |inline_assistant, _cx| {
  89                    inline_assistant.is_assistant2_enabled = is_assistant2_enabled;
  90                });
  91            }
  92        })
  93        .detach();
  94    })
  95    .detach();
  96}
  97
  98const PROMPT_HISTORY_MAX_LEN: usize = 20;
  99
 100pub struct InlineAssistant {
 101    next_assist_id: InlineAssistId,
 102    next_assist_group_id: InlineAssistGroupId,
 103    assists: HashMap<InlineAssistId, InlineAssist>,
 104    assists_by_editor: HashMap<WeakEntity<Editor>, EditorInlineAssists>,
 105    assist_groups: HashMap<InlineAssistGroupId, InlineAssistGroup>,
 106    confirmed_assists: HashMap<InlineAssistId, Entity<CodegenAlternative>>,
 107    prompt_history: VecDeque<String>,
 108    prompt_builder: Arc<PromptBuilder>,
 109    telemetry: Arc<Telemetry>,
 110    fs: Arc<dyn Fs>,
 111    is_assistant2_enabled: bool,
 112}
 113
 114impl Global for InlineAssistant {}
 115
 116impl InlineAssistant {
 117    pub fn new(
 118        fs: Arc<dyn Fs>,
 119        prompt_builder: Arc<PromptBuilder>,
 120        telemetry: Arc<Telemetry>,
 121    ) -> Self {
 122        Self {
 123            next_assist_id: InlineAssistId::default(),
 124            next_assist_group_id: InlineAssistGroupId::default(),
 125            assists: HashMap::default(),
 126            assists_by_editor: HashMap::default(),
 127            assist_groups: HashMap::default(),
 128            confirmed_assists: HashMap::default(),
 129            prompt_history: VecDeque::default(),
 130            prompt_builder,
 131            telemetry,
 132            fs,
 133            is_assistant2_enabled: false,
 134        }
 135    }
 136
 137    pub fn register_workspace(
 138        &mut self,
 139        workspace: &Entity<Workspace>,
 140        window: &mut Window,
 141        cx: &mut App,
 142    ) {
 143        window
 144            .subscribe(workspace, cx, |workspace, event, window, cx| {
 145                Self::update_global(cx, |this, cx| {
 146                    this.handle_workspace_event(workspace, event, window, cx)
 147                });
 148            })
 149            .detach();
 150
 151        let workspace = workspace.downgrade();
 152        cx.observe_global::<SettingsStore>(move |cx| {
 153            let Some(workspace) = workspace.upgrade() else {
 154                return;
 155            };
 156            let Some(terminal_panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {
 157                return;
 158            };
 159            let enabled = AssistantSettings::get_global(cx).enabled;
 160            terminal_panel.update(cx, |terminal_panel, cx| {
 161                terminal_panel.set_assistant_enabled(enabled, cx)
 162            });
 163        })
 164        .detach();
 165    }
 166
 167    fn handle_workspace_event(
 168        &mut self,
 169        workspace: Entity<Workspace>,
 170        event: &workspace::Event,
 171        window: &mut Window,
 172        cx: &mut App,
 173    ) {
 174        match event {
 175            workspace::Event::UserSavedItem { item, .. } => {
 176                // When the user manually saves an editor, automatically accepts all finished transformations.
 177                if let Some(editor) = item.upgrade().and_then(|item| item.act_as::<Editor>(cx)) {
 178                    if let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) {
 179                        for assist_id in editor_assists.assist_ids.clone() {
 180                            let assist = &self.assists[&assist_id];
 181                            if let CodegenStatus::Done = assist.codegen.read(cx).status(cx) {
 182                                self.finish_assist(assist_id, false, window, cx)
 183                            }
 184                        }
 185                    }
 186                }
 187            }
 188            workspace::Event::ItemAdded { item } => {
 189                self.register_workspace_item(&workspace, item.as_ref(), window, cx);
 190            }
 191            _ => (),
 192        }
 193    }
 194
 195    fn register_workspace_item(
 196        &mut self,
 197        workspace: &Entity<Workspace>,
 198        item: &dyn ItemHandle,
 199        window: &mut Window,
 200        cx: &mut App,
 201    ) {
 202        let is_assistant2_enabled = self.is_assistant2_enabled;
 203
 204        if let Some(editor) = item.act_as::<Editor>(cx) {
 205            editor.update(cx, |editor, cx| {
 206                if is_assistant2_enabled {
 207                    editor.remove_code_action_provider(
 208                        ASSISTANT_CODE_ACTION_PROVIDER_ID.into(),
 209                        window,
 210                        cx,
 211                    );
 212                } else {
 213                    editor.add_code_action_provider(
 214                        Rc::new(AssistantCodeActionProvider {
 215                            editor: cx.entity().downgrade(),
 216                            workspace: workspace.downgrade(),
 217                        }),
 218                        window,
 219                        cx,
 220                    );
 221                }
 222            });
 223        }
 224    }
 225
 226    pub fn assist(
 227        &mut self,
 228        editor: &Entity<Editor>,
 229        workspace: Option<WeakEntity<Workspace>>,
 230        assistant_panel: Option<&Entity<AssistantPanel>>,
 231        initial_prompt: Option<String>,
 232        window: &mut Window,
 233        cx: &mut App,
 234    ) {
 235        let (snapshot, initial_selections) = editor.update(cx, |editor, cx| {
 236            (
 237                editor.snapshot(window, cx),
 238                editor.selections.all::<Point>(cx),
 239            )
 240        });
 241
 242        let mut selections = Vec::<Selection<Point>>::new();
 243        let mut newest_selection = None;
 244        for mut selection in initial_selections {
 245            if selection.end > selection.start {
 246                selection.start.column = 0;
 247                // If the selection ends at the start of the line, we don't want to include it.
 248                if selection.end.column == 0 {
 249                    selection.end.row -= 1;
 250                }
 251                selection.end.column = snapshot
 252                    .buffer_snapshot
 253                    .line_len(MultiBufferRow(selection.end.row));
 254            } else if let Some(fold) =
 255                snapshot.crease_for_buffer_row(MultiBufferRow(selection.end.row))
 256            {
 257                selection.start = fold.range().start;
 258                selection.end = fold.range().end;
 259                if MultiBufferRow(selection.end.row) < snapshot.buffer_snapshot.max_row() {
 260                    let chars = snapshot
 261                        .buffer_snapshot
 262                        .chars_at(Point::new(selection.end.row + 1, 0));
 263
 264                    for c in chars {
 265                        if c == '\n' {
 266                            break;
 267                        }
 268                        if c.is_whitespace() {
 269                            continue;
 270                        }
 271                        if snapshot
 272                            .language_at(selection.end)
 273                            .is_some_and(|language| language.config().brackets.is_closing_brace(c))
 274                        {
 275                            selection.end.row += 1;
 276                            selection.end.column = snapshot
 277                                .buffer_snapshot
 278                                .line_len(MultiBufferRow(selection.end.row));
 279                        }
 280                    }
 281                }
 282            }
 283
 284            if let Some(prev_selection) = selections.last_mut() {
 285                if selection.start <= prev_selection.end {
 286                    prev_selection.end = selection.end;
 287                    continue;
 288                }
 289            }
 290
 291            let latest_selection = newest_selection.get_or_insert_with(|| selection.clone());
 292            if selection.id > latest_selection.id {
 293                *latest_selection = selection.clone();
 294            }
 295            selections.push(selection);
 296        }
 297        let snapshot = &snapshot.buffer_snapshot;
 298        let newest_selection = newest_selection.unwrap();
 299
 300        let mut codegen_ranges = Vec::new();
 301        for (buffer, buffer_range, excerpt_id) in
 302            snapshot.ranges_to_buffer_ranges(selections.iter().map(|selection| {
 303                snapshot.anchor_before(selection.start)..snapshot.anchor_after(selection.end)
 304            }))
 305        {
 306            let start = buffer.anchor_before(buffer_range.start);
 307            let end = buffer.anchor_after(buffer_range.end);
 308
 309            codegen_ranges.push(Anchor::range_in_buffer(
 310                excerpt_id,
 311                buffer.remote_id(),
 312                start..end,
 313            ));
 314
 315            if let Some(ConfiguredModel { model, .. }) =
 316                LanguageModelRegistry::read_global(cx).default_model()
 317            {
 318                self.telemetry.report_assistant_event(AssistantEventData {
 319                    conversation_id: None,
 320                    kind: AssistantKind::Inline,
 321                    phase: AssistantPhase::Invoked,
 322                    message_id: None,
 323                    model: model.telemetry_id(),
 324                    model_provider: model.provider_id().to_string(),
 325                    response_latency: None,
 326                    error_message: None,
 327                    language_name: buffer.language().map(|language| language.name().to_proto()),
 328                });
 329            }
 330        }
 331
 332        let assist_group_id = self.next_assist_group_id.post_inc();
 333        let prompt_buffer = cx.new(|cx| Buffer::local(initial_prompt.unwrap_or_default(), cx));
 334        let prompt_buffer = cx.new(|cx| MultiBuffer::singleton(prompt_buffer, cx));
 335
 336        let mut assists = Vec::new();
 337        let mut assist_to_focus = None;
 338        for range in codegen_ranges {
 339            let assist_id = self.next_assist_id.post_inc();
 340            let codegen = cx.new(|cx| {
 341                Codegen::new(
 342                    editor.read(cx).buffer().clone(),
 343                    range.clone(),
 344                    None,
 345                    self.telemetry.clone(),
 346                    self.prompt_builder.clone(),
 347                    cx,
 348                )
 349            });
 350
 351            let gutter_dimensions = Arc::new(Mutex::new(GutterDimensions::default()));
 352            let prompt_editor = cx.new(|cx| {
 353                PromptEditor::new(
 354                    assist_id,
 355                    gutter_dimensions.clone(),
 356                    self.prompt_history.clone(),
 357                    prompt_buffer.clone(),
 358                    codegen.clone(),
 359                    editor,
 360                    assistant_panel,
 361                    workspace.clone(),
 362                    self.fs.clone(),
 363                    window,
 364                    cx,
 365                )
 366            });
 367
 368            if assist_to_focus.is_none() {
 369                let focus_assist = if newest_selection.reversed {
 370                    range.start.to_point(&snapshot) == newest_selection.start
 371                } else {
 372                    range.end.to_point(&snapshot) == newest_selection.end
 373                };
 374                if focus_assist {
 375                    assist_to_focus = Some(assist_id);
 376                }
 377            }
 378
 379            let [prompt_block_id, end_block_id] =
 380                self.insert_assist_blocks(editor, &range, &prompt_editor, cx);
 381
 382            assists.push((
 383                assist_id,
 384                range,
 385                prompt_editor,
 386                prompt_block_id,
 387                end_block_id,
 388            ));
 389        }
 390
 391        let editor_assists = self
 392            .assists_by_editor
 393            .entry(editor.downgrade())
 394            .or_insert_with(|| EditorInlineAssists::new(&editor, window, cx));
 395        let mut assist_group = InlineAssistGroup::new();
 396        for (assist_id, range, prompt_editor, prompt_block_id, end_block_id) in assists {
 397            self.assists.insert(
 398                assist_id,
 399                InlineAssist::new(
 400                    assist_id,
 401                    assist_group_id,
 402                    assistant_panel.is_some(),
 403                    editor,
 404                    &prompt_editor,
 405                    prompt_block_id,
 406                    end_block_id,
 407                    range,
 408                    prompt_editor.read(cx).codegen.clone(),
 409                    workspace.clone(),
 410                    window,
 411                    cx,
 412                ),
 413            );
 414            assist_group.assist_ids.push(assist_id);
 415            editor_assists.assist_ids.push(assist_id);
 416        }
 417        self.assist_groups.insert(assist_group_id, assist_group);
 418
 419        if let Some(assist_id) = assist_to_focus {
 420            self.focus_assist(assist_id, window, cx);
 421        }
 422    }
 423
 424    pub fn suggest_assist(
 425        &mut self,
 426        editor: &Entity<Editor>,
 427        mut range: Range<Anchor>,
 428        initial_prompt: String,
 429        initial_transaction_id: Option<TransactionId>,
 430        focus: bool,
 431        workspace: Option<WeakEntity<Workspace>>,
 432        assistant_panel: Option<&Entity<AssistantPanel>>,
 433        window: &mut Window,
 434        cx: &mut App,
 435    ) -> InlineAssistId {
 436        let assist_group_id = self.next_assist_group_id.post_inc();
 437        let prompt_buffer = cx.new(|cx| Buffer::local(&initial_prompt, cx));
 438        let prompt_buffer = cx.new(|cx| MultiBuffer::singleton(prompt_buffer, cx));
 439
 440        let assist_id = self.next_assist_id.post_inc();
 441
 442        let buffer = editor.read(cx).buffer().clone();
 443        {
 444            let snapshot = buffer.read(cx).read(cx);
 445            range.start = range.start.bias_left(&snapshot);
 446            range.end = range.end.bias_right(&snapshot);
 447        }
 448
 449        let codegen = cx.new(|cx| {
 450            Codegen::new(
 451                editor.read(cx).buffer().clone(),
 452                range.clone(),
 453                initial_transaction_id,
 454                self.telemetry.clone(),
 455                self.prompt_builder.clone(),
 456                cx,
 457            )
 458        });
 459
 460        let gutter_dimensions = Arc::new(Mutex::new(GutterDimensions::default()));
 461        let prompt_editor = cx.new(|cx| {
 462            PromptEditor::new(
 463                assist_id,
 464                gutter_dimensions.clone(),
 465                self.prompt_history.clone(),
 466                prompt_buffer.clone(),
 467                codegen.clone(),
 468                editor,
 469                assistant_panel,
 470                workspace.clone(),
 471                self.fs.clone(),
 472                window,
 473                cx,
 474            )
 475        });
 476
 477        let [prompt_block_id, end_block_id] =
 478            self.insert_assist_blocks(editor, &range, &prompt_editor, cx);
 479
 480        let editor_assists = self
 481            .assists_by_editor
 482            .entry(editor.downgrade())
 483            .or_insert_with(|| EditorInlineAssists::new(&editor, window, cx));
 484
 485        let mut assist_group = InlineAssistGroup::new();
 486        self.assists.insert(
 487            assist_id,
 488            InlineAssist::new(
 489                assist_id,
 490                assist_group_id,
 491                assistant_panel.is_some(),
 492                editor,
 493                &prompt_editor,
 494                prompt_block_id,
 495                end_block_id,
 496                range,
 497                prompt_editor.read(cx).codegen.clone(),
 498                workspace.clone(),
 499                window,
 500                cx,
 501            ),
 502        );
 503        assist_group.assist_ids.push(assist_id);
 504        editor_assists.assist_ids.push(assist_id);
 505        self.assist_groups.insert(assist_group_id, assist_group);
 506
 507        if focus {
 508            self.focus_assist(assist_id, window, cx);
 509        }
 510
 511        assist_id
 512    }
 513
 514    fn insert_assist_blocks(
 515        &self,
 516        editor: &Entity<Editor>,
 517        range: &Range<Anchor>,
 518        prompt_editor: &Entity<PromptEditor>,
 519        cx: &mut App,
 520    ) -> [CustomBlockId; 2] {
 521        let prompt_editor_height = prompt_editor.update(cx, |prompt_editor, cx| {
 522            prompt_editor
 523                .editor
 524                .update(cx, |editor, cx| editor.max_point(cx).row().0 + 1 + 2)
 525        });
 526        let assist_blocks = vec![
 527            BlockProperties {
 528                style: BlockStyle::Sticky,
 529                placement: BlockPlacement::Above(range.start),
 530                height: Some(prompt_editor_height),
 531                render: build_assist_editor_renderer(prompt_editor),
 532                priority: 0,
 533            },
 534            BlockProperties {
 535                style: BlockStyle::Sticky,
 536                placement: BlockPlacement::Below(range.end),
 537                height: None,
 538                render: Arc::new(|cx| {
 539                    v_flex()
 540                        .h_full()
 541                        .w_full()
 542                        .border_t_1()
 543                        .border_color(cx.theme().status().info_border)
 544                        .into_any_element()
 545                }),
 546                priority: 0,
 547            },
 548        ];
 549
 550        editor.update(cx, |editor, cx| {
 551            let block_ids = editor.insert_blocks(assist_blocks, None, cx);
 552            [block_ids[0], block_ids[1]]
 553        })
 554    }
 555
 556    fn handle_prompt_editor_focus_in(&mut self, assist_id: InlineAssistId, cx: &mut App) {
 557        let assist = &self.assists[&assist_id];
 558        let Some(decorations) = assist.decorations.as_ref() else {
 559            return;
 560        };
 561        let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
 562        let editor_assists = self.assists_by_editor.get_mut(&assist.editor).unwrap();
 563
 564        assist_group.active_assist_id = Some(assist_id);
 565        if assist_group.linked {
 566            for assist_id in &assist_group.assist_ids {
 567                if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
 568                    decorations.prompt_editor.update(cx, |prompt_editor, cx| {
 569                        prompt_editor.set_show_cursor_when_unfocused(true, cx)
 570                    });
 571                }
 572            }
 573        }
 574
 575        assist
 576            .editor
 577            .update(cx, |editor, cx| {
 578                let scroll_top = editor.scroll_position(cx).y;
 579                let scroll_bottom = scroll_top + editor.visible_line_count().unwrap_or(0.);
 580                let prompt_row = editor
 581                    .row_for_block(decorations.prompt_block_id, cx)
 582                    .unwrap()
 583                    .0 as f32;
 584
 585                if (scroll_top..scroll_bottom).contains(&prompt_row) {
 586                    editor_assists.scroll_lock = Some(InlineAssistScrollLock {
 587                        assist_id,
 588                        distance_from_top: prompt_row - scroll_top,
 589                    });
 590                } else {
 591                    editor_assists.scroll_lock = None;
 592                }
 593            })
 594            .ok();
 595    }
 596
 597    fn handle_prompt_editor_focus_out(&mut self, assist_id: InlineAssistId, cx: &mut App) {
 598        let assist = &self.assists[&assist_id];
 599        let assist_group = self.assist_groups.get_mut(&assist.group_id).unwrap();
 600        if assist_group.active_assist_id == Some(assist_id) {
 601            assist_group.active_assist_id = None;
 602            if assist_group.linked {
 603                for assist_id in &assist_group.assist_ids {
 604                    if let Some(decorations) = self.assists[assist_id].decorations.as_ref() {
 605                        decorations.prompt_editor.update(cx, |prompt_editor, cx| {
 606                            prompt_editor.set_show_cursor_when_unfocused(false, cx)
 607                        });
 608                    }
 609                }
 610            }
 611        }
 612    }
 613
 614    fn handle_prompt_editor_event(
 615        &mut self,
 616        prompt_editor: Entity<PromptEditor>,
 617        event: &PromptEditorEvent,
 618        window: &mut Window,
 619        cx: &mut App,
 620    ) {
 621        let assist_id = prompt_editor.read(cx).id;
 622        match event {
 623            PromptEditorEvent::StartRequested => {
 624                self.start_assist(assist_id, window, cx);
 625            }
 626            PromptEditorEvent::StopRequested => {
 627                self.stop_assist(assist_id, cx);
 628            }
 629            PromptEditorEvent::ConfirmRequested => {
 630                self.finish_assist(assist_id, false, window, cx);
 631            }
 632            PromptEditorEvent::CancelRequested => {
 633                self.finish_assist(assist_id, true, window, cx);
 634            }
 635            PromptEditorEvent::DismissRequested => {
 636                self.dismiss_assist(assist_id, window, cx);
 637            }
 638        }
 639    }
 640
 641    fn handle_editor_newline(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 642        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 643            return;
 644        };
 645
 646        if editor.read(cx).selections.count() == 1 {
 647            let (selection, buffer) = editor.update(cx, |editor, cx| {
 648                (
 649                    editor.selections.newest::<usize>(cx),
 650                    editor.buffer().read(cx).snapshot(cx),
 651                )
 652            });
 653            for assist_id in &editor_assists.assist_ids {
 654                let assist = &self.assists[assist_id];
 655                let assist_range = assist.range.to_offset(&buffer);
 656                if assist_range.contains(&selection.start) && assist_range.contains(&selection.end)
 657                {
 658                    if matches!(assist.codegen.read(cx).status(cx), CodegenStatus::Pending) {
 659                        self.dismiss_assist(*assist_id, window, cx);
 660                    } else {
 661                        self.finish_assist(*assist_id, false, window, cx);
 662                    }
 663
 664                    return;
 665                }
 666            }
 667        }
 668
 669        cx.propagate();
 670    }
 671
 672    fn handle_editor_cancel(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 673        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 674            return;
 675        };
 676
 677        if editor.read(cx).selections.count() == 1 {
 678            let (selection, buffer) = editor.update(cx, |editor, cx| {
 679                (
 680                    editor.selections.newest::<usize>(cx),
 681                    editor.buffer().read(cx).snapshot(cx),
 682                )
 683            });
 684            let mut closest_assist_fallback = None;
 685            for assist_id in &editor_assists.assist_ids {
 686                let assist = &self.assists[assist_id];
 687                let assist_range = assist.range.to_offset(&buffer);
 688                if assist.decorations.is_some() {
 689                    if assist_range.contains(&selection.start)
 690                        && assist_range.contains(&selection.end)
 691                    {
 692                        self.focus_assist(*assist_id, window, cx);
 693                        return;
 694                    } else {
 695                        let distance_from_selection = assist_range
 696                            .start
 697                            .abs_diff(selection.start)
 698                            .min(assist_range.start.abs_diff(selection.end))
 699                            + assist_range
 700                                .end
 701                                .abs_diff(selection.start)
 702                                .min(assist_range.end.abs_diff(selection.end));
 703                        match closest_assist_fallback {
 704                            Some((_, old_distance)) => {
 705                                if distance_from_selection < old_distance {
 706                                    closest_assist_fallback =
 707                                        Some((assist_id, distance_from_selection));
 708                                }
 709                            }
 710                            None => {
 711                                closest_assist_fallback = Some((assist_id, distance_from_selection))
 712                            }
 713                        }
 714                    }
 715                }
 716            }
 717
 718            if let Some((&assist_id, _)) = closest_assist_fallback {
 719                self.focus_assist(assist_id, window, cx);
 720            }
 721        }
 722
 723        cx.propagate();
 724    }
 725
 726    fn handle_editor_release(
 727        &mut self,
 728        editor: WeakEntity<Editor>,
 729        window: &mut Window,
 730        cx: &mut App,
 731    ) {
 732        if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor) {
 733            for assist_id in editor_assists.assist_ids.clone() {
 734                self.finish_assist(assist_id, true, window, cx);
 735            }
 736        }
 737    }
 738
 739    fn handle_editor_change(&mut self, editor: Entity<Editor>, window: &mut Window, cx: &mut App) {
 740        let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) else {
 741            return;
 742        };
 743        let Some(scroll_lock) = editor_assists.scroll_lock.as_ref() else {
 744            return;
 745        };
 746        let assist = &self.assists[&scroll_lock.assist_id];
 747        let Some(decorations) = assist.decorations.as_ref() else {
 748            return;
 749        };
 750
 751        editor.update(cx, |editor, cx| {
 752            let scroll_position = editor.scroll_position(cx);
 753            let target_scroll_top = editor
 754                .row_for_block(decorations.prompt_block_id, cx)
 755                .unwrap()
 756                .0 as f32
 757                - scroll_lock.distance_from_top;
 758            if target_scroll_top != scroll_position.y {
 759                editor.set_scroll_position(point(scroll_position.x, target_scroll_top), window, cx);
 760            }
 761        });
 762    }
 763
 764    fn handle_editor_event(
 765        &mut self,
 766        editor: Entity<Editor>,
 767        event: &EditorEvent,
 768        window: &mut Window,
 769        cx: &mut App,
 770    ) {
 771        let Some(editor_assists) = self.assists_by_editor.get_mut(&editor.downgrade()) else {
 772            return;
 773        };
 774
 775        match event {
 776            EditorEvent::Edited { transaction_id } => {
 777                let buffer = editor.read(cx).buffer().read(cx);
 778                let edited_ranges =
 779                    buffer.edited_ranges_for_transaction::<usize>(*transaction_id, cx);
 780                let snapshot = buffer.snapshot(cx);
 781
 782                for assist_id in editor_assists.assist_ids.clone() {
 783                    let assist = &self.assists[&assist_id];
 784                    if matches!(
 785                        assist.codegen.read(cx).status(cx),
 786                        CodegenStatus::Error(_) | CodegenStatus::Done
 787                    ) {
 788                        let assist_range = assist.range.to_offset(&snapshot);
 789                        if edited_ranges
 790                            .iter()
 791                            .any(|range| range.overlaps(&assist_range))
 792                        {
 793                            self.finish_assist(assist_id, false, window, cx);
 794                        }
 795                    }
 796                }
 797            }
 798            EditorEvent::ScrollPositionChanged { .. } => {
 799                if let Some(scroll_lock) = editor_assists.scroll_lock.as_ref() {
 800                    let assist = &self.assists[&scroll_lock.assist_id];
 801                    if let Some(decorations) = assist.decorations.as_ref() {
 802                        let distance_from_top = editor.update(cx, |editor, cx| {
 803                            let scroll_top = editor.scroll_position(cx).y;
 804                            let prompt_row = editor
 805                                .row_for_block(decorations.prompt_block_id, cx)
 806                                .unwrap()
 807                                .0 as f32;
 808                            prompt_row - scroll_top
 809                        });
 810
 811                        if distance_from_top != scroll_lock.distance_from_top {
 812                            editor_assists.scroll_lock = None;
 813                        }
 814                    }
 815                }
 816            }
 817            EditorEvent::SelectionsChanged { .. } => {
 818                for assist_id in editor_assists.assist_ids.clone() {
 819                    let assist = &self.assists[&assist_id];
 820                    if let Some(decorations) = assist.decorations.as_ref() {
 821                        if decorations
 822                            .prompt_editor
 823                            .focus_handle(cx)
 824                            .is_focused(window)
 825                        {
 826                            return;
 827                        }
 828                    }
 829                }
 830
 831                editor_assists.scroll_lock = None;
 832            }
 833            _ => {}
 834        }
 835    }
 836
 837    pub fn finish_assist(
 838        &mut self,
 839        assist_id: InlineAssistId,
 840        undo: bool,
 841        window: &mut Window,
 842        cx: &mut App,
 843    ) {
 844        if let Some(assist) = self.assists.get(&assist_id) {
 845            let assist_group_id = assist.group_id;
 846            if self.assist_groups[&assist_group_id].linked {
 847                for assist_id in self.unlink_assist_group(assist_group_id, window, cx) {
 848                    self.finish_assist(assist_id, undo, window, cx);
 849                }
 850                return;
 851            }
 852        }
 853
 854        self.dismiss_assist(assist_id, window, cx);
 855
 856        if let Some(assist) = self.assists.remove(&assist_id) {
 857            if let hash_map::Entry::Occupied(mut entry) = self.assist_groups.entry(assist.group_id)
 858            {
 859                entry.get_mut().assist_ids.retain(|id| *id != assist_id);
 860                if entry.get().assist_ids.is_empty() {
 861                    entry.remove();
 862                }
 863            }
 864
 865            if let hash_map::Entry::Occupied(mut entry) =
 866                self.assists_by_editor.entry(assist.editor.clone())
 867            {
 868                entry.get_mut().assist_ids.retain(|id| *id != assist_id);
 869                if entry.get().assist_ids.is_empty() {
 870                    entry.remove();
 871                    if let Some(editor) = assist.editor.upgrade() {
 872                        self.update_editor_highlights(&editor, cx);
 873                    }
 874                } else {
 875                    entry.get().highlight_updates.send(()).ok();
 876                }
 877            }
 878
 879            let active_alternative = assist.codegen.read(cx).active_alternative().clone();
 880            let message_id = active_alternative.read(cx).message_id.clone();
 881
 882            if let Some(ConfiguredModel { model, .. }) =
 883                LanguageModelRegistry::read_global(cx).default_model()
 884            {
 885                let language_name = assist.editor.upgrade().and_then(|editor| {
 886                    let multibuffer = editor.read(cx).buffer().read(cx);
 887                    let multibuffer_snapshot = multibuffer.snapshot(cx);
 888                    let ranges = multibuffer_snapshot.range_to_buffer_ranges(assist.range.clone());
 889                    ranges
 890                        .first()
 891                        .and_then(|(buffer, _, _)| buffer.language())
 892                        .map(|language| language.name())
 893                });
 894                report_assistant_event(
 895                    AssistantEventData {
 896                        conversation_id: None,
 897                        kind: AssistantKind::Inline,
 898                        message_id,
 899                        phase: if undo {
 900                            AssistantPhase::Rejected
 901                        } else {
 902                            AssistantPhase::Accepted
 903                        },
 904                        model: model.telemetry_id(),
 905                        model_provider: model.provider_id().to_string(),
 906                        response_latency: None,
 907                        error_message: None,
 908                        language_name: language_name.map(|name| name.to_proto()),
 909                    },
 910                    Some(self.telemetry.clone()),
 911                    cx.http_client(),
 912                    model.api_key(cx),
 913                    cx.background_executor(),
 914                );
 915            }
 916
 917            if undo {
 918                assist.codegen.update(cx, |codegen, cx| codegen.undo(cx));
 919            } else {
 920                self.confirmed_assists.insert(assist_id, active_alternative);
 921            }
 922        }
 923    }
 924
 925    fn dismiss_assist(
 926        &mut self,
 927        assist_id: InlineAssistId,
 928        window: &mut Window,
 929        cx: &mut App,
 930    ) -> bool {
 931        let Some(assist) = self.assists.get_mut(&assist_id) else {
 932            return false;
 933        };
 934        let Some(editor) = assist.editor.upgrade() else {
 935            return false;
 936        };
 937        let Some(decorations) = assist.decorations.take() else {
 938            return false;
 939        };
 940
 941        editor.update(cx, |editor, cx| {
 942            let mut to_remove = decorations.removed_line_block_ids;
 943            to_remove.insert(decorations.prompt_block_id);
 944            to_remove.insert(decorations.end_block_id);
 945            editor.remove_blocks(to_remove, None, cx);
 946        });
 947
 948        if decorations
 949            .prompt_editor
 950            .focus_handle(cx)
 951            .contains_focused(window, cx)
 952        {
 953            self.focus_next_assist(assist_id, window, cx);
 954        }
 955
 956        if let Some(editor_assists) = self.assists_by_editor.get_mut(&editor.downgrade()) {
 957            if editor_assists
 958                .scroll_lock
 959                .as_ref()
 960                .map_or(false, |lock| lock.assist_id == assist_id)
 961            {
 962                editor_assists.scroll_lock = None;
 963            }
 964            editor_assists.highlight_updates.send(()).ok();
 965        }
 966
 967        true
 968    }
 969
 970    fn focus_next_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
 971        let Some(assist) = self.assists.get(&assist_id) else {
 972            return;
 973        };
 974
 975        let assist_group = &self.assist_groups[&assist.group_id];
 976        let assist_ix = assist_group
 977            .assist_ids
 978            .iter()
 979            .position(|id| *id == assist_id)
 980            .unwrap();
 981        let assist_ids = assist_group
 982            .assist_ids
 983            .iter()
 984            .skip(assist_ix + 1)
 985            .chain(assist_group.assist_ids.iter().take(assist_ix));
 986
 987        for assist_id in assist_ids {
 988            let assist = &self.assists[assist_id];
 989            if assist.decorations.is_some() {
 990                self.focus_assist(*assist_id, window, cx);
 991                return;
 992            }
 993        }
 994
 995        assist
 996            .editor
 997            .update(cx, |editor, cx| window.focus(&editor.focus_handle(cx)))
 998            .ok();
 999    }
1000
1001    fn focus_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1002        let Some(assist) = self.assists.get(&assist_id) else {
1003            return;
1004        };
1005
1006        if let Some(decorations) = assist.decorations.as_ref() {
1007            decorations.prompt_editor.update(cx, |prompt_editor, cx| {
1008                prompt_editor.editor.update(cx, |editor, cx| {
1009                    window.focus(&editor.focus_handle(cx));
1010                    editor.select_all(&SelectAll, window, cx);
1011                })
1012            });
1013        }
1014
1015        self.scroll_to_assist(assist_id, window, cx);
1016    }
1017
1018    pub fn scroll_to_assist(
1019        &mut self,
1020        assist_id: InlineAssistId,
1021        window: &mut Window,
1022        cx: &mut App,
1023    ) {
1024        let Some(assist) = self.assists.get(&assist_id) else {
1025            return;
1026        };
1027        let Some(editor) = assist.editor.upgrade() else {
1028            return;
1029        };
1030
1031        let position = assist.range.start;
1032        editor.update(cx, |editor, cx| {
1033            editor.change_selections(None, window, cx, |selections| {
1034                selections.select_anchor_ranges([position..position])
1035            });
1036
1037            let mut scroll_target_top;
1038            let mut scroll_target_bottom;
1039            if let Some(decorations) = assist.decorations.as_ref() {
1040                scroll_target_top = editor
1041                    .row_for_block(decorations.prompt_block_id, cx)
1042                    .unwrap()
1043                    .0 as f32;
1044                scroll_target_bottom = editor
1045                    .row_for_block(decorations.end_block_id, cx)
1046                    .unwrap()
1047                    .0 as f32;
1048            } else {
1049                let snapshot = editor.snapshot(window, cx);
1050                let start_row = assist
1051                    .range
1052                    .start
1053                    .to_display_point(&snapshot.display_snapshot)
1054                    .row();
1055                scroll_target_top = start_row.0 as f32;
1056                scroll_target_bottom = scroll_target_top + 1.;
1057            }
1058            scroll_target_top -= editor.vertical_scroll_margin() as f32;
1059            scroll_target_bottom += editor.vertical_scroll_margin() as f32;
1060
1061            let height_in_lines = editor.visible_line_count().unwrap_or(0.);
1062            let scroll_top = editor.scroll_position(cx).y;
1063            let scroll_bottom = scroll_top + height_in_lines;
1064
1065            if scroll_target_top < scroll_top {
1066                editor.set_scroll_position(point(0., scroll_target_top), window, cx);
1067            } else if scroll_target_bottom > scroll_bottom {
1068                if (scroll_target_bottom - scroll_target_top) <= height_in_lines {
1069                    editor.set_scroll_position(
1070                        point(0., scroll_target_bottom - height_in_lines),
1071                        window,
1072                        cx,
1073                    );
1074                } else {
1075                    editor.set_scroll_position(point(0., scroll_target_top), window, cx);
1076                }
1077            }
1078        });
1079    }
1080
1081    fn unlink_assist_group(
1082        &mut self,
1083        assist_group_id: InlineAssistGroupId,
1084        window: &mut Window,
1085        cx: &mut App,
1086    ) -> Vec<InlineAssistId> {
1087        let assist_group = self.assist_groups.get_mut(&assist_group_id).unwrap();
1088        assist_group.linked = false;
1089        for assist_id in &assist_group.assist_ids {
1090            let assist = self.assists.get_mut(assist_id).unwrap();
1091            if let Some(editor_decorations) = assist.decorations.as_ref() {
1092                editor_decorations
1093                    .prompt_editor
1094                    .update(cx, |prompt_editor, cx| prompt_editor.unlink(window, cx));
1095            }
1096        }
1097        assist_group.assist_ids.clone()
1098    }
1099
1100    pub fn start_assist(&mut self, assist_id: InlineAssistId, window: &mut Window, cx: &mut App) {
1101        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1102            assist
1103        } else {
1104            return;
1105        };
1106
1107        let assist_group_id = assist.group_id;
1108        if self.assist_groups[&assist_group_id].linked {
1109            for assist_id in self.unlink_assist_group(assist_group_id, window, cx) {
1110                self.start_assist(assist_id, window, cx);
1111            }
1112            return;
1113        }
1114
1115        let Some(user_prompt) = assist.user_prompt(cx) else {
1116            return;
1117        };
1118
1119        self.prompt_history.retain(|prompt| *prompt != user_prompt);
1120        self.prompt_history.push_back(user_prompt.clone());
1121        if self.prompt_history.len() > PROMPT_HISTORY_MAX_LEN {
1122            self.prompt_history.pop_front();
1123        }
1124
1125        let assistant_panel_context = assist.assistant_panel_context(cx);
1126
1127        assist
1128            .codegen
1129            .update(cx, |codegen, cx| {
1130                codegen.start(user_prompt, assistant_panel_context, cx)
1131            })
1132            .log_err();
1133    }
1134
1135    pub fn stop_assist(&mut self, assist_id: InlineAssistId, cx: &mut App) {
1136        let assist = if let Some(assist) = self.assists.get_mut(&assist_id) {
1137            assist
1138        } else {
1139            return;
1140        };
1141
1142        assist.codegen.update(cx, |codegen, cx| codegen.stop(cx));
1143    }
1144
1145    fn update_editor_highlights(&self, editor: &Entity<Editor>, cx: &mut App) {
1146        let mut gutter_pending_ranges = Vec::new();
1147        let mut gutter_transformed_ranges = Vec::new();
1148        let mut foreground_ranges = Vec::new();
1149        let mut inserted_row_ranges = Vec::new();
1150        let empty_assist_ids = Vec::new();
1151        let assist_ids = self
1152            .assists_by_editor
1153            .get(&editor.downgrade())
1154            .map_or(&empty_assist_ids, |editor_assists| {
1155                &editor_assists.assist_ids
1156            });
1157
1158        for assist_id in assist_ids {
1159            if let Some(assist) = self.assists.get(assist_id) {
1160                let codegen = assist.codegen.read(cx);
1161                let buffer = codegen.buffer(cx).read(cx).read(cx);
1162                foreground_ranges.extend(codegen.last_equal_ranges(cx).iter().cloned());
1163
1164                let pending_range =
1165                    codegen.edit_position(cx).unwrap_or(assist.range.start)..assist.range.end;
1166                if pending_range.end.to_offset(&buffer) > pending_range.start.to_offset(&buffer) {
1167                    gutter_pending_ranges.push(pending_range);
1168                }
1169
1170                if let Some(edit_position) = codegen.edit_position(cx) {
1171                    let edited_range = assist.range.start..edit_position;
1172                    if edited_range.end.to_offset(&buffer) > edited_range.start.to_offset(&buffer) {
1173                        gutter_transformed_ranges.push(edited_range);
1174                    }
1175                }
1176
1177                if assist.decorations.is_some() {
1178                    inserted_row_ranges
1179                        .extend(codegen.diff(cx).inserted_row_ranges.iter().cloned());
1180                }
1181            }
1182        }
1183
1184        let snapshot = editor.read(cx).buffer().read(cx).snapshot(cx);
1185        merge_ranges(&mut foreground_ranges, &snapshot);
1186        merge_ranges(&mut gutter_pending_ranges, &snapshot);
1187        merge_ranges(&mut gutter_transformed_ranges, &snapshot);
1188        editor.update(cx, |editor, cx| {
1189            enum GutterPendingRange {}
1190            if gutter_pending_ranges.is_empty() {
1191                editor.clear_gutter_highlights::<GutterPendingRange>(cx);
1192            } else {
1193                editor.highlight_gutter::<GutterPendingRange>(
1194                    &gutter_pending_ranges,
1195                    |cx| cx.theme().status().info_background,
1196                    cx,
1197                )
1198            }
1199
1200            enum GutterTransformedRange {}
1201            if gutter_transformed_ranges.is_empty() {
1202                editor.clear_gutter_highlights::<GutterTransformedRange>(cx);
1203            } else {
1204                editor.highlight_gutter::<GutterTransformedRange>(
1205                    &gutter_transformed_ranges,
1206                    |cx| cx.theme().status().info,
1207                    cx,
1208                )
1209            }
1210
1211            if foreground_ranges.is_empty() {
1212                editor.clear_highlights::<InlineAssist>(cx);
1213            } else {
1214                editor.highlight_text::<InlineAssist>(
1215                    foreground_ranges,
1216                    HighlightStyle {
1217                        fade_out: Some(0.6),
1218                        ..Default::default()
1219                    },
1220                    cx,
1221                );
1222            }
1223
1224            editor.clear_row_highlights::<InlineAssist>();
1225            for row_range in inserted_row_ranges {
1226                editor.highlight_rows::<InlineAssist>(
1227                    row_range,
1228                    cx.theme().status().info_background,
1229                    false,
1230                    cx,
1231                );
1232            }
1233        });
1234    }
1235
1236    fn update_editor_blocks(
1237        &mut self,
1238        editor: &Entity<Editor>,
1239        assist_id: InlineAssistId,
1240        window: &mut Window,
1241        cx: &mut App,
1242    ) {
1243        let Some(assist) = self.assists.get_mut(&assist_id) else {
1244            return;
1245        };
1246        let Some(decorations) = assist.decorations.as_mut() else {
1247            return;
1248        };
1249
1250        let codegen = assist.codegen.read(cx);
1251        let old_snapshot = codegen.snapshot(cx);
1252        let old_buffer = codegen.old_buffer(cx);
1253        let deleted_row_ranges = codegen.diff(cx).deleted_row_ranges.clone();
1254
1255        editor.update(cx, |editor, cx| {
1256            let old_blocks = mem::take(&mut decorations.removed_line_block_ids);
1257            editor.remove_blocks(old_blocks, None, cx);
1258
1259            let mut new_blocks = Vec::new();
1260            for (new_row, old_row_range) in deleted_row_ranges {
1261                let (_, buffer_start) = old_snapshot
1262                    .point_to_buffer_offset(Point::new(*old_row_range.start(), 0))
1263                    .unwrap();
1264                let (_, buffer_end) = old_snapshot
1265                    .point_to_buffer_offset(Point::new(
1266                        *old_row_range.end(),
1267                        old_snapshot.line_len(MultiBufferRow(*old_row_range.end())),
1268                    ))
1269                    .unwrap();
1270
1271                let deleted_lines_editor = cx.new(|cx| {
1272                    let multi_buffer =
1273                        cx.new(|_| MultiBuffer::without_headers(language::Capability::ReadOnly));
1274                    multi_buffer.update(cx, |multi_buffer, cx| {
1275                        multi_buffer.push_excerpts(
1276                            old_buffer.clone(),
1277                            Some(ExcerptRange::new(buffer_start..buffer_end)),
1278                            cx,
1279                        );
1280                    });
1281
1282                    enum DeletedLines {}
1283                    let mut editor = Editor::for_multibuffer(multi_buffer, None, window, cx);
1284                    editor.set_soft_wrap_mode(language::language_settings::SoftWrap::None, cx);
1285                    editor.set_show_wrap_guides(false, cx);
1286                    editor.set_show_gutter(false, cx);
1287                    editor.scroll_manager.set_forbid_vertical_scroll(true);
1288                    editor.set_show_scrollbars(false, cx);
1289                    editor.set_read_only(true);
1290                    editor.set_show_edit_predictions(Some(false), window, cx);
1291                    editor.highlight_rows::<DeletedLines>(
1292                        Anchor::min()..Anchor::max(),
1293                        cx.theme().status().deleted_background,
1294                        false,
1295                        cx,
1296                    );
1297                    editor
1298                });
1299
1300                let height =
1301                    deleted_lines_editor.update(cx, |editor, cx| editor.max_point(cx).row().0 + 1);
1302                new_blocks.push(BlockProperties {
1303                    placement: BlockPlacement::Above(new_row),
1304                    height: Some(height),
1305                    style: BlockStyle::Flex,
1306                    render: Arc::new(move |cx| {
1307                        div()
1308                            .block_mouse_down()
1309                            .bg(cx.theme().status().deleted_background)
1310                            .size_full()
1311                            .h(height as f32 * cx.window.line_height())
1312                            .pl(cx.gutter_dimensions.full_width())
1313                            .child(deleted_lines_editor.clone())
1314                            .into_any_element()
1315                    }),
1316                    priority: 0,
1317                });
1318            }
1319
1320            decorations.removed_line_block_ids = editor
1321                .insert_blocks(new_blocks, None, cx)
1322                .into_iter()
1323                .collect();
1324        })
1325    }
1326}
1327
1328struct EditorInlineAssists {
1329    assist_ids: Vec<InlineAssistId>,
1330    scroll_lock: Option<InlineAssistScrollLock>,
1331    highlight_updates: async_watch::Sender<()>,
1332    _update_highlights: Task<Result<()>>,
1333    _subscriptions: Vec<gpui::Subscription>,
1334}
1335
1336struct InlineAssistScrollLock {
1337    assist_id: InlineAssistId,
1338    distance_from_top: f32,
1339}
1340
1341impl EditorInlineAssists {
1342    fn new(editor: &Entity<Editor>, window: &mut Window, cx: &mut App) -> Self {
1343        let (highlight_updates_tx, mut highlight_updates_rx) = async_watch::channel(());
1344        Self {
1345            assist_ids: Vec::new(),
1346            scroll_lock: None,
1347            highlight_updates: highlight_updates_tx,
1348            _update_highlights: cx.spawn({
1349                let editor = editor.downgrade();
1350                async move |cx| {
1351                    while let Ok(()) = highlight_updates_rx.changed().await {
1352                        let editor = editor.upgrade().context("editor was dropped")?;
1353                        cx.update_global(|assistant: &mut InlineAssistant, cx| {
1354                            assistant.update_editor_highlights(&editor, cx);
1355                        })?;
1356                    }
1357                    Ok(())
1358                }
1359            }),
1360            _subscriptions: vec![
1361                cx.observe_release_in(editor, window, {
1362                    let editor = editor.downgrade();
1363                    |_, window, cx| {
1364                        InlineAssistant::update_global(cx, |this, cx| {
1365                            this.handle_editor_release(editor, window, cx);
1366                        })
1367                    }
1368                }),
1369                window.observe(editor, cx, move |editor, window, cx| {
1370                    InlineAssistant::update_global(cx, |this, cx| {
1371                        this.handle_editor_change(editor, window, cx)
1372                    })
1373                }),
1374                window.subscribe(editor, cx, move |editor, event, window, cx| {
1375                    InlineAssistant::update_global(cx, |this, cx| {
1376                        this.handle_editor_event(editor, event, window, cx)
1377                    })
1378                }),
1379                editor.update(cx, |editor, cx| {
1380                    let editor_handle = cx.entity().downgrade();
1381                    editor.register_action(move |_: &editor::actions::Newline, window, cx| {
1382                        InlineAssistant::update_global(cx, |this, cx| {
1383                            if let Some(editor) = editor_handle.upgrade() {
1384                                this.handle_editor_newline(editor, window, cx)
1385                            }
1386                        })
1387                    })
1388                }),
1389                editor.update(cx, |editor, cx| {
1390                    let editor_handle = cx.entity().downgrade();
1391                    editor.register_action(move |_: &editor::actions::Cancel, window, cx| {
1392                        InlineAssistant::update_global(cx, |this, cx| {
1393                            if let Some(editor) = editor_handle.upgrade() {
1394                                this.handle_editor_cancel(editor, window, cx)
1395                            }
1396                        })
1397                    })
1398                }),
1399            ],
1400        }
1401    }
1402}
1403
1404struct InlineAssistGroup {
1405    assist_ids: Vec<InlineAssistId>,
1406    linked: bool,
1407    active_assist_id: Option<InlineAssistId>,
1408}
1409
1410impl InlineAssistGroup {
1411    fn new() -> Self {
1412        Self {
1413            assist_ids: Vec::new(),
1414            linked: true,
1415            active_assist_id: None,
1416        }
1417    }
1418}
1419
1420fn build_assist_editor_renderer(editor: &Entity<PromptEditor>) -> RenderBlock {
1421    let editor = editor.clone();
1422    Arc::new(move |cx: &mut BlockContext| {
1423        *editor.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
1424        editor.clone().into_any_element()
1425    })
1426}
1427
1428#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
1429pub struct InlineAssistId(usize);
1430
1431impl InlineAssistId {
1432    fn post_inc(&mut self) -> InlineAssistId {
1433        let id = *self;
1434        self.0 += 1;
1435        id
1436    }
1437}
1438
1439#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
1440struct InlineAssistGroupId(usize);
1441
1442impl InlineAssistGroupId {
1443    fn post_inc(&mut self) -> InlineAssistGroupId {
1444        let id = *self;
1445        self.0 += 1;
1446        id
1447    }
1448}
1449
1450enum PromptEditorEvent {
1451    StartRequested,
1452    StopRequested,
1453    ConfirmRequested,
1454    CancelRequested,
1455    DismissRequested,
1456}
1457
1458struct PromptEditor {
1459    id: InlineAssistId,
1460    editor: Entity<Editor>,
1461    language_model_selector: Entity<LanguageModelSelector>,
1462    edited_since_done: bool,
1463    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
1464    prompt_history: VecDeque<String>,
1465    prompt_history_ix: Option<usize>,
1466    pending_prompt: String,
1467    codegen: Entity<Codegen>,
1468    _codegen_subscription: Subscription,
1469    editor_subscriptions: Vec<Subscription>,
1470    pending_token_count: Task<Result<()>>,
1471    token_counts: Option<TokenCounts>,
1472    _token_count_subscriptions: Vec<Subscription>,
1473    workspace: Option<WeakEntity<Workspace>>,
1474    show_rate_limit_notice: bool,
1475}
1476
1477#[derive(Copy, Clone)]
1478pub struct TokenCounts {
1479    total: usize,
1480    assistant_panel: usize,
1481}
1482
1483impl EventEmitter<PromptEditorEvent> for PromptEditor {}
1484
1485impl Render for PromptEditor {
1486    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1487        let gutter_dimensions = *self.gutter_dimensions.lock();
1488        let codegen = self.codegen.read(cx);
1489
1490        let mut buttons = Vec::new();
1491        if codegen.alternative_count(cx) > 1 {
1492            buttons.push(self.render_cycle_controls(cx));
1493        }
1494
1495        let status = codegen.status(cx);
1496        buttons.extend(match status {
1497            CodegenStatus::Idle => {
1498                vec![
1499                    IconButton::new("cancel", IconName::Close)
1500                        .icon_color(Color::Muted)
1501                        .shape(IconButtonShape::Square)
1502                        .tooltip(|window, cx| {
1503                            Tooltip::for_action("Cancel Assist", &menu::Cancel, window, cx)
1504                        })
1505                        .on_click(
1506                            cx.listener(|_, _, _, cx| cx.emit(PromptEditorEvent::CancelRequested)),
1507                        )
1508                        .into_any_element(),
1509                    IconButton::new("start", IconName::SparkleAlt)
1510                        .icon_color(Color::Muted)
1511                        .shape(IconButtonShape::Square)
1512                        .tooltip(|window, cx| {
1513                            Tooltip::for_action("Transform", &menu::Confirm, window, cx)
1514                        })
1515                        .on_click(
1516                            cx.listener(|_, _, _, cx| cx.emit(PromptEditorEvent::StartRequested)),
1517                        )
1518                        .into_any_element(),
1519                ]
1520            }
1521            CodegenStatus::Pending => {
1522                vec![
1523                    IconButton::new("cancel", IconName::Close)
1524                        .icon_color(Color::Muted)
1525                        .shape(IconButtonShape::Square)
1526                        .tooltip(Tooltip::text("Cancel Assist"))
1527                        .on_click(
1528                            cx.listener(|_, _, _, cx| cx.emit(PromptEditorEvent::CancelRequested)),
1529                        )
1530                        .into_any_element(),
1531                    IconButton::new("stop", IconName::Stop)
1532                        .icon_color(Color::Error)
1533                        .shape(IconButtonShape::Square)
1534                        .tooltip(|window, cx| {
1535                            Tooltip::with_meta(
1536                                "Interrupt Transformation",
1537                                Some(&menu::Cancel),
1538                                "Changes won't be discarded",
1539                                window,
1540                                cx,
1541                            )
1542                        })
1543                        .on_click(
1544                            cx.listener(|_, _, _, cx| cx.emit(PromptEditorEvent::StopRequested)),
1545                        )
1546                        .into_any_element(),
1547                ]
1548            }
1549            CodegenStatus::Error(_) | CodegenStatus::Done => {
1550                let must_rerun =
1551                    self.edited_since_done || matches!(status, CodegenStatus::Error(_));
1552                // when accept button isn't visible, then restart maps to confirm
1553                // when accept button is visible, then restart must be mapped to an alternate keyboard shortcut
1554                let restart_key: &dyn gpui::Action = if must_rerun {
1555                    &menu::Confirm
1556                } else {
1557                    &menu::Restart
1558                };
1559                vec![
1560                    IconButton::new("cancel", IconName::Close)
1561                        .icon_color(Color::Muted)
1562                        .shape(IconButtonShape::Square)
1563                        .tooltip(|window, cx| {
1564                            Tooltip::for_action("Cancel Assist", &menu::Cancel, window, cx)
1565                        })
1566                        .on_click(
1567                            cx.listener(|_, _, _, cx| cx.emit(PromptEditorEvent::CancelRequested)),
1568                        )
1569                        .into_any_element(),
1570                    IconButton::new("restart", IconName::RotateCw)
1571                        .icon_color(Color::Muted)
1572                        .shape(IconButtonShape::Square)
1573                        .tooltip(|window, cx| {
1574                            Tooltip::with_meta(
1575                                "Regenerate Transformation",
1576                                Some(restart_key),
1577                                "Current change will be discarded",
1578                                window,
1579                                cx,
1580                            )
1581                        })
1582                        .on_click(cx.listener(|_, _, _, cx| {
1583                            cx.emit(PromptEditorEvent::StartRequested);
1584                        }))
1585                        .into_any_element(),
1586                    if !must_rerun {
1587                        IconButton::new("confirm", IconName::Check)
1588                            .icon_color(Color::Info)
1589                            .shape(IconButtonShape::Square)
1590                            .tooltip(|window, cx| {
1591                                Tooltip::for_action("Confirm Assist", &menu::Confirm, window, cx)
1592                            })
1593                            .on_click(cx.listener(|_, _, _, cx| {
1594                                cx.emit(PromptEditorEvent::ConfirmRequested);
1595                            }))
1596                            .into_any_element()
1597                    } else {
1598                        div().into_any_element()
1599                    },
1600                ]
1601            }
1602        });
1603
1604        h_flex()
1605            .key_context("PromptEditor")
1606            .bg(cx.theme().colors().editor_background)
1607            .block_mouse_down()
1608            .cursor(CursorStyle::Arrow)
1609            .border_y_1()
1610            .border_color(cx.theme().status().info_border)
1611            .size_full()
1612            .py(window.line_height() / 2.5)
1613            .on_action(cx.listener(Self::confirm))
1614            .on_action(cx.listener(Self::cancel))
1615            .on_action(cx.listener(Self::restart))
1616            .on_action(cx.listener(Self::move_up))
1617            .on_action(cx.listener(Self::move_down))
1618            .capture_action(cx.listener(Self::cycle_prev))
1619            .capture_action(cx.listener(Self::cycle_next))
1620            .child(
1621                h_flex()
1622                    .w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0))
1623                    .justify_center()
1624                    .gap_2()
1625                    .child(LanguageModelSelectorPopoverMenu::new(
1626                        self.language_model_selector.clone(),
1627                        IconButton::new("context", IconName::SettingsAlt)
1628                            .shape(IconButtonShape::Square)
1629                            .icon_size(IconSize::Small)
1630                            .icon_color(Color::Muted),
1631                        move |window, cx| {
1632                            Tooltip::with_meta(
1633                                format!(
1634                                    "Using {}",
1635                                    LanguageModelRegistry::read_global(cx)
1636                                        .default_model()
1637                                        .map(|default| default.model.name().0)
1638                                        .unwrap_or_else(|| "No model selected".into()),
1639                                ),
1640                                None,
1641                                "Change Model",
1642                                window,
1643                                cx,
1644                            )
1645                        },
1646                        gpui::Corner::TopRight,
1647                    ))
1648                    .map(|el| {
1649                        let CodegenStatus::Error(error) = self.codegen.read(cx).status(cx) else {
1650                            return el;
1651                        };
1652
1653                        let error_message = SharedString::from(error.to_string());
1654                        if error.error_code() == proto::ErrorCode::RateLimitExceeded
1655                            && cx.has_flag::<ZedPro>()
1656                        {
1657                            el.child(
1658                                v_flex()
1659                                    .child(
1660                                        IconButton::new("rate-limit-error", IconName::XCircle)
1661                                            .toggle_state(self.show_rate_limit_notice)
1662                                            .shape(IconButtonShape::Square)
1663                                            .icon_size(IconSize::Small)
1664                                            .on_click(cx.listener(Self::toggle_rate_limit_notice)),
1665                                    )
1666                                    .children(self.show_rate_limit_notice.then(|| {
1667                                        deferred(
1668                                            anchored()
1669                                                .position_mode(gpui::AnchoredPositionMode::Local)
1670                                                .position(point(px(0.), px(24.)))
1671                                                .anchor(gpui::Corner::TopLeft)
1672                                                .child(self.render_rate_limit_notice(cx)),
1673                                        )
1674                                    })),
1675                            )
1676                        } else {
1677                            el.child(
1678                                div()
1679                                    .id("error")
1680                                    .tooltip(Tooltip::text(error_message))
1681                                    .child(
1682                                        Icon::new(IconName::XCircle)
1683                                            .size(IconSize::Small)
1684                                            .color(Color::Error),
1685                                    ),
1686                            )
1687                        }
1688                    }),
1689            )
1690            .child(div().flex_1().child(self.render_prompt_editor(cx)))
1691            .child(
1692                h_flex()
1693                    .gap_2()
1694                    .pr_6()
1695                    .children(self.render_token_count(cx))
1696                    .children(buttons),
1697            )
1698    }
1699}
1700
1701impl Focusable for PromptEditor {
1702    fn focus_handle(&self, cx: &App) -> FocusHandle {
1703        self.editor.focus_handle(cx)
1704    }
1705}
1706
1707impl PromptEditor {
1708    const MAX_LINES: u8 = 8;
1709
1710    fn new(
1711        id: InlineAssistId,
1712        gutter_dimensions: Arc<Mutex<GutterDimensions>>,
1713        prompt_history: VecDeque<String>,
1714        prompt_buffer: Entity<MultiBuffer>,
1715        codegen: Entity<Codegen>,
1716        parent_editor: &Entity<Editor>,
1717        assistant_panel: Option<&Entity<AssistantPanel>>,
1718        workspace: Option<WeakEntity<Workspace>>,
1719        fs: Arc<dyn Fs>,
1720        window: &mut Window,
1721        cx: &mut Context<Self>,
1722    ) -> Self {
1723        let prompt_editor = cx.new(|cx| {
1724            let mut editor = Editor::new(
1725                EditorMode::AutoHeight {
1726                    max_lines: Self::MAX_LINES as usize,
1727                },
1728                prompt_buffer,
1729                None,
1730                window,
1731                cx,
1732            );
1733            editor.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
1734            // Since the prompt editors for all inline assistants are linked,
1735            // always show the cursor (even when it isn't focused) because
1736            // typing in one will make what you typed appear in all of them.
1737            editor.set_show_cursor_when_unfocused(true, cx);
1738            editor.set_placeholder_text(Self::placeholder_text(codegen.read(cx), window, cx), cx);
1739            editor
1740        });
1741
1742        let mut token_count_subscriptions = Vec::new();
1743        token_count_subscriptions.push(cx.subscribe_in(
1744            parent_editor,
1745            window,
1746            Self::handle_parent_editor_event,
1747        ));
1748        if let Some(assistant_panel) = assistant_panel {
1749            token_count_subscriptions.push(cx.subscribe_in(
1750                assistant_panel,
1751                window,
1752                Self::handle_assistant_panel_event,
1753            ));
1754        }
1755
1756        let mut this = Self {
1757            id,
1758            editor: prompt_editor,
1759            language_model_selector: cx.new(|cx| {
1760                let fs = fs.clone();
1761                LanguageModelSelector::new(
1762                    move |model, cx| {
1763                        update_settings_file::<AssistantSettings>(
1764                            fs.clone(),
1765                            cx,
1766                            move |settings, _| settings.set_model(model.clone()),
1767                        );
1768                    },
1769                    window,
1770                    cx,
1771                )
1772            }),
1773            edited_since_done: false,
1774            gutter_dimensions,
1775            prompt_history,
1776            prompt_history_ix: None,
1777            pending_prompt: String::new(),
1778            _codegen_subscription: cx.observe(&codegen, Self::handle_codegen_changed),
1779            editor_subscriptions: Vec::new(),
1780            codegen,
1781            pending_token_count: Task::ready(Ok(())),
1782            token_counts: None,
1783            _token_count_subscriptions: token_count_subscriptions,
1784            workspace,
1785            show_rate_limit_notice: false,
1786        };
1787        this.count_tokens(cx);
1788        this.subscribe_to_editor(window, cx);
1789        this
1790    }
1791
1792    fn subscribe_to_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1793        self.editor_subscriptions.clear();
1794        self.editor_subscriptions.push(cx.subscribe_in(
1795            &self.editor,
1796            window,
1797            Self::handle_prompt_editor_events,
1798        ));
1799    }
1800
1801    fn set_show_cursor_when_unfocused(
1802        &mut self,
1803        show_cursor_when_unfocused: bool,
1804        cx: &mut Context<Self>,
1805    ) {
1806        self.editor.update(cx, |editor, cx| {
1807            editor.set_show_cursor_when_unfocused(show_cursor_when_unfocused, cx)
1808        });
1809    }
1810
1811    fn unlink(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1812        let prompt = self.prompt(cx);
1813        let focus = self.editor.focus_handle(cx).contains_focused(window, cx);
1814        self.editor = cx.new(|cx| {
1815            let mut editor = Editor::auto_height(Self::MAX_LINES as usize, window, cx);
1816            editor.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
1817            editor.set_placeholder_text(
1818                Self::placeholder_text(self.codegen.read(cx), window, cx),
1819                cx,
1820            );
1821            editor.set_placeholder_text("Add a prompt…", cx);
1822            editor.set_text(prompt, window, cx);
1823            if focus {
1824                window.focus(&editor.focus_handle(cx));
1825            }
1826            editor
1827        });
1828        self.subscribe_to_editor(window, cx);
1829    }
1830
1831    fn placeholder_text(codegen: &Codegen, window: &Window, cx: &App) -> String {
1832        let context_keybinding = text_for_action(&zed_actions::assistant::ToggleFocus, window, cx)
1833            .map(|keybinding| format!("{keybinding} for context"))
1834            .unwrap_or_default();
1835
1836        let action = if codegen.is_insertion {
1837            "Generate"
1838        } else {
1839            "Transform"
1840        };
1841
1842        format!("{action}{context_keybinding} • ↓↑ for history")
1843    }
1844
1845    fn prompt(&self, cx: &App) -> String {
1846        self.editor.read(cx).text(cx)
1847    }
1848
1849    fn toggle_rate_limit_notice(
1850        &mut self,
1851        _: &ClickEvent,
1852        window: &mut Window,
1853        cx: &mut Context<Self>,
1854    ) {
1855        self.show_rate_limit_notice = !self.show_rate_limit_notice;
1856        if self.show_rate_limit_notice {
1857            window.focus(&self.editor.focus_handle(cx));
1858        }
1859        cx.notify();
1860    }
1861
1862    fn handle_parent_editor_event(
1863        &mut self,
1864        _: &Entity<Editor>,
1865        event: &EditorEvent,
1866        _: &mut Window,
1867        cx: &mut Context<Self>,
1868    ) {
1869        if let EditorEvent::BufferEdited { .. } = event {
1870            self.count_tokens(cx);
1871        }
1872    }
1873
1874    fn handle_assistant_panel_event(
1875        &mut self,
1876        _: &Entity<AssistantPanel>,
1877        event: &AssistantPanelEvent,
1878        _: &mut Window,
1879        cx: &mut Context<Self>,
1880    ) {
1881        let AssistantPanelEvent::ContextEdited { .. } = event;
1882        self.count_tokens(cx);
1883    }
1884
1885    fn count_tokens(&mut self, cx: &mut Context<Self>) {
1886        let assist_id = self.id;
1887        self.pending_token_count = cx.spawn(async move |this, cx| {
1888            cx.background_executor().timer(Duration::from_secs(1)).await;
1889            let token_count = cx
1890                .update_global(|inline_assistant: &mut InlineAssistant, cx| {
1891                    let assist = inline_assistant
1892                        .assists
1893                        .get(&assist_id)
1894                        .context("assist not found")?;
1895                    anyhow::Ok(assist.count_tokens(cx))
1896                })??
1897                .await?;
1898
1899            this.update(cx, |this, cx| {
1900                this.token_counts = Some(token_count);
1901                cx.notify();
1902            })
1903        })
1904    }
1905
1906    fn handle_prompt_editor_events(
1907        &mut self,
1908        _: &Entity<Editor>,
1909        event: &EditorEvent,
1910        window: &mut Window,
1911        cx: &mut Context<Self>,
1912    ) {
1913        match event {
1914            EditorEvent::Edited { .. } => {
1915                if let Some(workspace) = window.root::<Workspace>().flatten() {
1916                    workspace.update(cx, |workspace, cx| {
1917                        let is_via_ssh = workspace
1918                            .project()
1919                            .update(cx, |project, _| project.is_via_ssh());
1920
1921                        workspace
1922                            .client()
1923                            .telemetry()
1924                            .log_edit_event("inline assist", is_via_ssh);
1925                    });
1926                }
1927                let prompt = self.editor.read(cx).text(cx);
1928                if self
1929                    .prompt_history_ix
1930                    .map_or(true, |ix| self.prompt_history[ix] != prompt)
1931                {
1932                    self.prompt_history_ix.take();
1933                    self.pending_prompt = prompt;
1934                }
1935
1936                self.edited_since_done = true;
1937                cx.notify();
1938            }
1939            EditorEvent::BufferEdited => {
1940                self.count_tokens(cx);
1941            }
1942            EditorEvent::Blurred => {
1943                if self.show_rate_limit_notice {
1944                    self.show_rate_limit_notice = false;
1945                    cx.notify();
1946                }
1947            }
1948            _ => {}
1949        }
1950    }
1951
1952    fn handle_codegen_changed(&mut self, _: Entity<Codegen>, cx: &mut Context<Self>) {
1953        match self.codegen.read(cx).status(cx) {
1954            CodegenStatus::Idle => {
1955                self.editor
1956                    .update(cx, |editor, _| editor.set_read_only(false));
1957            }
1958            CodegenStatus::Pending => {
1959                self.editor
1960                    .update(cx, |editor, _| editor.set_read_only(true));
1961            }
1962            CodegenStatus::Done => {
1963                self.edited_since_done = false;
1964                self.editor
1965                    .update(cx, |editor, _| editor.set_read_only(false));
1966            }
1967            CodegenStatus::Error(error) => {
1968                if cx.has_flag::<ZedPro>()
1969                    && error.error_code() == proto::ErrorCode::RateLimitExceeded
1970                    && !dismissed_rate_limit_notice()
1971                {
1972                    self.show_rate_limit_notice = true;
1973                    cx.notify();
1974                }
1975
1976                self.edited_since_done = false;
1977                self.editor
1978                    .update(cx, |editor, _| editor.set_read_only(false));
1979            }
1980        }
1981    }
1982
1983    fn restart(&mut self, _: &menu::Restart, _window: &mut Window, cx: &mut Context<Self>) {
1984        cx.emit(PromptEditorEvent::StartRequested);
1985    }
1986
1987    fn cancel(
1988        &mut self,
1989        _: &editor::actions::Cancel,
1990        _window: &mut Window,
1991        cx: &mut Context<Self>,
1992    ) {
1993        match self.codegen.read(cx).status(cx) {
1994            CodegenStatus::Idle | CodegenStatus::Done | CodegenStatus::Error(_) => {
1995                cx.emit(PromptEditorEvent::CancelRequested);
1996            }
1997            CodegenStatus::Pending => {
1998                cx.emit(PromptEditorEvent::StopRequested);
1999            }
2000        }
2001    }
2002
2003    fn confirm(&mut self, _: &menu::Confirm, _window: &mut Window, cx: &mut Context<Self>) {
2004        match self.codegen.read(cx).status(cx) {
2005            CodegenStatus::Idle => {
2006                cx.emit(PromptEditorEvent::StartRequested);
2007            }
2008            CodegenStatus::Pending => {
2009                cx.emit(PromptEditorEvent::DismissRequested);
2010            }
2011            CodegenStatus::Done => {
2012                if self.edited_since_done {
2013                    cx.emit(PromptEditorEvent::StartRequested);
2014                } else {
2015                    cx.emit(PromptEditorEvent::ConfirmRequested);
2016                }
2017            }
2018            CodegenStatus::Error(_) => {
2019                cx.emit(PromptEditorEvent::StartRequested);
2020            }
2021        }
2022    }
2023
2024    fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
2025        if let Some(ix) = self.prompt_history_ix {
2026            if ix > 0 {
2027                self.prompt_history_ix = Some(ix - 1);
2028                let prompt = self.prompt_history[ix - 1].as_str();
2029                self.editor.update(cx, |editor, cx| {
2030                    editor.set_text(prompt, window, cx);
2031                    editor.move_to_beginning(&Default::default(), window, cx);
2032                });
2033            }
2034        } else if !self.prompt_history.is_empty() {
2035            self.prompt_history_ix = Some(self.prompt_history.len() - 1);
2036            let prompt = self.prompt_history[self.prompt_history.len() - 1].as_str();
2037            self.editor.update(cx, |editor, cx| {
2038                editor.set_text(prompt, window, cx);
2039                editor.move_to_beginning(&Default::default(), window, cx);
2040            });
2041        }
2042    }
2043
2044    fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
2045        if let Some(ix) = self.prompt_history_ix {
2046            if ix < self.prompt_history.len() - 1 {
2047                self.prompt_history_ix = Some(ix + 1);
2048                let prompt = self.prompt_history[ix + 1].as_str();
2049                self.editor.update(cx, |editor, cx| {
2050                    editor.set_text(prompt, window, cx);
2051                    editor.move_to_end(&Default::default(), window, cx)
2052                });
2053            } else {
2054                self.prompt_history_ix = None;
2055                let prompt = self.pending_prompt.as_str();
2056                self.editor.update(cx, |editor, cx| {
2057                    editor.set_text(prompt, window, cx);
2058                    editor.move_to_end(&Default::default(), window, cx)
2059                });
2060            }
2061        }
2062    }
2063
2064    fn cycle_prev(
2065        &mut self,
2066        _: &CyclePreviousInlineAssist,
2067        _: &mut Window,
2068        cx: &mut Context<Self>,
2069    ) {
2070        self.codegen
2071            .update(cx, |codegen, cx| codegen.cycle_prev(cx));
2072    }
2073
2074    fn cycle_next(&mut self, _: &CycleNextInlineAssist, _: &mut Window, cx: &mut Context<Self>) {
2075        self.codegen
2076            .update(cx, |codegen, cx| codegen.cycle_next(cx));
2077    }
2078
2079    fn render_cycle_controls(&self, cx: &Context<Self>) -> AnyElement {
2080        let codegen = self.codegen.read(cx);
2081        let disabled = matches!(codegen.status(cx), CodegenStatus::Idle);
2082
2083        let model_registry = LanguageModelRegistry::read_global(cx);
2084        let default_model = model_registry.default_model().map(|default| default.model);
2085        let alternative_models = model_registry.inline_alternative_models();
2086
2087        let get_model_name = |index: usize| -> String {
2088            let name = |model: &Arc<dyn LanguageModel>| model.name().0.to_string();
2089
2090            match index {
2091                0 => default_model.as_ref().map_or_else(String::new, name),
2092                index if index <= alternative_models.len() => alternative_models
2093                    .get(index - 1)
2094                    .map_or_else(String::new, name),
2095                _ => String::new(),
2096            }
2097        };
2098
2099        let total_models = alternative_models.len() + 1;
2100
2101        if total_models <= 1 {
2102            return div().into_any_element();
2103        }
2104
2105        let current_index = codegen.active_alternative;
2106        let prev_index = (current_index + total_models - 1) % total_models;
2107        let next_index = (current_index + 1) % total_models;
2108
2109        let prev_model_name = get_model_name(prev_index);
2110        let next_model_name = get_model_name(next_index);
2111
2112        h_flex()
2113            .child(
2114                IconButton::new("previous", IconName::ChevronLeft)
2115                    .icon_color(Color::Muted)
2116                    .disabled(disabled || current_index == 0)
2117                    .shape(IconButtonShape::Square)
2118                    .tooltip({
2119                        let focus_handle = self.editor.focus_handle(cx);
2120                        move |window, cx| {
2121                            cx.new(|cx| {
2122                                let mut tooltip = Tooltip::new("Previous Alternative").key_binding(
2123                                    KeyBinding::for_action_in(
2124                                        &CyclePreviousInlineAssist,
2125                                        &focus_handle,
2126                                        window,
2127                                        cx,
2128                                    ),
2129                                );
2130                                if !disabled && current_index != 0 {
2131                                    tooltip = tooltip.meta(prev_model_name.clone());
2132                                }
2133                                tooltip
2134                            })
2135                            .into()
2136                        }
2137                    })
2138                    .on_click(cx.listener(|this, _, _, cx| {
2139                        this.codegen
2140                            .update(cx, |codegen, cx| codegen.cycle_prev(cx))
2141                    })),
2142            )
2143            .child(
2144                Label::new(format!(
2145                    "{}/{}",
2146                    codegen.active_alternative + 1,
2147                    codegen.alternative_count(cx)
2148                ))
2149                .size(LabelSize::Small)
2150                .color(if disabled {
2151                    Color::Disabled
2152                } else {
2153                    Color::Muted
2154                }),
2155            )
2156            .child(
2157                IconButton::new("next", IconName::ChevronRight)
2158                    .icon_color(Color::Muted)
2159                    .disabled(disabled || current_index == total_models - 1)
2160                    .shape(IconButtonShape::Square)
2161                    .tooltip({
2162                        let focus_handle = self.editor.focus_handle(cx);
2163                        move |window, cx| {
2164                            cx.new(|cx| {
2165                                let mut tooltip = Tooltip::new("Next Alternative").key_binding(
2166                                    KeyBinding::for_action_in(
2167                                        &CycleNextInlineAssist,
2168                                        &focus_handle,
2169                                        window,
2170                                        cx,
2171                                    ),
2172                                );
2173                                if !disabled && current_index != total_models - 1 {
2174                                    tooltip = tooltip.meta(next_model_name.clone());
2175                                }
2176                                tooltip
2177                            })
2178                            .into()
2179                        }
2180                    })
2181                    .on_click(cx.listener(|this, _, _, cx| {
2182                        this.codegen
2183                            .update(cx, |codegen, cx| codegen.cycle_next(cx))
2184                    })),
2185            )
2186            .into_any_element()
2187    }
2188
2189    fn render_token_count(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2190        let model = LanguageModelRegistry::read_global(cx)
2191            .default_model()?
2192            .model;
2193        let token_counts = self.token_counts?;
2194        let max_token_count = model.max_token_count();
2195
2196        let remaining_tokens = max_token_count as isize - token_counts.total as isize;
2197        let token_count_color = if remaining_tokens <= 0 {
2198            Color::Error
2199        } else if token_counts.total as f32 / max_token_count as f32 >= 0.8 {
2200            Color::Warning
2201        } else {
2202            Color::Muted
2203        };
2204
2205        let mut token_count = h_flex()
2206            .id("token_count")
2207            .gap_0p5()
2208            .child(
2209                Label::new(humanize_token_count(token_counts.total))
2210                    .size(LabelSize::Small)
2211                    .color(token_count_color),
2212            )
2213            .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
2214            .child(
2215                Label::new(humanize_token_count(max_token_count))
2216                    .size(LabelSize::Small)
2217                    .color(Color::Muted),
2218            );
2219        if let Some(workspace) = self.workspace.clone() {
2220            token_count = token_count
2221                .tooltip(move |window, cx| {
2222                    Tooltip::with_meta(
2223                        format!(
2224                            "Tokens Used ({} from the Assistant Panel)",
2225                            humanize_token_count(token_counts.assistant_panel)
2226                        ),
2227                        None,
2228                        "Click to open the Assistant Panel",
2229                        window,
2230                        cx,
2231                    )
2232                })
2233                .cursor_pointer()
2234                .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| cx.stop_propagation())
2235                .on_click(move |_, window, cx| {
2236                    cx.stop_propagation();
2237                    workspace
2238                        .update(cx, |workspace, cx| {
2239                            workspace.focus_panel::<AssistantPanel>(window, cx)
2240                        })
2241                        .ok();
2242                });
2243        } else {
2244            token_count = token_count
2245                .cursor_default()
2246                .tooltip(Tooltip::text("Tokens used"));
2247        }
2248
2249        Some(token_count)
2250    }
2251
2252    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
2253        let settings = ThemeSettings::get_global(cx);
2254        let text_style = TextStyle {
2255            color: if self.editor.read(cx).read_only(cx) {
2256                cx.theme().colors().text_disabled
2257            } else {
2258                cx.theme().colors().text
2259            },
2260            font_family: settings.buffer_font.family.clone(),
2261            font_fallbacks: settings.buffer_font.fallbacks.clone(),
2262            font_size: settings.buffer_font_size(cx).into(),
2263            font_weight: settings.buffer_font.weight,
2264            line_height: relative(settings.buffer_line_height.value()),
2265            ..Default::default()
2266        };
2267        EditorElement::new(
2268            &self.editor,
2269            EditorStyle {
2270                background: cx.theme().colors().editor_background,
2271                local_player: cx.theme().players().local(),
2272                text: text_style,
2273                ..Default::default()
2274            },
2275        )
2276    }
2277
2278    fn render_rate_limit_notice(&self, cx: &mut Context<Self>) -> impl IntoElement {
2279        Popover::new().child(
2280            v_flex()
2281                .occlude()
2282                .p_2()
2283                .child(
2284                    Label::new("Out of Tokens")
2285                        .size(LabelSize::Small)
2286                        .weight(FontWeight::BOLD),
2287                )
2288                .child(Label::new(
2289                    "Try Zed Pro for higher limits, a wider range of models, and more.",
2290                ))
2291                .child(
2292                    h_flex()
2293                        .justify_between()
2294                        .child(CheckboxWithLabel::new(
2295                            "dont-show-again",
2296                            Label::new("Don't show again"),
2297                            if dismissed_rate_limit_notice() {
2298                                ui::ToggleState::Selected
2299                            } else {
2300                                ui::ToggleState::Unselected
2301                            },
2302                            |selection, _, cx| {
2303                                let is_dismissed = match selection {
2304                                    ui::ToggleState::Unselected => false,
2305                                    ui::ToggleState::Indeterminate => return,
2306                                    ui::ToggleState::Selected => true,
2307                                };
2308
2309                                set_rate_limit_notice_dismissed(is_dismissed, cx)
2310                            },
2311                        ))
2312                        .child(
2313                            h_flex()
2314                                .gap_2()
2315                                .child(
2316                                    Button::new("dismiss", "Dismiss")
2317                                        .style(ButtonStyle::Transparent)
2318                                        .on_click(cx.listener(Self::toggle_rate_limit_notice)),
2319                                )
2320                                .child(Button::new("more-info", "More Info").on_click(
2321                                    |_event, window, cx| {
2322                                        window.dispatch_action(
2323                                            Box::new(zed_actions::OpenAccountSettings),
2324                                            cx,
2325                                        )
2326                                    },
2327                                )),
2328                        ),
2329                ),
2330        )
2331    }
2332}
2333
2334const DISMISSED_RATE_LIMIT_NOTICE_KEY: &str = "dismissed-rate-limit-notice";
2335
2336fn dismissed_rate_limit_notice() -> bool {
2337    db::kvp::KEY_VALUE_STORE
2338        .read_kvp(DISMISSED_RATE_LIMIT_NOTICE_KEY)
2339        .log_err()
2340        .map_or(false, |s| s.is_some())
2341}
2342
2343fn set_rate_limit_notice_dismissed(is_dismissed: bool, cx: &mut App) {
2344    db::write_and_log(cx, move || async move {
2345        if is_dismissed {
2346            db::kvp::KEY_VALUE_STORE
2347                .write_kvp(DISMISSED_RATE_LIMIT_NOTICE_KEY.into(), "1".into())
2348                .await
2349        } else {
2350            db::kvp::KEY_VALUE_STORE
2351                .delete_kvp(DISMISSED_RATE_LIMIT_NOTICE_KEY.into())
2352                .await
2353        }
2354    })
2355}
2356
2357struct InlineAssist {
2358    group_id: InlineAssistGroupId,
2359    range: Range<Anchor>,
2360    editor: WeakEntity<Editor>,
2361    decorations: Option<InlineAssistDecorations>,
2362    codegen: Entity<Codegen>,
2363    _subscriptions: Vec<Subscription>,
2364    workspace: Option<WeakEntity<Workspace>>,
2365    include_context: bool,
2366}
2367
2368impl InlineAssist {
2369    fn new(
2370        assist_id: InlineAssistId,
2371        group_id: InlineAssistGroupId,
2372        include_context: bool,
2373        editor: &Entity<Editor>,
2374        prompt_editor: &Entity<PromptEditor>,
2375        prompt_block_id: CustomBlockId,
2376        end_block_id: CustomBlockId,
2377        range: Range<Anchor>,
2378        codegen: Entity<Codegen>,
2379        workspace: Option<WeakEntity<Workspace>>,
2380        window: &mut Window,
2381        cx: &mut App,
2382    ) -> Self {
2383        let prompt_editor_focus_handle = prompt_editor.focus_handle(cx);
2384        InlineAssist {
2385            group_id,
2386            include_context,
2387            editor: editor.downgrade(),
2388            decorations: Some(InlineAssistDecorations {
2389                prompt_block_id,
2390                prompt_editor: prompt_editor.clone(),
2391                removed_line_block_ids: HashSet::default(),
2392                end_block_id,
2393            }),
2394            range,
2395            codegen: codegen.clone(),
2396            workspace: workspace.clone(),
2397            _subscriptions: vec![
2398                window.on_focus_in(&prompt_editor_focus_handle, cx, move |_, cx| {
2399                    InlineAssistant::update_global(cx, |this, cx| {
2400                        this.handle_prompt_editor_focus_in(assist_id, cx)
2401                    })
2402                }),
2403                window.on_focus_out(&prompt_editor_focus_handle, cx, move |_, _, cx| {
2404                    InlineAssistant::update_global(cx, |this, cx| {
2405                        this.handle_prompt_editor_focus_out(assist_id, cx)
2406                    })
2407                }),
2408                window.subscribe(
2409                    prompt_editor,
2410                    cx,
2411                    move |prompt_editor, event, window, cx| {
2412                        InlineAssistant::update_global(cx, |this, cx| {
2413                            this.handle_prompt_editor_event(prompt_editor, event, window, cx)
2414                        })
2415                    },
2416                ),
2417                window.observe(&codegen, cx, {
2418                    let editor = editor.downgrade();
2419                    move |_, window, cx| {
2420                        if let Some(editor) = editor.upgrade() {
2421                            InlineAssistant::update_global(cx, |this, cx| {
2422                                if let Some(editor_assists) =
2423                                    this.assists_by_editor.get(&editor.downgrade())
2424                                {
2425                                    editor_assists.highlight_updates.send(()).ok();
2426                                }
2427
2428                                this.update_editor_blocks(&editor, assist_id, window, cx);
2429                            })
2430                        }
2431                    }
2432                }),
2433                window.subscribe(&codegen, cx, move |codegen, event, window, cx| {
2434                    InlineAssistant::update_global(cx, |this, cx| match event {
2435                        CodegenEvent::Undone => this.finish_assist(assist_id, false, window, cx),
2436                        CodegenEvent::Finished => {
2437                            let assist = if let Some(assist) = this.assists.get(&assist_id) {
2438                                assist
2439                            } else {
2440                                return;
2441                            };
2442
2443                            if let CodegenStatus::Error(error) = codegen.read(cx).status(cx) {
2444                                if assist.decorations.is_none() {
2445                                    if let Some(workspace) = assist
2446                                        .workspace
2447                                        .as_ref()
2448                                        .and_then(|workspace| workspace.upgrade())
2449                                    {
2450                                        let error = format!("Inline assistant error: {}", error);
2451                                        workspace.update(cx, |workspace, cx| {
2452                                            struct InlineAssistantError;
2453
2454                                            let id =
2455                                                NotificationId::composite::<InlineAssistantError>(
2456                                                    assist_id.0,
2457                                                );
2458
2459                                            workspace.show_toast(Toast::new(id, error), cx);
2460                                        })
2461                                    }
2462                                }
2463                            }
2464
2465                            if assist.decorations.is_none() {
2466                                this.finish_assist(assist_id, false, window, cx);
2467                            }
2468                        }
2469                    })
2470                }),
2471            ],
2472        }
2473    }
2474
2475    fn user_prompt(&self, cx: &App) -> Option<String> {
2476        let decorations = self.decorations.as_ref()?;
2477        Some(decorations.prompt_editor.read(cx).prompt(cx))
2478    }
2479
2480    fn assistant_panel_context(&self, cx: &mut App) -> Option<LanguageModelRequest> {
2481        if self.include_context {
2482            let workspace = self.workspace.as_ref()?;
2483            let workspace = workspace.upgrade()?.read(cx);
2484            let assistant_panel = workspace.panel::<AssistantPanel>(cx)?;
2485            Some(
2486                assistant_panel
2487                    .read(cx)
2488                    .active_context(cx)?
2489                    .read(cx)
2490                    .to_completion_request(RequestType::Chat, cx),
2491            )
2492        } else {
2493            None
2494        }
2495    }
2496
2497    pub fn count_tokens(&self, cx: &mut App) -> BoxFuture<'static, Result<TokenCounts>> {
2498        let Some(user_prompt) = self.user_prompt(cx) else {
2499            return future::ready(Err(anyhow!("no user prompt"))).boxed();
2500        };
2501        let assistant_panel_context = self.assistant_panel_context(cx);
2502        self.codegen
2503            .read(cx)
2504            .count_tokens(user_prompt, assistant_panel_context, cx)
2505    }
2506}
2507
2508struct InlineAssistDecorations {
2509    prompt_block_id: CustomBlockId,
2510    prompt_editor: Entity<PromptEditor>,
2511    removed_line_block_ids: HashSet<CustomBlockId>,
2512    end_block_id: CustomBlockId,
2513}
2514
2515#[derive(Copy, Clone, Debug)]
2516pub enum CodegenEvent {
2517    Finished,
2518    Undone,
2519}
2520
2521pub struct Codegen {
2522    alternatives: Vec<Entity<CodegenAlternative>>,
2523    active_alternative: usize,
2524    seen_alternatives: HashSet<usize>,
2525    subscriptions: Vec<Subscription>,
2526    buffer: Entity<MultiBuffer>,
2527    range: Range<Anchor>,
2528    initial_transaction_id: Option<TransactionId>,
2529    telemetry: Arc<Telemetry>,
2530    builder: Arc<PromptBuilder>,
2531    is_insertion: bool,
2532}
2533
2534impl Codegen {
2535    pub fn new(
2536        buffer: Entity<MultiBuffer>,
2537        range: Range<Anchor>,
2538        initial_transaction_id: Option<TransactionId>,
2539        telemetry: Arc<Telemetry>,
2540        builder: Arc<PromptBuilder>,
2541        cx: &mut Context<Self>,
2542    ) -> Self {
2543        let codegen = cx.new(|cx| {
2544            CodegenAlternative::new(
2545                buffer.clone(),
2546                range.clone(),
2547                false,
2548                Some(telemetry.clone()),
2549                builder.clone(),
2550                cx,
2551            )
2552        });
2553        let mut this = Self {
2554            is_insertion: range.to_offset(&buffer.read(cx).snapshot(cx)).is_empty(),
2555            alternatives: vec![codegen],
2556            active_alternative: 0,
2557            seen_alternatives: HashSet::default(),
2558            subscriptions: Vec::new(),
2559            buffer,
2560            range,
2561            initial_transaction_id,
2562            telemetry,
2563            builder,
2564        };
2565        this.activate(0, cx);
2566        this
2567    }
2568
2569    fn subscribe_to_alternative(&mut self, cx: &mut Context<Self>) {
2570        let codegen = self.active_alternative().clone();
2571        self.subscriptions.clear();
2572        self.subscriptions
2573            .push(cx.observe(&codegen, |_, _, cx| cx.notify()));
2574        self.subscriptions
2575            .push(cx.subscribe(&codegen, |_, _, event, cx| cx.emit(*event)));
2576    }
2577
2578    fn active_alternative(&self) -> &Entity<CodegenAlternative> {
2579        &self.alternatives[self.active_alternative]
2580    }
2581
2582    fn status<'a>(&self, cx: &'a App) -> &'a CodegenStatus {
2583        &self.active_alternative().read(cx).status
2584    }
2585
2586    fn alternative_count(&self, cx: &App) -> usize {
2587        LanguageModelRegistry::read_global(cx)
2588            .inline_alternative_models()
2589            .len()
2590            + 1
2591    }
2592
2593    pub fn cycle_prev(&mut self, cx: &mut Context<Self>) {
2594        let next_active_ix = if self.active_alternative == 0 {
2595            self.alternatives.len() - 1
2596        } else {
2597            self.active_alternative - 1
2598        };
2599        self.activate(next_active_ix, cx);
2600    }
2601
2602    pub fn cycle_next(&mut self, cx: &mut Context<Self>) {
2603        let next_active_ix = (self.active_alternative + 1) % self.alternatives.len();
2604        self.activate(next_active_ix, cx);
2605    }
2606
2607    fn activate(&mut self, index: usize, cx: &mut Context<Self>) {
2608        self.active_alternative()
2609            .update(cx, |codegen, cx| codegen.set_active(false, cx));
2610        self.seen_alternatives.insert(index);
2611        self.active_alternative = index;
2612        self.active_alternative()
2613            .update(cx, |codegen, cx| codegen.set_active(true, cx));
2614        self.subscribe_to_alternative(cx);
2615        cx.notify();
2616    }
2617
2618    pub fn start(
2619        &mut self,
2620        user_prompt: String,
2621        assistant_panel_context: Option<LanguageModelRequest>,
2622        cx: &mut Context<Self>,
2623    ) -> Result<()> {
2624        let alternative_models = LanguageModelRegistry::read_global(cx)
2625            .inline_alternative_models()
2626            .to_vec();
2627
2628        self.active_alternative()
2629            .update(cx, |alternative, cx| alternative.undo(cx));
2630        self.activate(0, cx);
2631        self.alternatives.truncate(1);
2632
2633        for _ in 0..alternative_models.len() {
2634            self.alternatives.push(cx.new(|cx| {
2635                CodegenAlternative::new(
2636                    self.buffer.clone(),
2637                    self.range.clone(),
2638                    false,
2639                    Some(self.telemetry.clone()),
2640                    self.builder.clone(),
2641                    cx,
2642                )
2643            }));
2644        }
2645
2646        let primary_model = LanguageModelRegistry::read_global(cx)
2647            .default_model()
2648            .context("no active model")?
2649            .model;
2650
2651        for (model, alternative) in iter::once(primary_model)
2652            .chain(alternative_models)
2653            .zip(&self.alternatives)
2654        {
2655            alternative.update(cx, |alternative, cx| {
2656                alternative.start(
2657                    user_prompt.clone(),
2658                    assistant_panel_context.clone(),
2659                    model.clone(),
2660                    cx,
2661                )
2662            })?;
2663        }
2664
2665        Ok(())
2666    }
2667
2668    pub fn stop(&mut self, cx: &mut Context<Self>) {
2669        for codegen in &self.alternatives {
2670            codegen.update(cx, |codegen, cx| codegen.stop(cx));
2671        }
2672    }
2673
2674    pub fn undo(&mut self, cx: &mut Context<Self>) {
2675        self.active_alternative()
2676            .update(cx, |codegen, cx| codegen.undo(cx));
2677
2678        self.buffer.update(cx, |buffer, cx| {
2679            if let Some(transaction_id) = self.initial_transaction_id.take() {
2680                buffer.undo_transaction(transaction_id, cx);
2681                buffer.refresh_preview(cx);
2682            }
2683        });
2684    }
2685
2686    pub fn count_tokens(
2687        &self,
2688        user_prompt: String,
2689        assistant_panel_context: Option<LanguageModelRequest>,
2690        cx: &App,
2691    ) -> BoxFuture<'static, Result<TokenCounts>> {
2692        self.active_alternative()
2693            .read(cx)
2694            .count_tokens(user_prompt, assistant_panel_context, cx)
2695    }
2696
2697    pub fn buffer(&self, cx: &App) -> Entity<MultiBuffer> {
2698        self.active_alternative().read(cx).buffer.clone()
2699    }
2700
2701    pub fn old_buffer(&self, cx: &App) -> Entity<Buffer> {
2702        self.active_alternative().read(cx).old_buffer.clone()
2703    }
2704
2705    pub fn snapshot(&self, cx: &App) -> MultiBufferSnapshot {
2706        self.active_alternative().read(cx).snapshot.clone()
2707    }
2708
2709    pub fn edit_position(&self, cx: &App) -> Option<Anchor> {
2710        self.active_alternative().read(cx).edit_position
2711    }
2712
2713    fn diff<'a>(&self, cx: &'a App) -> &'a Diff {
2714        &self.active_alternative().read(cx).diff
2715    }
2716
2717    pub fn last_equal_ranges<'a>(&self, cx: &'a App) -> &'a [Range<Anchor>] {
2718        self.active_alternative().read(cx).last_equal_ranges()
2719    }
2720}
2721
2722impl EventEmitter<CodegenEvent> for Codegen {}
2723
2724pub struct CodegenAlternative {
2725    buffer: Entity<MultiBuffer>,
2726    old_buffer: Entity<Buffer>,
2727    snapshot: MultiBufferSnapshot,
2728    edit_position: Option<Anchor>,
2729    range: Range<Anchor>,
2730    last_equal_ranges: Vec<Range<Anchor>>,
2731    transformation_transaction_id: Option<TransactionId>,
2732    status: CodegenStatus,
2733    generation: Task<()>,
2734    diff: Diff,
2735    telemetry: Option<Arc<Telemetry>>,
2736    _subscription: gpui::Subscription,
2737    builder: Arc<PromptBuilder>,
2738    active: bool,
2739    edits: Vec<(Range<Anchor>, String)>,
2740    line_operations: Vec<LineOperation>,
2741    request: Option<LanguageModelRequest>,
2742    elapsed_time: Option<f64>,
2743    completion: Option<String>,
2744    message_id: Option<String>,
2745}
2746
2747enum CodegenStatus {
2748    Idle,
2749    Pending,
2750    Done,
2751    Error(anyhow::Error),
2752}
2753
2754#[derive(Default)]
2755struct Diff {
2756    deleted_row_ranges: Vec<(Anchor, RangeInclusive<u32>)>,
2757    inserted_row_ranges: Vec<Range<Anchor>>,
2758}
2759
2760impl Diff {
2761    fn is_empty(&self) -> bool {
2762        self.deleted_row_ranges.is_empty() && self.inserted_row_ranges.is_empty()
2763    }
2764}
2765
2766impl EventEmitter<CodegenEvent> for CodegenAlternative {}
2767
2768impl CodegenAlternative {
2769    pub fn new(
2770        multi_buffer: Entity<MultiBuffer>,
2771        range: Range<Anchor>,
2772        active: bool,
2773        telemetry: Option<Arc<Telemetry>>,
2774        builder: Arc<PromptBuilder>,
2775        cx: &mut Context<Self>,
2776    ) -> Self {
2777        let snapshot = multi_buffer.read(cx).snapshot(cx);
2778
2779        let (buffer, _, _) = snapshot
2780            .range_to_buffer_ranges(range.clone())
2781            .pop()
2782            .unwrap();
2783        let old_buffer = cx.new(|cx| {
2784            let text = buffer.as_rope().clone();
2785            let line_ending = buffer.line_ending();
2786            let language = buffer.language().cloned();
2787            let language_registry = multi_buffer
2788                .read(cx)
2789                .buffer(buffer.remote_id())
2790                .unwrap()
2791                .read(cx)
2792                .language_registry();
2793
2794            let mut buffer = Buffer::local_normalized(text, line_ending, cx);
2795            buffer.set_language(language, cx);
2796            if let Some(language_registry) = language_registry {
2797                buffer.set_language_registry(language_registry)
2798            }
2799            buffer
2800        });
2801
2802        Self {
2803            buffer: multi_buffer.clone(),
2804            old_buffer,
2805            edit_position: None,
2806            message_id: None,
2807            snapshot,
2808            last_equal_ranges: Default::default(),
2809            transformation_transaction_id: None,
2810            status: CodegenStatus::Idle,
2811            generation: Task::ready(()),
2812            diff: Diff::default(),
2813            telemetry,
2814            _subscription: cx.subscribe(&multi_buffer, Self::handle_buffer_event),
2815            builder,
2816            active,
2817            edits: Vec::new(),
2818            line_operations: Vec::new(),
2819            range,
2820            request: None,
2821            elapsed_time: None,
2822            completion: None,
2823        }
2824    }
2825
2826    fn set_active(&mut self, active: bool, cx: &mut Context<Self>) {
2827        if active != self.active {
2828            self.active = active;
2829
2830            if self.active {
2831                let edits = self.edits.clone();
2832                self.apply_edits(edits, cx);
2833                if matches!(self.status, CodegenStatus::Pending) {
2834                    let line_operations = self.line_operations.clone();
2835                    self.reapply_line_based_diff(line_operations, cx);
2836                } else {
2837                    self.reapply_batch_diff(cx).detach();
2838                }
2839            } else if let Some(transaction_id) = self.transformation_transaction_id.take() {
2840                self.buffer.update(cx, |buffer, cx| {
2841                    buffer.undo_transaction(transaction_id, cx);
2842                    buffer.forget_transaction(transaction_id, cx);
2843                });
2844            }
2845        }
2846    }
2847
2848    fn handle_buffer_event(
2849        &mut self,
2850        _buffer: Entity<MultiBuffer>,
2851        event: &multi_buffer::Event,
2852        cx: &mut Context<Self>,
2853    ) {
2854        if let multi_buffer::Event::TransactionUndone { transaction_id } = event {
2855            if self.transformation_transaction_id == Some(*transaction_id) {
2856                self.transformation_transaction_id = None;
2857                self.generation = Task::ready(());
2858                cx.emit(CodegenEvent::Undone);
2859            }
2860        }
2861    }
2862
2863    pub fn last_equal_ranges(&self) -> &[Range<Anchor>] {
2864        &self.last_equal_ranges
2865    }
2866
2867    pub fn count_tokens(
2868        &self,
2869        user_prompt: String,
2870        assistant_panel_context: Option<LanguageModelRequest>,
2871        cx: &App,
2872    ) -> BoxFuture<'static, Result<TokenCounts>> {
2873        if let Some(ConfiguredModel { model, .. }) =
2874            LanguageModelRegistry::read_global(cx).inline_assistant_model()
2875        {
2876            let request = self.build_request(user_prompt, assistant_panel_context.clone(), cx);
2877            match request {
2878                Ok(request) => {
2879                    let total_count = model.count_tokens(request.clone(), cx);
2880                    let assistant_panel_count = assistant_panel_context
2881                        .map(|context| model.count_tokens(context, cx))
2882                        .unwrap_or_else(|| future::ready(Ok(0)).boxed());
2883
2884                    async move {
2885                        Ok(TokenCounts {
2886                            total: total_count.await?,
2887                            assistant_panel: assistant_panel_count.await?,
2888                        })
2889                    }
2890                    .boxed()
2891                }
2892                Err(error) => futures::future::ready(Err(error)).boxed(),
2893            }
2894        } else {
2895            future::ready(Err(anyhow!("no active model"))).boxed()
2896        }
2897    }
2898
2899    pub fn start(
2900        &mut self,
2901        user_prompt: String,
2902        assistant_panel_context: Option<LanguageModelRequest>,
2903        model: Arc<dyn LanguageModel>,
2904        cx: &mut Context<Self>,
2905    ) -> Result<()> {
2906        if let Some(transformation_transaction_id) = self.transformation_transaction_id.take() {
2907            self.buffer.update(cx, |buffer, cx| {
2908                buffer.undo_transaction(transformation_transaction_id, cx);
2909            });
2910        }
2911
2912        self.edit_position = Some(self.range.start.bias_right(&self.snapshot));
2913
2914        let api_key = model.api_key(cx);
2915        let telemetry_id = model.telemetry_id();
2916        let provider_id = model.provider_id();
2917        let stream: LocalBoxFuture<Result<LanguageModelTextStream>> =
2918            if user_prompt.trim().to_lowercase() == "delete" {
2919                async { Ok(LanguageModelTextStream::default()) }.boxed_local()
2920            } else {
2921                let request = self.build_request(user_prompt, assistant_panel_context, cx)?;
2922                self.request = Some(request.clone());
2923
2924                cx.spawn(async move |_, cx| model.stream_completion_text(request, &cx).await)
2925                    .boxed_local()
2926            };
2927        self.handle_stream(telemetry_id, provider_id.to_string(), api_key, stream, cx);
2928        Ok(())
2929    }
2930
2931    fn build_request(
2932        &self,
2933        user_prompt: String,
2934        assistant_panel_context: Option<LanguageModelRequest>,
2935        cx: &App,
2936    ) -> Result<LanguageModelRequest> {
2937        let buffer = self.buffer.read(cx).snapshot(cx);
2938        let language = buffer.language_at(self.range.start);
2939        let language_name = if let Some(language) = language.as_ref() {
2940            if Arc::ptr_eq(language, &language::PLAIN_TEXT) {
2941                None
2942            } else {
2943                Some(language.name())
2944            }
2945        } else {
2946            None
2947        };
2948
2949        let language_name = language_name.as_ref();
2950        let start = buffer.point_to_buffer_offset(self.range.start);
2951        let end = buffer.point_to_buffer_offset(self.range.end);
2952        let (buffer, range) = if let Some((start, end)) = start.zip(end) {
2953            let (start_buffer, start_buffer_offset) = start;
2954            let (end_buffer, end_buffer_offset) = end;
2955            if start_buffer.remote_id() == end_buffer.remote_id() {
2956                (start_buffer.clone(), start_buffer_offset..end_buffer_offset)
2957            } else {
2958                return Err(anyhow::anyhow!("invalid transformation range"));
2959            }
2960        } else {
2961            return Err(anyhow::anyhow!("invalid transformation range"));
2962        };
2963
2964        let prompt = self
2965            .builder
2966            .generate_inline_transformation_prompt(user_prompt, language_name, buffer, range)
2967            .map_err(|e| anyhow::anyhow!("Failed to generate content prompt: {}", e))?;
2968
2969        let mut messages = Vec::new();
2970        if let Some(context_request) = assistant_panel_context {
2971            messages = context_request.messages;
2972        }
2973
2974        messages.push(LanguageModelRequestMessage {
2975            role: Role::User,
2976            content: vec![prompt.into()],
2977            cache: false,
2978        });
2979
2980        Ok(LanguageModelRequest {
2981            messages,
2982            tools: Vec::new(),
2983            stop: Vec::new(),
2984            temperature: None,
2985        })
2986    }
2987
2988    pub fn handle_stream(
2989        &mut self,
2990        model_telemetry_id: String,
2991        model_provider_id: String,
2992        model_api_key: Option<String>,
2993        stream: impl 'static + Future<Output = Result<LanguageModelTextStream>>,
2994        cx: &mut Context<Self>,
2995    ) {
2996        let start_time = Instant::now();
2997        let snapshot = self.snapshot.clone();
2998        let selected_text = snapshot
2999            .text_for_range(self.range.start..self.range.end)
3000            .collect::<Rope>();
3001
3002        let selection_start = self.range.start.to_point(&snapshot);
3003
3004        // Start with the indentation of the first line in the selection
3005        let mut suggested_line_indent = snapshot
3006            .suggested_indents(selection_start.row..=selection_start.row, cx)
3007            .into_values()
3008            .next()
3009            .unwrap_or_else(|| snapshot.indent_size_for_line(MultiBufferRow(selection_start.row)));
3010
3011        // If the first line in the selection does not have indentation, check the following lines
3012        if suggested_line_indent.len == 0 && suggested_line_indent.kind == IndentKind::Space {
3013            for row in selection_start.row..=self.range.end.to_point(&snapshot).row {
3014                let line_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
3015                // Prefer tabs if a line in the selection uses tabs as indentation
3016                if line_indent.kind == IndentKind::Tab {
3017                    suggested_line_indent.kind = IndentKind::Tab;
3018                    break;
3019                }
3020            }
3021        }
3022
3023        let http_client = cx.http_client().clone();
3024        let telemetry = self.telemetry.clone();
3025        let language_name = {
3026            let multibuffer = self.buffer.read(cx);
3027            let snapshot = multibuffer.snapshot(cx);
3028            let ranges = snapshot.range_to_buffer_ranges(self.range.clone());
3029            ranges
3030                .first()
3031                .and_then(|(buffer, _, _)| buffer.language())
3032                .map(|language| language.name())
3033        };
3034
3035        self.diff = Diff::default();
3036        self.status = CodegenStatus::Pending;
3037        let mut edit_start = self.range.start.to_offset(&snapshot);
3038        let completion = Arc::new(Mutex::new(String::new()));
3039        let completion_clone = completion.clone();
3040
3041        self.generation = cx.spawn(async move |codegen, cx| {
3042            let stream = stream.await;
3043            let message_id = stream
3044                .as_ref()
3045                .ok()
3046                .and_then(|stream| stream.message_id.clone());
3047            let generate = async {
3048                let (mut diff_tx, mut diff_rx) = mpsc::channel(1);
3049                let executor = cx.background_executor().clone();
3050                let message_id = message_id.clone();
3051                let line_based_stream_diff: Task<anyhow::Result<()>> =
3052                    cx.background_spawn(async move {
3053                        let mut response_latency = None;
3054                        let request_start = Instant::now();
3055                        let diff = async {
3056                            let chunks = StripInvalidSpans::new(stream?.stream);
3057                            futures::pin_mut!(chunks);
3058                            let mut diff = StreamingDiff::new(selected_text.to_string());
3059                            let mut line_diff = LineDiff::default();
3060
3061                            let mut new_text = String::new();
3062                            let mut base_indent = None;
3063                            let mut line_indent = None;
3064                            let mut first_line = true;
3065
3066                            while let Some(chunk) = chunks.next().await {
3067                                if response_latency.is_none() {
3068                                    response_latency = Some(request_start.elapsed());
3069                                }
3070                                let chunk = chunk?;
3071                                completion_clone.lock().push_str(&chunk);
3072
3073                                let mut lines = chunk.split('\n').peekable();
3074                                while let Some(line) = lines.next() {
3075                                    new_text.push_str(line);
3076                                    if line_indent.is_none() {
3077                                        if let Some(non_whitespace_ch_ix) =
3078                                            new_text.find(|ch: char| !ch.is_whitespace())
3079                                        {
3080                                            line_indent = Some(non_whitespace_ch_ix);
3081                                            base_indent = base_indent.or(line_indent);
3082
3083                                            let line_indent = line_indent.unwrap();
3084                                            let base_indent = base_indent.unwrap();
3085                                            let indent_delta =
3086                                                line_indent as i32 - base_indent as i32;
3087                                            let mut corrected_indent_len = cmp::max(
3088                                                0,
3089                                                suggested_line_indent.len as i32 + indent_delta,
3090                                            )
3091                                                as usize;
3092                                            if first_line {
3093                                                corrected_indent_len = corrected_indent_len
3094                                                    .saturating_sub(
3095                                                        selection_start.column as usize,
3096                                                    );
3097                                            }
3098
3099                                            let indent_char = suggested_line_indent.char();
3100                                            let mut indent_buffer = [0; 4];
3101                                            let indent_str =
3102                                                indent_char.encode_utf8(&mut indent_buffer);
3103                                            new_text.replace_range(
3104                                                ..line_indent,
3105                                                &indent_str.repeat(corrected_indent_len),
3106                                            );
3107                                        }
3108                                    }
3109
3110                                    if line_indent.is_some() {
3111                                        let char_ops = diff.push_new(&new_text);
3112                                        line_diff.push_char_operations(&char_ops, &selected_text);
3113                                        diff_tx
3114                                            .send((char_ops, line_diff.line_operations()))
3115                                            .await?;
3116                                        new_text.clear();
3117                                    }
3118
3119                                    if lines.peek().is_some() {
3120                                        let char_ops = diff.push_new("\n");
3121                                        line_diff.push_char_operations(&char_ops, &selected_text);
3122                                        diff_tx
3123                                            .send((char_ops, line_diff.line_operations()))
3124                                            .await?;
3125                                        if line_indent.is_none() {
3126                                            // Don't write out the leading indentation in empty lines on the next line
3127                                            // This is the case where the above if statement didn't clear the buffer
3128                                            new_text.clear();
3129                                        }
3130                                        line_indent = None;
3131                                        first_line = false;
3132                                    }
3133                                }
3134                            }
3135
3136                            let mut char_ops = diff.push_new(&new_text);
3137                            char_ops.extend(diff.finish());
3138                            line_diff.push_char_operations(&char_ops, &selected_text);
3139                            line_diff.finish(&selected_text);
3140                            diff_tx
3141                                .send((char_ops, line_diff.line_operations()))
3142                                .await?;
3143
3144                            anyhow::Ok(())
3145                        };
3146
3147                        let result = diff.await;
3148
3149                        let error_message = result.as_ref().err().map(|error| error.to_string());
3150                        report_assistant_event(
3151                            AssistantEventData {
3152                                conversation_id: None,
3153                                message_id,
3154                                kind: AssistantKind::Inline,
3155                                phase: AssistantPhase::Response,
3156                                model: model_telemetry_id,
3157                                model_provider: model_provider_id.to_string(),
3158                                response_latency,
3159                                error_message,
3160                                language_name: language_name.map(|name| name.to_proto()),
3161                            },
3162                            telemetry,
3163                            http_client,
3164                            model_api_key,
3165                            &executor,
3166                        );
3167
3168                        result?;
3169                        Ok(())
3170                    });
3171
3172                while let Some((char_ops, line_ops)) = diff_rx.next().await {
3173                    codegen.update(cx, |codegen, cx| {
3174                        codegen.last_equal_ranges.clear();
3175
3176                        let edits = char_ops
3177                            .into_iter()
3178                            .filter_map(|operation| match operation {
3179                                CharOperation::Insert { text } => {
3180                                    let edit_start = snapshot.anchor_after(edit_start);
3181                                    Some((edit_start..edit_start, text))
3182                                }
3183                                CharOperation::Delete { bytes } => {
3184                                    let edit_end = edit_start + bytes;
3185                                    let edit_range = snapshot.anchor_after(edit_start)
3186                                        ..snapshot.anchor_before(edit_end);
3187                                    edit_start = edit_end;
3188                                    Some((edit_range, String::new()))
3189                                }
3190                                CharOperation::Keep { bytes } => {
3191                                    let edit_end = edit_start + bytes;
3192                                    let edit_range = snapshot.anchor_after(edit_start)
3193                                        ..snapshot.anchor_before(edit_end);
3194                                    edit_start = edit_end;
3195                                    codegen.last_equal_ranges.push(edit_range);
3196                                    None
3197                                }
3198                            })
3199                            .collect::<Vec<_>>();
3200
3201                        if codegen.active {
3202                            codegen.apply_edits(edits.iter().cloned(), cx);
3203                            codegen.reapply_line_based_diff(line_ops.iter().cloned(), cx);
3204                        }
3205                        codegen.edits.extend(edits);
3206                        codegen.line_operations = line_ops;
3207                        codegen.edit_position = Some(snapshot.anchor_after(edit_start));
3208
3209                        cx.notify();
3210                    })?;
3211                }
3212
3213                // Streaming stopped and we have the new text in the buffer, and a line-based diff applied for the whole new buffer.
3214                // That diff is not what a regular diff is and might look unexpected, ergo apply a regular diff.
3215                // It's fine to apply even if the rest of the line diffing fails, as no more hunks are coming through `diff_rx`.
3216                let batch_diff_task =
3217                    codegen.update(cx, |codegen, cx| codegen.reapply_batch_diff(cx))?;
3218                let (line_based_stream_diff, ()) = join!(line_based_stream_diff, batch_diff_task);
3219                line_based_stream_diff?;
3220
3221                anyhow::Ok(())
3222            };
3223
3224            let result = generate.await;
3225            let elapsed_time = start_time.elapsed().as_secs_f64();
3226
3227            codegen
3228                .update(cx, |this, cx| {
3229                    this.message_id = message_id;
3230                    this.last_equal_ranges.clear();
3231                    if let Err(error) = result {
3232                        this.status = CodegenStatus::Error(error);
3233                    } else {
3234                        this.status = CodegenStatus::Done;
3235                    }
3236                    this.elapsed_time = Some(elapsed_time);
3237                    this.completion = Some(completion.lock().clone());
3238                    cx.emit(CodegenEvent::Finished);
3239                    cx.notify();
3240                })
3241                .ok();
3242        });
3243        cx.notify();
3244    }
3245
3246    pub fn stop(&mut self, cx: &mut Context<Self>) {
3247        self.last_equal_ranges.clear();
3248        if self.diff.is_empty() {
3249            self.status = CodegenStatus::Idle;
3250        } else {
3251            self.status = CodegenStatus::Done;
3252        }
3253        self.generation = Task::ready(());
3254        cx.emit(CodegenEvent::Finished);
3255        cx.notify();
3256    }
3257
3258    pub fn undo(&mut self, cx: &mut Context<Self>) {
3259        self.buffer.update(cx, |buffer, cx| {
3260            if let Some(transaction_id) = self.transformation_transaction_id.take() {
3261                buffer.undo_transaction(transaction_id, cx);
3262                buffer.refresh_preview(cx);
3263            }
3264        });
3265    }
3266
3267    fn apply_edits(
3268        &mut self,
3269        edits: impl IntoIterator<Item = (Range<Anchor>, String)>,
3270        cx: &mut Context<CodegenAlternative>,
3271    ) {
3272        let transaction = self.buffer.update(cx, |buffer, cx| {
3273            // Avoid grouping assistant edits with user edits.
3274            buffer.finalize_last_transaction(cx);
3275            buffer.start_transaction(cx);
3276            buffer.edit(edits, None, cx);
3277            buffer.end_transaction(cx)
3278        });
3279
3280        if let Some(transaction) = transaction {
3281            if let Some(first_transaction) = self.transformation_transaction_id {
3282                // Group all assistant edits into the first transaction.
3283                self.buffer.update(cx, |buffer, cx| {
3284                    buffer.merge_transactions(transaction, first_transaction, cx)
3285                });
3286            } else {
3287                self.transformation_transaction_id = Some(transaction);
3288                self.buffer
3289                    .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
3290            }
3291        }
3292    }
3293
3294    fn reapply_line_based_diff(
3295        &mut self,
3296        line_operations: impl IntoIterator<Item = LineOperation>,
3297        cx: &mut Context<Self>,
3298    ) {
3299        let old_snapshot = self.snapshot.clone();
3300        let old_range = self.range.to_point(&old_snapshot);
3301        let new_snapshot = self.buffer.read(cx).snapshot(cx);
3302        let new_range = self.range.to_point(&new_snapshot);
3303
3304        let mut old_row = old_range.start.row;
3305        let mut new_row = new_range.start.row;
3306
3307        self.diff.deleted_row_ranges.clear();
3308        self.diff.inserted_row_ranges.clear();
3309        for operation in line_operations {
3310            match operation {
3311                LineOperation::Keep { lines } => {
3312                    old_row += lines;
3313                    new_row += lines;
3314                }
3315                LineOperation::Delete { lines } => {
3316                    let old_end_row = old_row + lines - 1;
3317                    let new_row = new_snapshot.anchor_before(Point::new(new_row, 0));
3318
3319                    if let Some((_, last_deleted_row_range)) =
3320                        self.diff.deleted_row_ranges.last_mut()
3321                    {
3322                        if *last_deleted_row_range.end() + 1 == old_row {
3323                            *last_deleted_row_range = *last_deleted_row_range.start()..=old_end_row;
3324                        } else {
3325                            self.diff
3326                                .deleted_row_ranges
3327                                .push((new_row, old_row..=old_end_row));
3328                        }
3329                    } else {
3330                        self.diff
3331                            .deleted_row_ranges
3332                            .push((new_row, old_row..=old_end_row));
3333                    }
3334
3335                    old_row += lines;
3336                }
3337                LineOperation::Insert { lines } => {
3338                    let new_end_row = new_row + lines - 1;
3339                    let start = new_snapshot.anchor_before(Point::new(new_row, 0));
3340                    let end = new_snapshot.anchor_before(Point::new(
3341                        new_end_row,
3342                        new_snapshot.line_len(MultiBufferRow(new_end_row)),
3343                    ));
3344                    self.diff.inserted_row_ranges.push(start..end);
3345                    new_row += lines;
3346                }
3347            }
3348
3349            cx.notify();
3350        }
3351    }
3352
3353    fn reapply_batch_diff(&mut self, cx: &mut Context<Self>) -> Task<()> {
3354        let old_snapshot = self.snapshot.clone();
3355        let old_range = self.range.to_point(&old_snapshot);
3356        let new_snapshot = self.buffer.read(cx).snapshot(cx);
3357        let new_range = self.range.to_point(&new_snapshot);
3358
3359        cx.spawn(async move |codegen, cx| {
3360            let (deleted_row_ranges, inserted_row_ranges) = cx
3361                .background_spawn(async move {
3362                    let old_text = old_snapshot
3363                        .text_for_range(
3364                            Point::new(old_range.start.row, 0)
3365                                ..Point::new(
3366                                    old_range.end.row,
3367                                    old_snapshot.line_len(MultiBufferRow(old_range.end.row)),
3368                                ),
3369                        )
3370                        .collect::<String>();
3371                    let new_text = new_snapshot
3372                        .text_for_range(
3373                            Point::new(new_range.start.row, 0)
3374                                ..Point::new(
3375                                    new_range.end.row,
3376                                    new_snapshot.line_len(MultiBufferRow(new_range.end.row)),
3377                                ),
3378                        )
3379                        .collect::<String>();
3380
3381                    let old_start_row = old_range.start.row;
3382                    let new_start_row = new_range.start.row;
3383                    let mut deleted_row_ranges: Vec<(Anchor, RangeInclusive<u32>)> = Vec::new();
3384                    let mut inserted_row_ranges = Vec::new();
3385                    for (old_rows, new_rows) in line_diff(&old_text, &new_text) {
3386                        let old_rows = old_start_row + old_rows.start..old_start_row + old_rows.end;
3387                        let new_rows = new_start_row + new_rows.start..new_start_row + new_rows.end;
3388                        if !old_rows.is_empty() {
3389                            deleted_row_ranges.push((
3390                                new_snapshot.anchor_before(Point::new(new_rows.start, 0)),
3391                                old_rows.start..=old_rows.end - 1,
3392                            ));
3393                        }
3394                        if !new_rows.is_empty() {
3395                            let start = new_snapshot.anchor_before(Point::new(new_rows.start, 0));
3396                            let new_end_row = new_rows.end - 1;
3397                            let end = new_snapshot.anchor_before(Point::new(
3398                                new_end_row,
3399                                new_snapshot.line_len(MultiBufferRow(new_end_row)),
3400                            ));
3401                            inserted_row_ranges.push(start..end);
3402                        }
3403                    }
3404                    (deleted_row_ranges, inserted_row_ranges)
3405                })
3406                .await;
3407
3408            codegen
3409                .update(cx, |codegen, cx| {
3410                    codegen.diff.deleted_row_ranges = deleted_row_ranges;
3411                    codegen.diff.inserted_row_ranges = inserted_row_ranges;
3412                    cx.notify();
3413                })
3414                .ok();
3415        })
3416    }
3417}
3418
3419struct StripInvalidSpans<T> {
3420    stream: T,
3421    stream_done: bool,
3422    buffer: String,
3423    first_line: bool,
3424    line_end: bool,
3425    starts_with_code_block: bool,
3426}
3427
3428impl<T> StripInvalidSpans<T>
3429where
3430    T: Stream<Item = Result<String>>,
3431{
3432    fn new(stream: T) -> Self {
3433        Self {
3434            stream,
3435            stream_done: false,
3436            buffer: String::new(),
3437            first_line: true,
3438            line_end: false,
3439            starts_with_code_block: false,
3440        }
3441    }
3442}
3443
3444impl<T> Stream for StripInvalidSpans<T>
3445where
3446    T: Stream<Item = Result<String>>,
3447{
3448    type Item = Result<String>;
3449
3450    fn poll_next(self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<Option<Self::Item>> {
3451        const CODE_BLOCK_DELIMITER: &str = "```";
3452        const CURSOR_SPAN: &str = "<|CURSOR|>";
3453
3454        let this = unsafe { self.get_unchecked_mut() };
3455        loop {
3456            if !this.stream_done {
3457                let mut stream = unsafe { Pin::new_unchecked(&mut this.stream) };
3458                match stream.as_mut().poll_next(cx) {
3459                    Poll::Ready(Some(Ok(chunk))) => {
3460                        this.buffer.push_str(&chunk);
3461                    }
3462                    Poll::Ready(Some(Err(error))) => return Poll::Ready(Some(Err(error))),
3463                    Poll::Ready(None) => {
3464                        this.stream_done = true;
3465                    }
3466                    Poll::Pending => return Poll::Pending,
3467                }
3468            }
3469
3470            let mut chunk = String::new();
3471            let mut consumed = 0;
3472            if !this.buffer.is_empty() {
3473                let mut lines = this.buffer.split('\n').enumerate().peekable();
3474                while let Some((line_ix, line)) = lines.next() {
3475                    if line_ix > 0 {
3476                        this.first_line = false;
3477                    }
3478
3479                    if this.first_line {
3480                        let trimmed_line = line.trim();
3481                        if lines.peek().is_some() {
3482                            if trimmed_line.starts_with(CODE_BLOCK_DELIMITER) {
3483                                consumed += line.len() + 1;
3484                                this.starts_with_code_block = true;
3485                                continue;
3486                            }
3487                        } else if trimmed_line.is_empty()
3488                            || prefixes(CODE_BLOCK_DELIMITER)
3489                                .any(|prefix| trimmed_line.starts_with(prefix))
3490                        {
3491                            break;
3492                        }
3493                    }
3494
3495                    let line_without_cursor = line.replace(CURSOR_SPAN, "");
3496                    if lines.peek().is_some() {
3497                        if this.line_end {
3498                            chunk.push('\n');
3499                        }
3500
3501                        chunk.push_str(&line_without_cursor);
3502                        this.line_end = true;
3503                        consumed += line.len() + 1;
3504                    } else if this.stream_done {
3505                        if !this.starts_with_code_block
3506                            || !line_without_cursor.trim().ends_with(CODE_BLOCK_DELIMITER)
3507                        {
3508                            if this.line_end {
3509                                chunk.push('\n');
3510                            }
3511
3512                            chunk.push_str(&line);
3513                        }
3514
3515                        consumed += line.len();
3516                    } else {
3517                        let trimmed_line = line.trim();
3518                        if trimmed_line.is_empty()
3519                            || prefixes(CURSOR_SPAN).any(|prefix| trimmed_line.ends_with(prefix))
3520                            || prefixes(CODE_BLOCK_DELIMITER)
3521                                .any(|prefix| trimmed_line.ends_with(prefix))
3522                        {
3523                            break;
3524                        } else {
3525                            if this.line_end {
3526                                chunk.push('\n');
3527                                this.line_end = false;
3528                            }
3529
3530                            chunk.push_str(&line_without_cursor);
3531                            consumed += line.len();
3532                        }
3533                    }
3534                }
3535            }
3536
3537            this.buffer = this.buffer.split_off(consumed);
3538            if !chunk.is_empty() {
3539                return Poll::Ready(Some(Ok(chunk)));
3540            } else if this.stream_done {
3541                return Poll::Ready(None);
3542            }
3543        }
3544    }
3545}
3546
3547struct AssistantCodeActionProvider {
3548    editor: WeakEntity<Editor>,
3549    workspace: WeakEntity<Workspace>,
3550}
3551
3552const ASSISTANT_CODE_ACTION_PROVIDER_ID: &str = "assistant";
3553
3554impl CodeActionProvider for AssistantCodeActionProvider {
3555    fn id(&self) -> Arc<str> {
3556        ASSISTANT_CODE_ACTION_PROVIDER_ID.into()
3557    }
3558
3559    fn code_actions(
3560        &self,
3561        buffer: &Entity<Buffer>,
3562        range: Range<text::Anchor>,
3563        _: &mut Window,
3564        cx: &mut App,
3565    ) -> Task<Result<Vec<CodeAction>>> {
3566        if !Assistant::enabled(cx) {
3567            return Task::ready(Ok(Vec::new()));
3568        }
3569
3570        let snapshot = buffer.read(cx).snapshot();
3571        let mut range = range.to_point(&snapshot);
3572
3573        // Expand the range to line boundaries.
3574        range.start.column = 0;
3575        range.end.column = snapshot.line_len(range.end.row);
3576
3577        let mut has_diagnostics = false;
3578        for diagnostic in snapshot.diagnostics_in_range::<_, Point>(range.clone(), false) {
3579            range.start = cmp::min(range.start, diagnostic.range.start);
3580            range.end = cmp::max(range.end, diagnostic.range.end);
3581            has_diagnostics = true;
3582        }
3583        if has_diagnostics {
3584            if let Some(symbols_containing_start) = snapshot.symbols_containing(range.start, None) {
3585                if let Some(symbol) = symbols_containing_start.last() {
3586                    range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
3587                    range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
3588                }
3589            }
3590
3591            if let Some(symbols_containing_end) = snapshot.symbols_containing(range.end, None) {
3592                if let Some(symbol) = symbols_containing_end.last() {
3593                    range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
3594                    range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
3595                }
3596            }
3597
3598            Task::ready(Ok(vec![CodeAction {
3599                server_id: language::LanguageServerId(0),
3600                range: snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end),
3601                lsp_action: LspAction::Action(Box::new(lsp::CodeAction {
3602                    title: "Fix with Assistant".into(),
3603                    ..Default::default()
3604                })),
3605                resolved: true,
3606            }]))
3607        } else {
3608            Task::ready(Ok(Vec::new()))
3609        }
3610    }
3611
3612    fn apply_code_action(
3613        &self,
3614        buffer: Entity<Buffer>,
3615        action: CodeAction,
3616        excerpt_id: ExcerptId,
3617        _push_to_history: bool,
3618        window: &mut Window,
3619        cx: &mut App,
3620    ) -> Task<Result<ProjectTransaction>> {
3621        let editor = self.editor.clone();
3622        let workspace = self.workspace.clone();
3623        window.spawn(cx, async move |cx| {
3624            let editor = editor.upgrade().context("editor was released")?;
3625            let range = editor
3626                .update(cx, |editor, cx| {
3627                    editor.buffer().update(cx, |multibuffer, cx| {
3628                        let buffer = buffer.read(cx);
3629                        let multibuffer_snapshot = multibuffer.read(cx);
3630
3631                        let old_context_range =
3632                            multibuffer_snapshot.context_range_for_excerpt(excerpt_id)?;
3633                        let mut new_context_range = old_context_range.clone();
3634                        if action
3635                            .range
3636                            .start
3637                            .cmp(&old_context_range.start, buffer)
3638                            .is_lt()
3639                        {
3640                            new_context_range.start = action.range.start;
3641                        }
3642                        if action.range.end.cmp(&old_context_range.end, buffer).is_gt() {
3643                            new_context_range.end = action.range.end;
3644                        }
3645                        drop(multibuffer_snapshot);
3646
3647                        if new_context_range != old_context_range {
3648                            multibuffer.resize_excerpt(excerpt_id, new_context_range, cx);
3649                        }
3650
3651                        let multibuffer_snapshot = multibuffer.read(cx);
3652                        Some(
3653                            multibuffer_snapshot
3654                                .anchor_in_excerpt(excerpt_id, action.range.start)?
3655                                ..multibuffer_snapshot
3656                                    .anchor_in_excerpt(excerpt_id, action.range.end)?,
3657                        )
3658                    })
3659                })?
3660                .context("invalid range")?;
3661            let assistant_panel = workspace.update(cx, |workspace, cx| {
3662                workspace
3663                    .panel::<AssistantPanel>(cx)
3664                    .context("assistant panel was released")
3665            })??;
3666
3667            cx.update_global(|assistant: &mut InlineAssistant, window, cx| {
3668                let assist_id = assistant.suggest_assist(
3669                    &editor,
3670                    range,
3671                    "Fix Diagnostics".into(),
3672                    None,
3673                    true,
3674                    Some(workspace),
3675                    Some(&assistant_panel),
3676                    window,
3677                    cx,
3678                );
3679                assistant.start_assist(assist_id, window, cx);
3680            })?;
3681
3682            Ok(ProjectTransaction::default())
3683        })
3684    }
3685}
3686
3687fn prefixes(text: &str) -> impl Iterator<Item = &str> {
3688    (0..text.len() - 1).map(|ix| &text[..ix + 1])
3689}
3690
3691fn merge_ranges(ranges: &mut Vec<Range<Anchor>>, buffer: &MultiBufferSnapshot) {
3692    ranges.sort_unstable_by(|a, b| {
3693        a.start
3694            .cmp(&b.start, buffer)
3695            .then_with(|| b.end.cmp(&a.end, buffer))
3696    });
3697
3698    let mut ix = 0;
3699    while ix + 1 < ranges.len() {
3700        let b = ranges[ix + 1].clone();
3701        let a = &mut ranges[ix];
3702        if a.end.cmp(&b.start, buffer).is_gt() {
3703            if a.end.cmp(&b.end, buffer).is_lt() {
3704                a.end = b.end;
3705            }
3706            ranges.remove(ix + 1);
3707        } else {
3708            ix += 1;
3709        }
3710    }
3711}
3712
3713#[cfg(test)]
3714mod tests {
3715    use super::*;
3716    use futures::stream::{self};
3717    use gpui::TestAppContext;
3718    use indoc::indoc;
3719    use language::{
3720        Buffer, Language, LanguageConfig, LanguageMatcher, Point, language_settings,
3721        tree_sitter_rust,
3722    };
3723    use language_model::{LanguageModelRegistry, TokenUsage};
3724    use rand::prelude::*;
3725    use serde::Serialize;
3726    use settings::SettingsStore;
3727    use std::{future, sync::Arc};
3728
3729    #[derive(Serialize)]
3730    pub struct DummyCompletionRequest {
3731        pub name: String,
3732    }
3733
3734    #[gpui::test(iterations = 10)]
3735    async fn test_transform_autoindent(cx: &mut TestAppContext, mut rng: StdRng) {
3736        cx.set_global(cx.update(SettingsStore::test));
3737        cx.update(language_model::LanguageModelRegistry::test);
3738        cx.update(language_settings::init);
3739
3740        let text = indoc! {"
3741            fn main() {
3742                let x = 0;
3743                for _ in 0..10 {
3744                    x += 1;
3745                }
3746            }
3747        "};
3748        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
3749        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
3750        let range = buffer.read_with(cx, |buffer, cx| {
3751            let snapshot = buffer.snapshot(cx);
3752            snapshot.anchor_before(Point::new(1, 0))..snapshot.anchor_after(Point::new(4, 5))
3753        });
3754        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3755        let codegen = cx.new(|cx| {
3756            CodegenAlternative::new(
3757                buffer.clone(),
3758                range.clone(),
3759                true,
3760                None,
3761                prompt_builder,
3762                cx,
3763            )
3764        });
3765
3766        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
3767
3768        let mut new_text = concat!(
3769            "       let mut x = 0;\n",
3770            "       while x < 10 {\n",
3771            "           x += 1;\n",
3772            "       }",
3773        );
3774        while !new_text.is_empty() {
3775            let max_len = cmp::min(new_text.len(), 10);
3776            let len = rng.gen_range(1..=max_len);
3777            let (chunk, suffix) = new_text.split_at(len);
3778            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
3779            new_text = suffix;
3780            cx.background_executor.run_until_parked();
3781        }
3782        drop(chunks_tx);
3783        cx.background_executor.run_until_parked();
3784
3785        assert_eq!(
3786            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3787            indoc! {"
3788                fn main() {
3789                    let mut x = 0;
3790                    while x < 10 {
3791                        x += 1;
3792                    }
3793                }
3794            "}
3795        );
3796    }
3797
3798    #[gpui::test(iterations = 10)]
3799    async fn test_autoindent_when_generating_past_indentation(
3800        cx: &mut TestAppContext,
3801        mut rng: StdRng,
3802    ) {
3803        cx.set_global(cx.update(SettingsStore::test));
3804        cx.update(language_settings::init);
3805
3806        let text = indoc! {"
3807            fn main() {
3808                le
3809            }
3810        "};
3811        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
3812        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
3813        let range = buffer.read_with(cx, |buffer, cx| {
3814            let snapshot = buffer.snapshot(cx);
3815            snapshot.anchor_before(Point::new(1, 6))..snapshot.anchor_after(Point::new(1, 6))
3816        });
3817        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3818        let codegen = cx.new(|cx| {
3819            CodegenAlternative::new(
3820                buffer.clone(),
3821                range.clone(),
3822                true,
3823                None,
3824                prompt_builder,
3825                cx,
3826            )
3827        });
3828
3829        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
3830
3831        cx.background_executor.run_until_parked();
3832
3833        let mut new_text = concat!(
3834            "t mut x = 0;\n",
3835            "while x < 10 {\n",
3836            "    x += 1;\n",
3837            "}", //
3838        );
3839        while !new_text.is_empty() {
3840            let max_len = cmp::min(new_text.len(), 10);
3841            let len = rng.gen_range(1..=max_len);
3842            let (chunk, suffix) = new_text.split_at(len);
3843            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
3844            new_text = suffix;
3845            cx.background_executor.run_until_parked();
3846        }
3847        drop(chunks_tx);
3848        cx.background_executor.run_until_parked();
3849
3850        assert_eq!(
3851            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3852            indoc! {"
3853                fn main() {
3854                    let mut x = 0;
3855                    while x < 10 {
3856                        x += 1;
3857                    }
3858                }
3859            "}
3860        );
3861    }
3862
3863    #[gpui::test(iterations = 10)]
3864    async fn test_autoindent_when_generating_before_indentation(
3865        cx: &mut TestAppContext,
3866        mut rng: StdRng,
3867    ) {
3868        cx.update(LanguageModelRegistry::test);
3869        cx.set_global(cx.update(SettingsStore::test));
3870        cx.update(language_settings::init);
3871
3872        let text = concat!(
3873            "fn main() {\n",
3874            "  \n",
3875            "}\n" //
3876        );
3877        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
3878        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
3879        let range = buffer.read_with(cx, |buffer, cx| {
3880            let snapshot = buffer.snapshot(cx);
3881            snapshot.anchor_before(Point::new(1, 2))..snapshot.anchor_after(Point::new(1, 2))
3882        });
3883        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3884        let codegen = cx.new(|cx| {
3885            CodegenAlternative::new(
3886                buffer.clone(),
3887                range.clone(),
3888                true,
3889                None,
3890                prompt_builder,
3891                cx,
3892            )
3893        });
3894
3895        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
3896
3897        cx.background_executor.run_until_parked();
3898
3899        let mut new_text = concat!(
3900            "let mut x = 0;\n",
3901            "while x < 10 {\n",
3902            "    x += 1;\n",
3903            "}", //
3904        );
3905        while !new_text.is_empty() {
3906            let max_len = cmp::min(new_text.len(), 10);
3907            let len = rng.gen_range(1..=max_len);
3908            let (chunk, suffix) = new_text.split_at(len);
3909            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
3910            new_text = suffix;
3911            cx.background_executor.run_until_parked();
3912        }
3913        drop(chunks_tx);
3914        cx.background_executor.run_until_parked();
3915
3916        assert_eq!(
3917            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3918            indoc! {"
3919                fn main() {
3920                    let mut x = 0;
3921                    while x < 10 {
3922                        x += 1;
3923                    }
3924                }
3925            "}
3926        );
3927    }
3928
3929    #[gpui::test(iterations = 10)]
3930    async fn test_autoindent_respects_tabs_in_selection(cx: &mut TestAppContext) {
3931        cx.update(LanguageModelRegistry::test);
3932        cx.set_global(cx.update(SettingsStore::test));
3933        cx.update(language_settings::init);
3934
3935        let text = indoc! {"
3936            func main() {
3937            \tx := 0
3938            \tfor i := 0; i < 10; i++ {
3939            \t\tx++
3940            \t}
3941            }
3942        "};
3943        let buffer = cx.new(|cx| Buffer::local(text, cx));
3944        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
3945        let range = buffer.read_with(cx, |buffer, cx| {
3946            let snapshot = buffer.snapshot(cx);
3947            snapshot.anchor_before(Point::new(0, 0))..snapshot.anchor_after(Point::new(4, 2))
3948        });
3949        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3950        let codegen = cx.new(|cx| {
3951            CodegenAlternative::new(
3952                buffer.clone(),
3953                range.clone(),
3954                true,
3955                None,
3956                prompt_builder,
3957                cx,
3958            )
3959        });
3960
3961        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
3962        let new_text = concat!(
3963            "func main() {\n",
3964            "\tx := 0\n",
3965            "\tfor x < 10 {\n",
3966            "\t\tx++\n",
3967            "\t}", //
3968        );
3969        chunks_tx.unbounded_send(new_text.to_string()).unwrap();
3970        drop(chunks_tx);
3971        cx.background_executor.run_until_parked();
3972
3973        assert_eq!(
3974            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3975            indoc! {"
3976                func main() {
3977                \tx := 0
3978                \tfor x < 10 {
3979                \t\tx++
3980                \t}
3981                }
3982            "}
3983        );
3984    }
3985
3986    #[gpui::test]
3987    async fn test_inactive_codegen_alternative(cx: &mut TestAppContext) {
3988        cx.update(LanguageModelRegistry::test);
3989        cx.set_global(cx.update(SettingsStore::test));
3990        cx.update(language_settings::init);
3991
3992        let text = indoc! {"
3993            fn main() {
3994                let x = 0;
3995            }
3996        "};
3997        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
3998        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
3999        let range = buffer.read_with(cx, |buffer, cx| {
4000            let snapshot = buffer.snapshot(cx);
4001            snapshot.anchor_before(Point::new(1, 0))..snapshot.anchor_after(Point::new(1, 14))
4002        });
4003        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
4004        let codegen = cx.new(|cx| {
4005            CodegenAlternative::new(
4006                buffer.clone(),
4007                range.clone(),
4008                false,
4009                None,
4010                prompt_builder,
4011                cx,
4012            )
4013        });
4014
4015        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
4016        chunks_tx
4017            .unbounded_send("let mut x = 0;\nx += 1;".to_string())
4018            .unwrap();
4019        drop(chunks_tx);
4020        cx.run_until_parked();
4021
4022        // The codegen is inactive, so the buffer doesn't get modified.
4023        assert_eq!(
4024            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
4025            text
4026        );
4027
4028        // Activating the codegen applies the changes.
4029        codegen.update(cx, |codegen, cx| codegen.set_active(true, cx));
4030        assert_eq!(
4031            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
4032            indoc! {"
4033                fn main() {
4034                    let mut x = 0;
4035                    x += 1;
4036                }
4037            "}
4038        );
4039
4040        // Deactivating the codegen undoes the changes.
4041        codegen.update(cx, |codegen, cx| codegen.set_active(false, cx));
4042        cx.run_until_parked();
4043        assert_eq!(
4044            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
4045            text
4046        );
4047    }
4048
4049    #[gpui::test]
4050    async fn test_strip_invalid_spans_from_codeblock() {
4051        assert_chunks("Lorem ipsum dolor", "Lorem ipsum dolor").await;
4052        assert_chunks("```\nLorem ipsum dolor", "Lorem ipsum dolor").await;
4053        assert_chunks("```\nLorem ipsum dolor\n```", "Lorem ipsum dolor").await;
4054        assert_chunks(
4055            "```html\n```js\nLorem ipsum dolor\n```\n```",
4056            "```js\nLorem ipsum dolor\n```",
4057        )
4058        .await;
4059        assert_chunks("``\nLorem ipsum dolor\n```", "``\nLorem ipsum dolor\n```").await;
4060        assert_chunks("Lorem<|CURSOR|> ipsum", "Lorem ipsum").await;
4061        assert_chunks("Lorem ipsum", "Lorem ipsum").await;
4062        assert_chunks("```\n<|CURSOR|>Lorem ipsum\n```", "Lorem ipsum").await;
4063
4064        async fn assert_chunks(text: &str, expected_text: &str) {
4065            for chunk_size in 1..=text.len() {
4066                let actual_text = StripInvalidSpans::new(chunks(text, chunk_size))
4067                    .map(|chunk| chunk.unwrap())
4068                    .collect::<String>()
4069                    .await;
4070                assert_eq!(
4071                    actual_text, expected_text,
4072                    "failed to strip invalid spans, chunk size: {}",
4073                    chunk_size
4074                );
4075            }
4076        }
4077
4078        fn chunks(text: &str, size: usize) -> impl Stream<Item = Result<String>> {
4079            stream::iter(
4080                text.chars()
4081                    .collect::<Vec<_>>()
4082                    .chunks(size)
4083                    .map(|chunk| Ok(chunk.iter().collect::<String>()))
4084                    .collect::<Vec<_>>(),
4085            )
4086        }
4087    }
4088
4089    fn simulate_response_stream(
4090        codegen: Entity<CodegenAlternative>,
4091        cx: &mut TestAppContext,
4092    ) -> mpsc::UnboundedSender<String> {
4093        let (chunks_tx, chunks_rx) = mpsc::unbounded();
4094        codegen.update(cx, |codegen, cx| {
4095            codegen.handle_stream(
4096                String::new(),
4097                String::new(),
4098                None,
4099                future::ready(Ok(LanguageModelTextStream {
4100                    message_id: None,
4101                    stream: chunks_rx.map(Ok).boxed(),
4102                    last_token_usage: Arc::new(Mutex::new(TokenUsage::default())),
4103                })),
4104                cx,
4105            );
4106        });
4107        chunks_tx
4108    }
4109
4110    fn rust_lang() -> Language {
4111        Language::new(
4112            LanguageConfig {
4113                name: "Rust".into(),
4114                matcher: LanguageMatcher {
4115                    path_suffixes: vec!["rs".to_string()],
4116                    ..Default::default()
4117                },
4118                ..Default::default()
4119            },
4120            Some(tree_sitter_rust::LANGUAGE.into()),
4121        )
4122        .with_indents_query(
4123            r#"
4124            (call_expression) @indent
4125            (field_expression) @indent
4126            (_ "(" ")" @end) @indent
4127            (_ "{" "}" @end) @indent
4128            "#,
4129        )
4130        .unwrap()
4131    }
4132}