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 _, ZedProFeatureFlag,
  22};
  23use fs::Fs;
  24use futures::{
  25    SinkExt, Stream, StreamExt, TryStreamExt as _,
  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, ModelType};
  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                    Default::default(),
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                        Default::default(),
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::<ZedProFeatureFlag>()
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                    ModelType::Default,
1770                    window,
1771                    cx,
1772                )
1773            }),
1774            edited_since_done: false,
1775            gutter_dimensions,
1776            prompt_history,
1777            prompt_history_ix: None,
1778            pending_prompt: String::new(),
1779            _codegen_subscription: cx.observe(&codegen, Self::handle_codegen_changed),
1780            editor_subscriptions: Vec::new(),
1781            codegen,
1782            pending_token_count: Task::ready(Ok(())),
1783            token_counts: None,
1784            _token_count_subscriptions: token_count_subscriptions,
1785            workspace,
1786            show_rate_limit_notice: false,
1787        };
1788        this.count_tokens(cx);
1789        this.subscribe_to_editor(window, cx);
1790        this
1791    }
1792
1793    fn subscribe_to_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1794        self.editor_subscriptions.clear();
1795        self.editor_subscriptions.push(cx.subscribe_in(
1796            &self.editor,
1797            window,
1798            Self::handle_prompt_editor_events,
1799        ));
1800    }
1801
1802    fn set_show_cursor_when_unfocused(
1803        &mut self,
1804        show_cursor_when_unfocused: bool,
1805        cx: &mut Context<Self>,
1806    ) {
1807        self.editor.update(cx, |editor, cx| {
1808            editor.set_show_cursor_when_unfocused(show_cursor_when_unfocused, cx)
1809        });
1810    }
1811
1812    fn unlink(&mut self, window: &mut Window, cx: &mut Context<Self>) {
1813        let prompt = self.prompt(cx);
1814        let focus = self.editor.focus_handle(cx).contains_focused(window, cx);
1815        self.editor = cx.new(|cx| {
1816            let mut editor = Editor::auto_height(Self::MAX_LINES as usize, window, cx);
1817            editor.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
1818            editor.set_placeholder_text(
1819                Self::placeholder_text(self.codegen.read(cx), window, cx),
1820                cx,
1821            );
1822            editor.set_placeholder_text("Add a prompt…", cx);
1823            editor.set_text(prompt, window, cx);
1824            if focus {
1825                window.focus(&editor.focus_handle(cx));
1826            }
1827            editor
1828        });
1829        self.subscribe_to_editor(window, cx);
1830    }
1831
1832    fn placeholder_text(codegen: &Codegen, window: &Window, cx: &App) -> String {
1833        let context_keybinding = text_for_action(&zed_actions::assistant::ToggleFocus, window, cx)
1834            .map(|keybinding| format!("{keybinding} for context"))
1835            .unwrap_or_default();
1836
1837        let action = if codegen.is_insertion {
1838            "Generate"
1839        } else {
1840            "Transform"
1841        };
1842
1843        format!("{action}{context_keybinding} • ↓↑ for history")
1844    }
1845
1846    fn prompt(&self, cx: &App) -> String {
1847        self.editor.read(cx).text(cx)
1848    }
1849
1850    fn toggle_rate_limit_notice(
1851        &mut self,
1852        _: &ClickEvent,
1853        window: &mut Window,
1854        cx: &mut Context<Self>,
1855    ) {
1856        self.show_rate_limit_notice = !self.show_rate_limit_notice;
1857        if self.show_rate_limit_notice {
1858            window.focus(&self.editor.focus_handle(cx));
1859        }
1860        cx.notify();
1861    }
1862
1863    fn handle_parent_editor_event(
1864        &mut self,
1865        _: &Entity<Editor>,
1866        event: &EditorEvent,
1867        _: &mut Window,
1868        cx: &mut Context<Self>,
1869    ) {
1870        if let EditorEvent::BufferEdited { .. } = event {
1871            self.count_tokens(cx);
1872        }
1873    }
1874
1875    fn handle_assistant_panel_event(
1876        &mut self,
1877        _: &Entity<AssistantPanel>,
1878        event: &AssistantPanelEvent,
1879        _: &mut Window,
1880        cx: &mut Context<Self>,
1881    ) {
1882        let AssistantPanelEvent::ContextEdited { .. } = event;
1883        self.count_tokens(cx);
1884    }
1885
1886    fn count_tokens(&mut self, cx: &mut Context<Self>) {
1887        let assist_id = self.id;
1888        self.pending_token_count = cx.spawn(async move |this, cx| {
1889            cx.background_executor().timer(Duration::from_secs(1)).await;
1890            let token_count = cx
1891                .update_global(|inline_assistant: &mut InlineAssistant, cx| {
1892                    let assist = inline_assistant
1893                        .assists
1894                        .get(&assist_id)
1895                        .context("assist not found")?;
1896                    anyhow::Ok(assist.count_tokens(cx))
1897                })??
1898                .await?;
1899
1900            this.update(cx, |this, cx| {
1901                this.token_counts = Some(token_count);
1902                cx.notify();
1903            })
1904        })
1905    }
1906
1907    fn handle_prompt_editor_events(
1908        &mut self,
1909        _: &Entity<Editor>,
1910        event: &EditorEvent,
1911        window: &mut Window,
1912        cx: &mut Context<Self>,
1913    ) {
1914        match event {
1915            EditorEvent::Edited { .. } => {
1916                if let Some(workspace) = window.root::<Workspace>().flatten() {
1917                    workspace.update(cx, |workspace, cx| {
1918                        let is_via_ssh = workspace
1919                            .project()
1920                            .update(cx, |project, _| project.is_via_ssh());
1921
1922                        workspace
1923                            .client()
1924                            .telemetry()
1925                            .log_edit_event("inline assist", is_via_ssh);
1926                    });
1927                }
1928                let prompt = self.editor.read(cx).text(cx);
1929                if self
1930                    .prompt_history_ix
1931                    .map_or(true, |ix| self.prompt_history[ix] != prompt)
1932                {
1933                    self.prompt_history_ix.take();
1934                    self.pending_prompt = prompt;
1935                }
1936
1937                self.edited_since_done = true;
1938                cx.notify();
1939            }
1940            EditorEvent::BufferEdited => {
1941                self.count_tokens(cx);
1942            }
1943            EditorEvent::Blurred => {
1944                if self.show_rate_limit_notice {
1945                    self.show_rate_limit_notice = false;
1946                    cx.notify();
1947                }
1948            }
1949            _ => {}
1950        }
1951    }
1952
1953    fn handle_codegen_changed(&mut self, _: Entity<Codegen>, cx: &mut Context<Self>) {
1954        match self.codegen.read(cx).status(cx) {
1955            CodegenStatus::Idle => {
1956                self.editor
1957                    .update(cx, |editor, _| editor.set_read_only(false));
1958            }
1959            CodegenStatus::Pending => {
1960                self.editor
1961                    .update(cx, |editor, _| editor.set_read_only(true));
1962            }
1963            CodegenStatus::Done => {
1964                self.edited_since_done = false;
1965                self.editor
1966                    .update(cx, |editor, _| editor.set_read_only(false));
1967            }
1968            CodegenStatus::Error(error) => {
1969                if cx.has_flag::<ZedProFeatureFlag>()
1970                    && error.error_code() == proto::ErrorCode::RateLimitExceeded
1971                    && !dismissed_rate_limit_notice()
1972                {
1973                    self.show_rate_limit_notice = true;
1974                    cx.notify();
1975                }
1976
1977                self.edited_since_done = false;
1978                self.editor
1979                    .update(cx, |editor, _| editor.set_read_only(false));
1980            }
1981        }
1982    }
1983
1984    fn restart(&mut self, _: &menu::Restart, _window: &mut Window, cx: &mut Context<Self>) {
1985        cx.emit(PromptEditorEvent::StartRequested);
1986    }
1987
1988    fn cancel(
1989        &mut self,
1990        _: &editor::actions::Cancel,
1991        _window: &mut Window,
1992        cx: &mut Context<Self>,
1993    ) {
1994        match self.codegen.read(cx).status(cx) {
1995            CodegenStatus::Idle | CodegenStatus::Done | CodegenStatus::Error(_) => {
1996                cx.emit(PromptEditorEvent::CancelRequested);
1997            }
1998            CodegenStatus::Pending => {
1999                cx.emit(PromptEditorEvent::StopRequested);
2000            }
2001        }
2002    }
2003
2004    fn confirm(&mut self, _: &menu::Confirm, _window: &mut Window, cx: &mut Context<Self>) {
2005        match self.codegen.read(cx).status(cx) {
2006            CodegenStatus::Idle => {
2007                cx.emit(PromptEditorEvent::StartRequested);
2008            }
2009            CodegenStatus::Pending => {
2010                cx.emit(PromptEditorEvent::DismissRequested);
2011            }
2012            CodegenStatus::Done => {
2013                if self.edited_since_done {
2014                    cx.emit(PromptEditorEvent::StartRequested);
2015                } else {
2016                    cx.emit(PromptEditorEvent::ConfirmRequested);
2017                }
2018            }
2019            CodegenStatus::Error(_) => {
2020                cx.emit(PromptEditorEvent::StartRequested);
2021            }
2022        }
2023    }
2024
2025    fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
2026        if let Some(ix) = self.prompt_history_ix {
2027            if ix > 0 {
2028                self.prompt_history_ix = Some(ix - 1);
2029                let prompt = self.prompt_history[ix - 1].as_str();
2030                self.editor.update(cx, |editor, cx| {
2031                    editor.set_text(prompt, window, cx);
2032                    editor.move_to_beginning(&Default::default(), window, cx);
2033                });
2034            }
2035        } else if !self.prompt_history.is_empty() {
2036            self.prompt_history_ix = Some(self.prompt_history.len() - 1);
2037            let prompt = self.prompt_history[self.prompt_history.len() - 1].as_str();
2038            self.editor.update(cx, |editor, cx| {
2039                editor.set_text(prompt, window, cx);
2040                editor.move_to_beginning(&Default::default(), window, cx);
2041            });
2042        }
2043    }
2044
2045    fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
2046        if let Some(ix) = self.prompt_history_ix {
2047            if ix < self.prompt_history.len() - 1 {
2048                self.prompt_history_ix = Some(ix + 1);
2049                let prompt = self.prompt_history[ix + 1].as_str();
2050                self.editor.update(cx, |editor, cx| {
2051                    editor.set_text(prompt, window, cx);
2052                    editor.move_to_end(&Default::default(), window, cx)
2053                });
2054            } else {
2055                self.prompt_history_ix = None;
2056                let prompt = self.pending_prompt.as_str();
2057                self.editor.update(cx, |editor, cx| {
2058                    editor.set_text(prompt, window, cx);
2059                    editor.move_to_end(&Default::default(), window, cx)
2060                });
2061            }
2062        }
2063    }
2064
2065    fn cycle_prev(
2066        &mut self,
2067        _: &CyclePreviousInlineAssist,
2068        _: &mut Window,
2069        cx: &mut Context<Self>,
2070    ) {
2071        self.codegen
2072            .update(cx, |codegen, cx| codegen.cycle_prev(cx));
2073    }
2074
2075    fn cycle_next(&mut self, _: &CycleNextInlineAssist, _: &mut Window, cx: &mut Context<Self>) {
2076        self.codegen
2077            .update(cx, |codegen, cx| codegen.cycle_next(cx));
2078    }
2079
2080    fn render_cycle_controls(&self, cx: &Context<Self>) -> AnyElement {
2081        let codegen = self.codegen.read(cx);
2082        let disabled = matches!(codegen.status(cx), CodegenStatus::Idle);
2083
2084        let model_registry = LanguageModelRegistry::read_global(cx);
2085        let default_model = model_registry.default_model().map(|default| default.model);
2086        let alternative_models = model_registry.inline_alternative_models();
2087
2088        let get_model_name = |index: usize| -> String {
2089            let name = |model: &Arc<dyn LanguageModel>| model.name().0.to_string();
2090
2091            match index {
2092                0 => default_model.as_ref().map_or_else(String::new, name),
2093                index if index <= alternative_models.len() => alternative_models
2094                    .get(index - 1)
2095                    .map_or_else(String::new, name),
2096                _ => String::new(),
2097            }
2098        };
2099
2100        let total_models = alternative_models.len() + 1;
2101
2102        if total_models <= 1 {
2103            return div().into_any_element();
2104        }
2105
2106        let current_index = codegen.active_alternative;
2107        let prev_index = (current_index + total_models - 1) % total_models;
2108        let next_index = (current_index + 1) % total_models;
2109
2110        let prev_model_name = get_model_name(prev_index);
2111        let next_model_name = get_model_name(next_index);
2112
2113        h_flex()
2114            .child(
2115                IconButton::new("previous", IconName::ChevronLeft)
2116                    .icon_color(Color::Muted)
2117                    .disabled(disabled || current_index == 0)
2118                    .shape(IconButtonShape::Square)
2119                    .tooltip({
2120                        let focus_handle = self.editor.focus_handle(cx);
2121                        move |window, cx| {
2122                            cx.new(|cx| {
2123                                let mut tooltip = Tooltip::new("Previous Alternative").key_binding(
2124                                    KeyBinding::for_action_in(
2125                                        &CyclePreviousInlineAssist,
2126                                        &focus_handle,
2127                                        window,
2128                                        cx,
2129                                    ),
2130                                );
2131                                if !disabled && current_index != 0 {
2132                                    tooltip = tooltip.meta(prev_model_name.clone());
2133                                }
2134                                tooltip
2135                            })
2136                            .into()
2137                        }
2138                    })
2139                    .on_click(cx.listener(|this, _, _, cx| {
2140                        this.codegen
2141                            .update(cx, |codegen, cx| codegen.cycle_prev(cx))
2142                    })),
2143            )
2144            .child(
2145                Label::new(format!(
2146                    "{}/{}",
2147                    codegen.active_alternative + 1,
2148                    codegen.alternative_count(cx)
2149                ))
2150                .size(LabelSize::Small)
2151                .color(if disabled {
2152                    Color::Disabled
2153                } else {
2154                    Color::Muted
2155                }),
2156            )
2157            .child(
2158                IconButton::new("next", IconName::ChevronRight)
2159                    .icon_color(Color::Muted)
2160                    .disabled(disabled || current_index == total_models - 1)
2161                    .shape(IconButtonShape::Square)
2162                    .tooltip({
2163                        let focus_handle = self.editor.focus_handle(cx);
2164                        move |window, cx| {
2165                            cx.new(|cx| {
2166                                let mut tooltip = Tooltip::new("Next Alternative").key_binding(
2167                                    KeyBinding::for_action_in(
2168                                        &CycleNextInlineAssist,
2169                                        &focus_handle,
2170                                        window,
2171                                        cx,
2172                                    ),
2173                                );
2174                                if !disabled && current_index != total_models - 1 {
2175                                    tooltip = tooltip.meta(next_model_name.clone());
2176                                }
2177                                tooltip
2178                            })
2179                            .into()
2180                        }
2181                    })
2182                    .on_click(cx.listener(|this, _, _, cx| {
2183                        this.codegen
2184                            .update(cx, |codegen, cx| codegen.cycle_next(cx))
2185                    })),
2186            )
2187            .into_any_element()
2188    }
2189
2190    fn render_token_count(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2191        let model = LanguageModelRegistry::read_global(cx)
2192            .default_model()?
2193            .model;
2194        let token_counts = self.token_counts?;
2195        let max_token_count = model.max_token_count();
2196
2197        let remaining_tokens = max_token_count as isize - token_counts.total as isize;
2198        let token_count_color = if remaining_tokens <= 0 {
2199            Color::Error
2200        } else if token_counts.total as f32 / max_token_count as f32 >= 0.8 {
2201            Color::Warning
2202        } else {
2203            Color::Muted
2204        };
2205
2206        let mut token_count = h_flex()
2207            .id("token_count")
2208            .gap_0p5()
2209            .child(
2210                Label::new(humanize_token_count(token_counts.total))
2211                    .size(LabelSize::Small)
2212                    .color(token_count_color),
2213            )
2214            .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
2215            .child(
2216                Label::new(humanize_token_count(max_token_count))
2217                    .size(LabelSize::Small)
2218                    .color(Color::Muted),
2219            );
2220        if let Some(workspace) = self.workspace.clone() {
2221            token_count = token_count
2222                .tooltip(move |window, cx| {
2223                    Tooltip::with_meta(
2224                        format!(
2225                            "Tokens Used ({} from the Assistant Panel)",
2226                            humanize_token_count(token_counts.assistant_panel)
2227                        ),
2228                        None,
2229                        "Click to open the Assistant Panel",
2230                        window,
2231                        cx,
2232                    )
2233                })
2234                .cursor_pointer()
2235                .on_mouse_down(gpui::MouseButton::Left, |_, _, cx| cx.stop_propagation())
2236                .on_click(move |_, window, cx| {
2237                    cx.stop_propagation();
2238                    workspace
2239                        .update(cx, |workspace, cx| {
2240                            workspace.focus_panel::<AssistantPanel>(window, cx)
2241                        })
2242                        .ok();
2243                });
2244        } else {
2245            token_count = token_count
2246                .cursor_default()
2247                .tooltip(Tooltip::text("Tokens used"));
2248        }
2249
2250        Some(token_count)
2251    }
2252
2253    fn render_prompt_editor(&self, cx: &mut Context<Self>) -> impl IntoElement {
2254        let settings = ThemeSettings::get_global(cx);
2255        let text_style = TextStyle {
2256            color: if self.editor.read(cx).read_only(cx) {
2257                cx.theme().colors().text_disabled
2258            } else {
2259                cx.theme().colors().text
2260            },
2261            font_family: settings.buffer_font.family.clone(),
2262            font_fallbacks: settings.buffer_font.fallbacks.clone(),
2263            font_size: settings.buffer_font_size(cx).into(),
2264            font_weight: settings.buffer_font.weight,
2265            line_height: relative(settings.buffer_line_height.value()),
2266            ..Default::default()
2267        };
2268        EditorElement::new(
2269            &self.editor,
2270            EditorStyle {
2271                background: cx.theme().colors().editor_background,
2272                local_player: cx.theme().players().local(),
2273                text: text_style,
2274                ..Default::default()
2275            },
2276        )
2277    }
2278
2279    fn render_rate_limit_notice(&self, cx: &mut Context<Self>) -> impl IntoElement {
2280        Popover::new().child(
2281            v_flex()
2282                .occlude()
2283                .p_2()
2284                .child(
2285                    Label::new("Out of Tokens")
2286                        .size(LabelSize::Small)
2287                        .weight(FontWeight::BOLD),
2288                )
2289                .child(Label::new(
2290                    "Try Zed Pro for higher limits, a wider range of models, and more.",
2291                ))
2292                .child(
2293                    h_flex()
2294                        .justify_between()
2295                        .child(CheckboxWithLabel::new(
2296                            "dont-show-again",
2297                            Label::new("Don't show again"),
2298                            if dismissed_rate_limit_notice() {
2299                                ui::ToggleState::Selected
2300                            } else {
2301                                ui::ToggleState::Unselected
2302                            },
2303                            |selection, _, cx| {
2304                                let is_dismissed = match selection {
2305                                    ui::ToggleState::Unselected => false,
2306                                    ui::ToggleState::Indeterminate => return,
2307                                    ui::ToggleState::Selected => true,
2308                                };
2309
2310                                set_rate_limit_notice_dismissed(is_dismissed, cx)
2311                            },
2312                        ))
2313                        .child(
2314                            h_flex()
2315                                .gap_2()
2316                                .child(
2317                                    Button::new("dismiss", "Dismiss")
2318                                        .style(ButtonStyle::Transparent)
2319                                        .on_click(cx.listener(Self::toggle_rate_limit_notice)),
2320                                )
2321                                .child(Button::new("more-info", "More Info").on_click(
2322                                    |_event, window, cx| {
2323                                        window.dispatch_action(
2324                                            Box::new(zed_actions::OpenAccountSettings),
2325                                            cx,
2326                                        )
2327                                    },
2328                                )),
2329                        ),
2330                ),
2331        )
2332    }
2333}
2334
2335const DISMISSED_RATE_LIMIT_NOTICE_KEY: &str = "dismissed-rate-limit-notice";
2336
2337fn dismissed_rate_limit_notice() -> bool {
2338    db::kvp::KEY_VALUE_STORE
2339        .read_kvp(DISMISSED_RATE_LIMIT_NOTICE_KEY)
2340        .log_err()
2341        .map_or(false, |s| s.is_some())
2342}
2343
2344fn set_rate_limit_notice_dismissed(is_dismissed: bool, cx: &mut App) {
2345    db::write_and_log(cx, move || async move {
2346        if is_dismissed {
2347            db::kvp::KEY_VALUE_STORE
2348                .write_kvp(DISMISSED_RATE_LIMIT_NOTICE_KEY.into(), "1".into())
2349                .await
2350        } else {
2351            db::kvp::KEY_VALUE_STORE
2352                .delete_kvp(DISMISSED_RATE_LIMIT_NOTICE_KEY.into())
2353                .await
2354        }
2355    })
2356}
2357
2358struct InlineAssist {
2359    group_id: InlineAssistGroupId,
2360    range: Range<Anchor>,
2361    editor: WeakEntity<Editor>,
2362    decorations: Option<InlineAssistDecorations>,
2363    codegen: Entity<Codegen>,
2364    _subscriptions: Vec<Subscription>,
2365    workspace: Option<WeakEntity<Workspace>>,
2366    include_context: bool,
2367}
2368
2369impl InlineAssist {
2370    fn new(
2371        assist_id: InlineAssistId,
2372        group_id: InlineAssistGroupId,
2373        include_context: bool,
2374        editor: &Entity<Editor>,
2375        prompt_editor: &Entity<PromptEditor>,
2376        prompt_block_id: CustomBlockId,
2377        end_block_id: CustomBlockId,
2378        range: Range<Anchor>,
2379        codegen: Entity<Codegen>,
2380        workspace: Option<WeakEntity<Workspace>>,
2381        window: &mut Window,
2382        cx: &mut App,
2383    ) -> Self {
2384        let prompt_editor_focus_handle = prompt_editor.focus_handle(cx);
2385        InlineAssist {
2386            group_id,
2387            include_context,
2388            editor: editor.downgrade(),
2389            decorations: Some(InlineAssistDecorations {
2390                prompt_block_id,
2391                prompt_editor: prompt_editor.clone(),
2392                removed_line_block_ids: HashSet::default(),
2393                end_block_id,
2394            }),
2395            range,
2396            codegen: codegen.clone(),
2397            workspace: workspace.clone(),
2398            _subscriptions: vec![
2399                window.on_focus_in(&prompt_editor_focus_handle, cx, move |_, cx| {
2400                    InlineAssistant::update_global(cx, |this, cx| {
2401                        this.handle_prompt_editor_focus_in(assist_id, cx)
2402                    })
2403                }),
2404                window.on_focus_out(&prompt_editor_focus_handle, cx, move |_, _, cx| {
2405                    InlineAssistant::update_global(cx, |this, cx| {
2406                        this.handle_prompt_editor_focus_out(assist_id, cx)
2407                    })
2408                }),
2409                window.subscribe(
2410                    prompt_editor,
2411                    cx,
2412                    move |prompt_editor, event, window, cx| {
2413                        InlineAssistant::update_global(cx, |this, cx| {
2414                            this.handle_prompt_editor_event(prompt_editor, event, window, cx)
2415                        })
2416                    },
2417                ),
2418                window.observe(&codegen, cx, {
2419                    let editor = editor.downgrade();
2420                    move |_, window, cx| {
2421                        if let Some(editor) = editor.upgrade() {
2422                            InlineAssistant::update_global(cx, |this, cx| {
2423                                if let Some(editor_assists) =
2424                                    this.assists_by_editor.get(&editor.downgrade())
2425                                {
2426                                    editor_assists.highlight_updates.send(()).ok();
2427                                }
2428
2429                                this.update_editor_blocks(&editor, assist_id, window, cx);
2430                            })
2431                        }
2432                    }
2433                }),
2434                window.subscribe(&codegen, cx, move |codegen, event, window, cx| {
2435                    InlineAssistant::update_global(cx, |this, cx| match event {
2436                        CodegenEvent::Undone => this.finish_assist(assist_id, false, window, cx),
2437                        CodegenEvent::Finished => {
2438                            let assist = if let Some(assist) = this.assists.get(&assist_id) {
2439                                assist
2440                            } else {
2441                                return;
2442                            };
2443
2444                            if let CodegenStatus::Error(error) = codegen.read(cx).status(cx) {
2445                                if assist.decorations.is_none() {
2446                                    if let Some(workspace) = assist
2447                                        .workspace
2448                                        .as_ref()
2449                                        .and_then(|workspace| workspace.upgrade())
2450                                    {
2451                                        let error = format!("Inline assistant error: {}", error);
2452                                        workspace.update(cx, |workspace, cx| {
2453                                            struct InlineAssistantError;
2454
2455                                            let id =
2456                                                NotificationId::composite::<InlineAssistantError>(
2457                                                    assist_id.0,
2458                                                );
2459
2460                                            workspace.show_toast(Toast::new(id, error), cx);
2461                                        })
2462                                    }
2463                                }
2464                            }
2465
2466                            if assist.decorations.is_none() {
2467                                this.finish_assist(assist_id, false, window, cx);
2468                            }
2469                        }
2470                    })
2471                }),
2472            ],
2473        }
2474    }
2475
2476    fn user_prompt(&self, cx: &App) -> Option<String> {
2477        let decorations = self.decorations.as_ref()?;
2478        Some(decorations.prompt_editor.read(cx).prompt(cx))
2479    }
2480
2481    fn assistant_panel_context(&self, cx: &mut App) -> Option<LanguageModelRequest> {
2482        if self.include_context {
2483            let workspace = self.workspace.as_ref()?;
2484            let workspace = workspace.upgrade()?.read(cx);
2485            let assistant_panel = workspace.panel::<AssistantPanel>(cx)?;
2486            Some(
2487                assistant_panel
2488                    .read(cx)
2489                    .active_context(cx)?
2490                    .read(cx)
2491                    .to_completion_request(RequestType::Chat, cx),
2492            )
2493        } else {
2494            None
2495        }
2496    }
2497
2498    pub fn count_tokens(&self, cx: &mut App) -> BoxFuture<'static, Result<TokenCounts>> {
2499        let Some(user_prompt) = self.user_prompt(cx) else {
2500            return future::ready(Err(anyhow!("no user prompt"))).boxed();
2501        };
2502        let assistant_panel_context = self.assistant_panel_context(cx);
2503        self.codegen
2504            .read(cx)
2505            .count_tokens(user_prompt, assistant_panel_context, cx)
2506    }
2507}
2508
2509struct InlineAssistDecorations {
2510    prompt_block_id: CustomBlockId,
2511    prompt_editor: Entity<PromptEditor>,
2512    removed_line_block_ids: HashSet<CustomBlockId>,
2513    end_block_id: CustomBlockId,
2514}
2515
2516#[derive(Copy, Clone, Debug)]
2517pub enum CodegenEvent {
2518    Finished,
2519    Undone,
2520}
2521
2522pub struct Codegen {
2523    alternatives: Vec<Entity<CodegenAlternative>>,
2524    active_alternative: usize,
2525    seen_alternatives: HashSet<usize>,
2526    subscriptions: Vec<Subscription>,
2527    buffer: Entity<MultiBuffer>,
2528    range: Range<Anchor>,
2529    initial_transaction_id: Option<TransactionId>,
2530    telemetry: Arc<Telemetry>,
2531    builder: Arc<PromptBuilder>,
2532    is_insertion: bool,
2533}
2534
2535impl Codegen {
2536    pub fn new(
2537        buffer: Entity<MultiBuffer>,
2538        range: Range<Anchor>,
2539        initial_transaction_id: Option<TransactionId>,
2540        telemetry: Arc<Telemetry>,
2541        builder: Arc<PromptBuilder>,
2542        cx: &mut Context<Self>,
2543    ) -> Self {
2544        let codegen = cx.new(|cx| {
2545            CodegenAlternative::new(
2546                buffer.clone(),
2547                range.clone(),
2548                false,
2549                Some(telemetry.clone()),
2550                builder.clone(),
2551                cx,
2552            )
2553        });
2554        let mut this = Self {
2555            is_insertion: range.to_offset(&buffer.read(cx).snapshot(cx)).is_empty(),
2556            alternatives: vec![codegen],
2557            active_alternative: 0,
2558            seen_alternatives: HashSet::default(),
2559            subscriptions: Vec::new(),
2560            buffer,
2561            range,
2562            initial_transaction_id,
2563            telemetry,
2564            builder,
2565        };
2566        this.activate(0, cx);
2567        this
2568    }
2569
2570    fn subscribe_to_alternative(&mut self, cx: &mut Context<Self>) {
2571        let codegen = self.active_alternative().clone();
2572        self.subscriptions.clear();
2573        self.subscriptions
2574            .push(cx.observe(&codegen, |_, _, cx| cx.notify()));
2575        self.subscriptions
2576            .push(cx.subscribe(&codegen, |_, _, event, cx| cx.emit(*event)));
2577    }
2578
2579    fn active_alternative(&self) -> &Entity<CodegenAlternative> {
2580        &self.alternatives[self.active_alternative]
2581    }
2582
2583    fn status<'a>(&self, cx: &'a App) -> &'a CodegenStatus {
2584        &self.active_alternative().read(cx).status
2585    }
2586
2587    fn alternative_count(&self, cx: &App) -> usize {
2588        LanguageModelRegistry::read_global(cx)
2589            .inline_alternative_models()
2590            .len()
2591            + 1
2592    }
2593
2594    pub fn cycle_prev(&mut self, cx: &mut Context<Self>) {
2595        let next_active_ix = if self.active_alternative == 0 {
2596            self.alternatives.len() - 1
2597        } else {
2598            self.active_alternative - 1
2599        };
2600        self.activate(next_active_ix, cx);
2601    }
2602
2603    pub fn cycle_next(&mut self, cx: &mut Context<Self>) {
2604        let next_active_ix = (self.active_alternative + 1) % self.alternatives.len();
2605        self.activate(next_active_ix, cx);
2606    }
2607
2608    fn activate(&mut self, index: usize, cx: &mut Context<Self>) {
2609        self.active_alternative()
2610            .update(cx, |codegen, cx| codegen.set_active(false, cx));
2611        self.seen_alternatives.insert(index);
2612        self.active_alternative = index;
2613        self.active_alternative()
2614            .update(cx, |codegen, cx| codegen.set_active(true, cx));
2615        self.subscribe_to_alternative(cx);
2616        cx.notify();
2617    }
2618
2619    pub fn start(
2620        &mut self,
2621        user_prompt: String,
2622        assistant_panel_context: Option<LanguageModelRequest>,
2623        cx: &mut Context<Self>,
2624    ) -> Result<()> {
2625        let alternative_models = LanguageModelRegistry::read_global(cx)
2626            .inline_alternative_models()
2627            .to_vec();
2628
2629        self.active_alternative()
2630            .update(cx, |alternative, cx| alternative.undo(cx));
2631        self.activate(0, cx);
2632        self.alternatives.truncate(1);
2633
2634        for _ in 0..alternative_models.len() {
2635            self.alternatives.push(cx.new(|cx| {
2636                CodegenAlternative::new(
2637                    self.buffer.clone(),
2638                    self.range.clone(),
2639                    false,
2640                    Some(self.telemetry.clone()),
2641                    self.builder.clone(),
2642                    cx,
2643                )
2644            }));
2645        }
2646
2647        let primary_model = LanguageModelRegistry::read_global(cx)
2648            .default_model()
2649            .context("no active model")?
2650            .model;
2651
2652        for (model, alternative) in iter::once(primary_model)
2653            .chain(alternative_models)
2654            .zip(&self.alternatives)
2655        {
2656            alternative.update(cx, |alternative, cx| {
2657                alternative.start(
2658                    user_prompt.clone(),
2659                    assistant_panel_context.clone(),
2660                    model.clone(),
2661                    cx,
2662                )
2663            })?;
2664        }
2665
2666        Ok(())
2667    }
2668
2669    pub fn stop(&mut self, cx: &mut Context<Self>) {
2670        for codegen in &self.alternatives {
2671            codegen.update(cx, |codegen, cx| codegen.stop(cx));
2672        }
2673    }
2674
2675    pub fn undo(&mut self, cx: &mut Context<Self>) {
2676        self.active_alternative()
2677            .update(cx, |codegen, cx| codegen.undo(cx));
2678
2679        self.buffer.update(cx, |buffer, cx| {
2680            if let Some(transaction_id) = self.initial_transaction_id.take() {
2681                buffer.undo_transaction(transaction_id, cx);
2682                buffer.refresh_preview(cx);
2683            }
2684        });
2685    }
2686
2687    pub fn count_tokens(
2688        &self,
2689        user_prompt: String,
2690        assistant_panel_context: Option<LanguageModelRequest>,
2691        cx: &App,
2692    ) -> BoxFuture<'static, Result<TokenCounts>> {
2693        self.active_alternative()
2694            .read(cx)
2695            .count_tokens(user_prompt, assistant_panel_context, cx)
2696    }
2697
2698    pub fn buffer(&self, cx: &App) -> Entity<MultiBuffer> {
2699        self.active_alternative().read(cx).buffer.clone()
2700    }
2701
2702    pub fn old_buffer(&self, cx: &App) -> Entity<Buffer> {
2703        self.active_alternative().read(cx).old_buffer.clone()
2704    }
2705
2706    pub fn snapshot(&self, cx: &App) -> MultiBufferSnapshot {
2707        self.active_alternative().read(cx).snapshot.clone()
2708    }
2709
2710    pub fn edit_position(&self, cx: &App) -> Option<Anchor> {
2711        self.active_alternative().read(cx).edit_position
2712    }
2713
2714    fn diff<'a>(&self, cx: &'a App) -> &'a Diff {
2715        &self.active_alternative().read(cx).diff
2716    }
2717
2718    pub fn last_equal_ranges<'a>(&self, cx: &'a App) -> &'a [Range<Anchor>] {
2719        self.active_alternative().read(cx).last_equal_ranges()
2720    }
2721}
2722
2723impl EventEmitter<CodegenEvent> for Codegen {}
2724
2725pub struct CodegenAlternative {
2726    buffer: Entity<MultiBuffer>,
2727    old_buffer: Entity<Buffer>,
2728    snapshot: MultiBufferSnapshot,
2729    edit_position: Option<Anchor>,
2730    range: Range<Anchor>,
2731    last_equal_ranges: Vec<Range<Anchor>>,
2732    transformation_transaction_id: Option<TransactionId>,
2733    status: CodegenStatus,
2734    generation: Task<()>,
2735    diff: Diff,
2736    telemetry: Option<Arc<Telemetry>>,
2737    _subscription: gpui::Subscription,
2738    builder: Arc<PromptBuilder>,
2739    active: bool,
2740    edits: Vec<(Range<Anchor>, String)>,
2741    line_operations: Vec<LineOperation>,
2742    request: Option<LanguageModelRequest>,
2743    elapsed_time: Option<f64>,
2744    completion: Option<String>,
2745    message_id: Option<String>,
2746}
2747
2748enum CodegenStatus {
2749    Idle,
2750    Pending,
2751    Done,
2752    Error(anyhow::Error),
2753}
2754
2755#[derive(Default)]
2756struct Diff {
2757    deleted_row_ranges: Vec<(Anchor, RangeInclusive<u32>)>,
2758    inserted_row_ranges: Vec<Range<Anchor>>,
2759}
2760
2761impl Diff {
2762    fn is_empty(&self) -> bool {
2763        self.deleted_row_ranges.is_empty() && self.inserted_row_ranges.is_empty()
2764    }
2765}
2766
2767impl EventEmitter<CodegenEvent> for CodegenAlternative {}
2768
2769impl CodegenAlternative {
2770    pub fn new(
2771        multi_buffer: Entity<MultiBuffer>,
2772        range: Range<Anchor>,
2773        active: bool,
2774        telemetry: Option<Arc<Telemetry>>,
2775        builder: Arc<PromptBuilder>,
2776        cx: &mut Context<Self>,
2777    ) -> Self {
2778        let snapshot = multi_buffer.read(cx).snapshot(cx);
2779
2780        let (buffer, _, _) = snapshot
2781            .range_to_buffer_ranges(range.clone())
2782            .pop()
2783            .unwrap();
2784        let old_buffer = cx.new(|cx| {
2785            let text = buffer.as_rope().clone();
2786            let line_ending = buffer.line_ending();
2787            let language = buffer.language().cloned();
2788            let language_registry = multi_buffer
2789                .read(cx)
2790                .buffer(buffer.remote_id())
2791                .unwrap()
2792                .read(cx)
2793                .language_registry();
2794
2795            let mut buffer = Buffer::local_normalized(text, line_ending, cx);
2796            buffer.set_language(language, cx);
2797            if let Some(language_registry) = language_registry {
2798                buffer.set_language_registry(language_registry)
2799            }
2800            buffer
2801        });
2802
2803        Self {
2804            buffer: multi_buffer.clone(),
2805            old_buffer,
2806            edit_position: None,
2807            message_id: None,
2808            snapshot,
2809            last_equal_ranges: Default::default(),
2810            transformation_transaction_id: None,
2811            status: CodegenStatus::Idle,
2812            generation: Task::ready(()),
2813            diff: Diff::default(),
2814            telemetry,
2815            _subscription: cx.subscribe(&multi_buffer, Self::handle_buffer_event),
2816            builder,
2817            active,
2818            edits: Vec::new(),
2819            line_operations: Vec::new(),
2820            range,
2821            request: None,
2822            elapsed_time: None,
2823            completion: None,
2824        }
2825    }
2826
2827    fn set_active(&mut self, active: bool, cx: &mut Context<Self>) {
2828        if active != self.active {
2829            self.active = active;
2830
2831            if self.active {
2832                let edits = self.edits.clone();
2833                self.apply_edits(edits, cx);
2834                if matches!(self.status, CodegenStatus::Pending) {
2835                    let line_operations = self.line_operations.clone();
2836                    self.reapply_line_based_diff(line_operations, cx);
2837                } else {
2838                    self.reapply_batch_diff(cx).detach();
2839                }
2840            } else if let Some(transaction_id) = self.transformation_transaction_id.take() {
2841                self.buffer.update(cx, |buffer, cx| {
2842                    buffer.undo_transaction(transaction_id, cx);
2843                    buffer.forget_transaction(transaction_id, cx);
2844                });
2845            }
2846        }
2847    }
2848
2849    fn handle_buffer_event(
2850        &mut self,
2851        _buffer: Entity<MultiBuffer>,
2852        event: &multi_buffer::Event,
2853        cx: &mut Context<Self>,
2854    ) {
2855        if let multi_buffer::Event::TransactionUndone { transaction_id } = event {
2856            if self.transformation_transaction_id == Some(*transaction_id) {
2857                self.transformation_transaction_id = None;
2858                self.generation = Task::ready(());
2859                cx.emit(CodegenEvent::Undone);
2860            }
2861        }
2862    }
2863
2864    pub fn last_equal_ranges(&self) -> &[Range<Anchor>] {
2865        &self.last_equal_ranges
2866    }
2867
2868    pub fn count_tokens(
2869        &self,
2870        user_prompt: String,
2871        assistant_panel_context: Option<LanguageModelRequest>,
2872        cx: &App,
2873    ) -> BoxFuture<'static, Result<TokenCounts>> {
2874        if let Some(ConfiguredModel { model, .. }) =
2875            LanguageModelRegistry::read_global(cx).inline_assistant_model()
2876        {
2877            let request = self.build_request(user_prompt, assistant_panel_context.clone(), cx);
2878            match request {
2879                Ok(request) => {
2880                    let total_count = model.count_tokens(request.clone(), cx);
2881                    let assistant_panel_count = assistant_panel_context
2882                        .map(|context| model.count_tokens(context, cx))
2883                        .unwrap_or_else(|| future::ready(Ok(0)).boxed());
2884
2885                    async move {
2886                        Ok(TokenCounts {
2887                            total: total_count.await?,
2888                            assistant_panel: assistant_panel_count.await?,
2889                        })
2890                    }
2891                    .boxed()
2892                }
2893                Err(error) => futures::future::ready(Err(error)).boxed(),
2894            }
2895        } else {
2896            future::ready(Err(anyhow!("no active model"))).boxed()
2897        }
2898    }
2899
2900    pub fn start(
2901        &mut self,
2902        user_prompt: String,
2903        assistant_panel_context: Option<LanguageModelRequest>,
2904        model: Arc<dyn LanguageModel>,
2905        cx: &mut Context<Self>,
2906    ) -> Result<()> {
2907        if let Some(transformation_transaction_id) = self.transformation_transaction_id.take() {
2908            self.buffer.update(cx, |buffer, cx| {
2909                buffer.undo_transaction(transformation_transaction_id, cx);
2910            });
2911        }
2912
2913        self.edit_position = Some(self.range.start.bias_right(&self.snapshot));
2914
2915        let api_key = model.api_key(cx);
2916        let telemetry_id = model.telemetry_id();
2917        let provider_id = model.provider_id();
2918        let stream: LocalBoxFuture<Result<LanguageModelTextStream>> =
2919            if user_prompt.trim().to_lowercase() == "delete" {
2920                async { Ok(LanguageModelTextStream::default()) }.boxed_local()
2921            } else {
2922                let request = self.build_request(user_prompt, assistant_panel_context, cx)?;
2923                self.request = Some(request.clone());
2924
2925                cx.spawn(async move |_, cx| model.stream_completion_text(request, &cx).await)
2926                    .boxed_local()
2927            };
2928        self.handle_stream(telemetry_id, provider_id.to_string(), api_key, stream, cx);
2929        Ok(())
2930    }
2931
2932    fn build_request(
2933        &self,
2934        user_prompt: String,
2935        assistant_panel_context: Option<LanguageModelRequest>,
2936        cx: &App,
2937    ) -> Result<LanguageModelRequest> {
2938        let buffer = self.buffer.read(cx).snapshot(cx);
2939        let language = buffer.language_at(self.range.start);
2940        let language_name = if let Some(language) = language.as_ref() {
2941            if Arc::ptr_eq(language, &language::PLAIN_TEXT) {
2942                None
2943            } else {
2944                Some(language.name())
2945            }
2946        } else {
2947            None
2948        };
2949
2950        let language_name = language_name.as_ref();
2951        let start = buffer.point_to_buffer_offset(self.range.start);
2952        let end = buffer.point_to_buffer_offset(self.range.end);
2953        let (buffer, range) = if let Some((start, end)) = start.zip(end) {
2954            let (start_buffer, start_buffer_offset) = start;
2955            let (end_buffer, end_buffer_offset) = end;
2956            if start_buffer.remote_id() == end_buffer.remote_id() {
2957                (start_buffer.clone(), start_buffer_offset..end_buffer_offset)
2958            } else {
2959                return Err(anyhow::anyhow!("invalid transformation range"));
2960            }
2961        } else {
2962            return Err(anyhow::anyhow!("invalid transformation range"));
2963        };
2964
2965        let prompt = self
2966            .builder
2967            .generate_inline_transformation_prompt(user_prompt, language_name, buffer, range)
2968            .map_err(|e| anyhow::anyhow!("Failed to generate content prompt: {}", e))?;
2969
2970        let mut messages = Vec::new();
2971        if let Some(context_request) = assistant_panel_context {
2972            messages = context_request.messages;
2973        }
2974
2975        messages.push(LanguageModelRequestMessage {
2976            role: Role::User,
2977            content: vec![prompt.into()],
2978            cache: false,
2979        });
2980
2981        Ok(LanguageModelRequest {
2982            thread_id: None,
2983            prompt_id: None,
2984            mode: None,
2985            messages,
2986            tools: Vec::new(),
2987            stop: Vec::new(),
2988            temperature: None,
2989        })
2990    }
2991
2992    pub fn handle_stream(
2993        &mut self,
2994        model_telemetry_id: String,
2995        model_provider_id: String,
2996        model_api_key: Option<String>,
2997        stream: impl 'static + Future<Output = Result<LanguageModelTextStream>>,
2998        cx: &mut Context<Self>,
2999    ) {
3000        let start_time = Instant::now();
3001        let snapshot = self.snapshot.clone();
3002        let selected_text = snapshot
3003            .text_for_range(self.range.start..self.range.end)
3004            .collect::<Rope>();
3005
3006        let selection_start = self.range.start.to_point(&snapshot);
3007
3008        // Start with the indentation of the first line in the selection
3009        let mut suggested_line_indent = snapshot
3010            .suggested_indents(selection_start.row..=selection_start.row, cx)
3011            .into_values()
3012            .next()
3013            .unwrap_or_else(|| snapshot.indent_size_for_line(MultiBufferRow(selection_start.row)));
3014
3015        // If the first line in the selection does not have indentation, check the following lines
3016        if suggested_line_indent.len == 0 && suggested_line_indent.kind == IndentKind::Space {
3017            for row in selection_start.row..=self.range.end.to_point(&snapshot).row {
3018                let line_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
3019                // Prefer tabs if a line in the selection uses tabs as indentation
3020                if line_indent.kind == IndentKind::Tab {
3021                    suggested_line_indent.kind = IndentKind::Tab;
3022                    break;
3023                }
3024            }
3025        }
3026
3027        let http_client = cx.http_client();
3028        let telemetry = self.telemetry.clone();
3029        let language_name = {
3030            let multibuffer = self.buffer.read(cx);
3031            let snapshot = multibuffer.snapshot(cx);
3032            let ranges = snapshot.range_to_buffer_ranges(self.range.clone());
3033            ranges
3034                .first()
3035                .and_then(|(buffer, _, _)| buffer.language())
3036                .map(|language| language.name())
3037        };
3038
3039        self.diff = Diff::default();
3040        self.status = CodegenStatus::Pending;
3041        let mut edit_start = self.range.start.to_offset(&snapshot);
3042        let completion = Arc::new(Mutex::new(String::new()));
3043        let completion_clone = completion.clone();
3044
3045        self.generation = cx.spawn(async move |codegen, cx| {
3046            let stream = stream.await;
3047            let message_id = stream
3048                .as_ref()
3049                .ok()
3050                .and_then(|stream| stream.message_id.clone());
3051            let generate = async {
3052                let (mut diff_tx, mut diff_rx) = mpsc::channel(1);
3053                let executor = cx.background_executor().clone();
3054                let message_id = message_id.clone();
3055                let line_based_stream_diff: Task<anyhow::Result<()>> =
3056                    cx.background_spawn(async move {
3057                        let mut response_latency = None;
3058                        let request_start = Instant::now();
3059                        let diff = async {
3060                            let chunks =
3061                                StripInvalidSpans::new(stream?.stream.map_err(|e| e.into()));
3062                            futures::pin_mut!(chunks);
3063                            let mut diff = StreamingDiff::new(selected_text.to_string());
3064                            let mut line_diff = LineDiff::default();
3065
3066                            let mut new_text = String::new();
3067                            let mut base_indent = None;
3068                            let mut line_indent = None;
3069                            let mut first_line = true;
3070
3071                            while let Some(chunk) = chunks.next().await {
3072                                if response_latency.is_none() {
3073                                    response_latency = Some(request_start.elapsed());
3074                                }
3075                                let chunk = chunk?;
3076                                completion_clone.lock().push_str(&chunk);
3077
3078                                let mut lines = chunk.split('\n').peekable();
3079                                while let Some(line) = lines.next() {
3080                                    new_text.push_str(line);
3081                                    if line_indent.is_none() {
3082                                        if let Some(non_whitespace_ch_ix) =
3083                                            new_text.find(|ch: char| !ch.is_whitespace())
3084                                        {
3085                                            line_indent = Some(non_whitespace_ch_ix);
3086                                            base_indent = base_indent.or(line_indent);
3087
3088                                            let line_indent = line_indent.unwrap();
3089                                            let base_indent = base_indent.unwrap();
3090                                            let indent_delta =
3091                                                line_indent as i32 - base_indent as i32;
3092                                            let mut corrected_indent_len = cmp::max(
3093                                                0,
3094                                                suggested_line_indent.len as i32 + indent_delta,
3095                                            )
3096                                                as usize;
3097                                            if first_line {
3098                                                corrected_indent_len = corrected_indent_len
3099                                                    .saturating_sub(
3100                                                        selection_start.column as usize,
3101                                                    );
3102                                            }
3103
3104                                            let indent_char = suggested_line_indent.char();
3105                                            let mut indent_buffer = [0; 4];
3106                                            let indent_str =
3107                                                indent_char.encode_utf8(&mut indent_buffer);
3108                                            new_text.replace_range(
3109                                                ..line_indent,
3110                                                &indent_str.repeat(corrected_indent_len),
3111                                            );
3112                                        }
3113                                    }
3114
3115                                    if line_indent.is_some() {
3116                                        let char_ops = diff.push_new(&new_text);
3117                                        line_diff.push_char_operations(&char_ops, &selected_text);
3118                                        diff_tx
3119                                            .send((char_ops, line_diff.line_operations()))
3120                                            .await?;
3121                                        new_text.clear();
3122                                    }
3123
3124                                    if lines.peek().is_some() {
3125                                        let char_ops = diff.push_new("\n");
3126                                        line_diff.push_char_operations(&char_ops, &selected_text);
3127                                        diff_tx
3128                                            .send((char_ops, line_diff.line_operations()))
3129                                            .await?;
3130                                        if line_indent.is_none() {
3131                                            // Don't write out the leading indentation in empty lines on the next line
3132                                            // This is the case where the above if statement didn't clear the buffer
3133                                            new_text.clear();
3134                                        }
3135                                        line_indent = None;
3136                                        first_line = false;
3137                                    }
3138                                }
3139                            }
3140
3141                            let mut char_ops = diff.push_new(&new_text);
3142                            char_ops.extend(diff.finish());
3143                            line_diff.push_char_operations(&char_ops, &selected_text);
3144                            line_diff.finish(&selected_text);
3145                            diff_tx
3146                                .send((char_ops, line_diff.line_operations()))
3147                                .await?;
3148
3149                            anyhow::Ok(())
3150                        };
3151
3152                        let result = diff.await;
3153
3154                        let error_message = result.as_ref().err().map(|error| error.to_string());
3155                        report_assistant_event(
3156                            AssistantEventData {
3157                                conversation_id: None,
3158                                message_id,
3159                                kind: AssistantKind::Inline,
3160                                phase: AssistantPhase::Response,
3161                                model: model_telemetry_id,
3162                                model_provider: model_provider_id.to_string(),
3163                                response_latency,
3164                                error_message,
3165                                language_name: language_name.map(|name| name.to_proto()),
3166                            },
3167                            telemetry,
3168                            http_client,
3169                            model_api_key,
3170                            &executor,
3171                        );
3172
3173                        result?;
3174                        Ok(())
3175                    });
3176
3177                while let Some((char_ops, line_ops)) = diff_rx.next().await {
3178                    codegen.update(cx, |codegen, cx| {
3179                        codegen.last_equal_ranges.clear();
3180
3181                        let edits = char_ops
3182                            .into_iter()
3183                            .filter_map(|operation| match operation {
3184                                CharOperation::Insert { text } => {
3185                                    let edit_start = snapshot.anchor_after(edit_start);
3186                                    Some((edit_start..edit_start, text))
3187                                }
3188                                CharOperation::Delete { bytes } => {
3189                                    let edit_end = edit_start + bytes;
3190                                    let edit_range = snapshot.anchor_after(edit_start)
3191                                        ..snapshot.anchor_before(edit_end);
3192                                    edit_start = edit_end;
3193                                    Some((edit_range, String::new()))
3194                                }
3195                                CharOperation::Keep { bytes } => {
3196                                    let edit_end = edit_start + bytes;
3197                                    let edit_range = snapshot.anchor_after(edit_start)
3198                                        ..snapshot.anchor_before(edit_end);
3199                                    edit_start = edit_end;
3200                                    codegen.last_equal_ranges.push(edit_range);
3201                                    None
3202                                }
3203                            })
3204                            .collect::<Vec<_>>();
3205
3206                        if codegen.active {
3207                            codegen.apply_edits(edits.iter().cloned(), cx);
3208                            codegen.reapply_line_based_diff(line_ops.iter().cloned(), cx);
3209                        }
3210                        codegen.edits.extend(edits);
3211                        codegen.line_operations = line_ops;
3212                        codegen.edit_position = Some(snapshot.anchor_after(edit_start));
3213
3214                        cx.notify();
3215                    })?;
3216                }
3217
3218                // Streaming stopped and we have the new text in the buffer, and a line-based diff applied for the whole new buffer.
3219                // That diff is not what a regular diff is and might look unexpected, ergo apply a regular diff.
3220                // It's fine to apply even if the rest of the line diffing fails, as no more hunks are coming through `diff_rx`.
3221                let batch_diff_task =
3222                    codegen.update(cx, |codegen, cx| codegen.reapply_batch_diff(cx))?;
3223                let (line_based_stream_diff, ()) = join!(line_based_stream_diff, batch_diff_task);
3224                line_based_stream_diff?;
3225
3226                anyhow::Ok(())
3227            };
3228
3229            let result = generate.await;
3230            let elapsed_time = start_time.elapsed().as_secs_f64();
3231
3232            codegen
3233                .update(cx, |this, cx| {
3234                    this.message_id = message_id;
3235                    this.last_equal_ranges.clear();
3236                    if let Err(error) = result {
3237                        this.status = CodegenStatus::Error(error);
3238                    } else {
3239                        this.status = CodegenStatus::Done;
3240                    }
3241                    this.elapsed_time = Some(elapsed_time);
3242                    this.completion = Some(completion.lock().clone());
3243                    cx.emit(CodegenEvent::Finished);
3244                    cx.notify();
3245                })
3246                .ok();
3247        });
3248        cx.notify();
3249    }
3250
3251    pub fn stop(&mut self, cx: &mut Context<Self>) {
3252        self.last_equal_ranges.clear();
3253        if self.diff.is_empty() {
3254            self.status = CodegenStatus::Idle;
3255        } else {
3256            self.status = CodegenStatus::Done;
3257        }
3258        self.generation = Task::ready(());
3259        cx.emit(CodegenEvent::Finished);
3260        cx.notify();
3261    }
3262
3263    pub fn undo(&mut self, cx: &mut Context<Self>) {
3264        self.buffer.update(cx, |buffer, cx| {
3265            if let Some(transaction_id) = self.transformation_transaction_id.take() {
3266                buffer.undo_transaction(transaction_id, cx);
3267                buffer.refresh_preview(cx);
3268            }
3269        });
3270    }
3271
3272    fn apply_edits(
3273        &mut self,
3274        edits: impl IntoIterator<Item = (Range<Anchor>, String)>,
3275        cx: &mut Context<CodegenAlternative>,
3276    ) {
3277        let transaction = self.buffer.update(cx, |buffer, cx| {
3278            // Avoid grouping assistant edits with user edits.
3279            buffer.finalize_last_transaction(cx);
3280            buffer.start_transaction(cx);
3281            buffer.edit(edits, None, cx);
3282            buffer.end_transaction(cx)
3283        });
3284
3285        if let Some(transaction) = transaction {
3286            if let Some(first_transaction) = self.transformation_transaction_id {
3287                // Group all assistant edits into the first transaction.
3288                self.buffer.update(cx, |buffer, cx| {
3289                    buffer.merge_transactions(transaction, first_transaction, cx)
3290                });
3291            } else {
3292                self.transformation_transaction_id = Some(transaction);
3293                self.buffer
3294                    .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
3295            }
3296        }
3297    }
3298
3299    fn reapply_line_based_diff(
3300        &mut self,
3301        line_operations: impl IntoIterator<Item = LineOperation>,
3302        cx: &mut Context<Self>,
3303    ) {
3304        let old_snapshot = self.snapshot.clone();
3305        let old_range = self.range.to_point(&old_snapshot);
3306        let new_snapshot = self.buffer.read(cx).snapshot(cx);
3307        let new_range = self.range.to_point(&new_snapshot);
3308
3309        let mut old_row = old_range.start.row;
3310        let mut new_row = new_range.start.row;
3311
3312        self.diff.deleted_row_ranges.clear();
3313        self.diff.inserted_row_ranges.clear();
3314        for operation in line_operations {
3315            match operation {
3316                LineOperation::Keep { lines } => {
3317                    old_row += lines;
3318                    new_row += lines;
3319                }
3320                LineOperation::Delete { lines } => {
3321                    let old_end_row = old_row + lines - 1;
3322                    let new_row = new_snapshot.anchor_before(Point::new(new_row, 0));
3323
3324                    if let Some((_, last_deleted_row_range)) =
3325                        self.diff.deleted_row_ranges.last_mut()
3326                    {
3327                        if *last_deleted_row_range.end() + 1 == old_row {
3328                            *last_deleted_row_range = *last_deleted_row_range.start()..=old_end_row;
3329                        } else {
3330                            self.diff
3331                                .deleted_row_ranges
3332                                .push((new_row, old_row..=old_end_row));
3333                        }
3334                    } else {
3335                        self.diff
3336                            .deleted_row_ranges
3337                            .push((new_row, old_row..=old_end_row));
3338                    }
3339
3340                    old_row += lines;
3341                }
3342                LineOperation::Insert { lines } => {
3343                    let new_end_row = new_row + lines - 1;
3344                    let start = new_snapshot.anchor_before(Point::new(new_row, 0));
3345                    let end = new_snapshot.anchor_before(Point::new(
3346                        new_end_row,
3347                        new_snapshot.line_len(MultiBufferRow(new_end_row)),
3348                    ));
3349                    self.diff.inserted_row_ranges.push(start..end);
3350                    new_row += lines;
3351                }
3352            }
3353
3354            cx.notify();
3355        }
3356    }
3357
3358    fn reapply_batch_diff(&mut self, cx: &mut Context<Self>) -> Task<()> {
3359        let old_snapshot = self.snapshot.clone();
3360        let old_range = self.range.to_point(&old_snapshot);
3361        let new_snapshot = self.buffer.read(cx).snapshot(cx);
3362        let new_range = self.range.to_point(&new_snapshot);
3363
3364        cx.spawn(async move |codegen, cx| {
3365            let (deleted_row_ranges, inserted_row_ranges) = cx
3366                .background_spawn(async move {
3367                    let old_text = old_snapshot
3368                        .text_for_range(
3369                            Point::new(old_range.start.row, 0)
3370                                ..Point::new(
3371                                    old_range.end.row,
3372                                    old_snapshot.line_len(MultiBufferRow(old_range.end.row)),
3373                                ),
3374                        )
3375                        .collect::<String>();
3376                    let new_text = new_snapshot
3377                        .text_for_range(
3378                            Point::new(new_range.start.row, 0)
3379                                ..Point::new(
3380                                    new_range.end.row,
3381                                    new_snapshot.line_len(MultiBufferRow(new_range.end.row)),
3382                                ),
3383                        )
3384                        .collect::<String>();
3385
3386                    let old_start_row = old_range.start.row;
3387                    let new_start_row = new_range.start.row;
3388                    let mut deleted_row_ranges: Vec<(Anchor, RangeInclusive<u32>)> = Vec::new();
3389                    let mut inserted_row_ranges = Vec::new();
3390                    for (old_rows, new_rows) in line_diff(&old_text, &new_text) {
3391                        let old_rows = old_start_row + old_rows.start..old_start_row + old_rows.end;
3392                        let new_rows = new_start_row + new_rows.start..new_start_row + new_rows.end;
3393                        if !old_rows.is_empty() {
3394                            deleted_row_ranges.push((
3395                                new_snapshot.anchor_before(Point::new(new_rows.start, 0)),
3396                                old_rows.start..=old_rows.end - 1,
3397                            ));
3398                        }
3399                        if !new_rows.is_empty() {
3400                            let start = new_snapshot.anchor_before(Point::new(new_rows.start, 0));
3401                            let new_end_row = new_rows.end - 1;
3402                            let end = new_snapshot.anchor_before(Point::new(
3403                                new_end_row,
3404                                new_snapshot.line_len(MultiBufferRow(new_end_row)),
3405                            ));
3406                            inserted_row_ranges.push(start..end);
3407                        }
3408                    }
3409                    (deleted_row_ranges, inserted_row_ranges)
3410                })
3411                .await;
3412
3413            codegen
3414                .update(cx, |codegen, cx| {
3415                    codegen.diff.deleted_row_ranges = deleted_row_ranges;
3416                    codegen.diff.inserted_row_ranges = inserted_row_ranges;
3417                    cx.notify();
3418                })
3419                .ok();
3420        })
3421    }
3422}
3423
3424struct StripInvalidSpans<T> {
3425    stream: T,
3426    stream_done: bool,
3427    buffer: String,
3428    first_line: bool,
3429    line_end: bool,
3430    starts_with_code_block: bool,
3431}
3432
3433impl<T> StripInvalidSpans<T>
3434where
3435    T: Stream<Item = Result<String>>,
3436{
3437    fn new(stream: T) -> Self {
3438        Self {
3439            stream,
3440            stream_done: false,
3441            buffer: String::new(),
3442            first_line: true,
3443            line_end: false,
3444            starts_with_code_block: false,
3445        }
3446    }
3447}
3448
3449impl<T> Stream for StripInvalidSpans<T>
3450where
3451    T: Stream<Item = Result<String>>,
3452{
3453    type Item = Result<String>;
3454
3455    fn poll_next(self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<Option<Self::Item>> {
3456        const CODE_BLOCK_DELIMITER: &str = "```";
3457        const CURSOR_SPAN: &str = "<|CURSOR|>";
3458
3459        let this = unsafe { self.get_unchecked_mut() };
3460        loop {
3461            if !this.stream_done {
3462                let mut stream = unsafe { Pin::new_unchecked(&mut this.stream) };
3463                match stream.as_mut().poll_next(cx) {
3464                    Poll::Ready(Some(Ok(chunk))) => {
3465                        this.buffer.push_str(&chunk);
3466                    }
3467                    Poll::Ready(Some(Err(error))) => return Poll::Ready(Some(Err(error))),
3468                    Poll::Ready(None) => {
3469                        this.stream_done = true;
3470                    }
3471                    Poll::Pending => return Poll::Pending,
3472                }
3473            }
3474
3475            let mut chunk = String::new();
3476            let mut consumed = 0;
3477            if !this.buffer.is_empty() {
3478                let mut lines = this.buffer.split('\n').enumerate().peekable();
3479                while let Some((line_ix, line)) = lines.next() {
3480                    if line_ix > 0 {
3481                        this.first_line = false;
3482                    }
3483
3484                    if this.first_line {
3485                        let trimmed_line = line.trim();
3486                        if lines.peek().is_some() {
3487                            if trimmed_line.starts_with(CODE_BLOCK_DELIMITER) {
3488                                consumed += line.len() + 1;
3489                                this.starts_with_code_block = true;
3490                                continue;
3491                            }
3492                        } else if trimmed_line.is_empty()
3493                            || prefixes(CODE_BLOCK_DELIMITER)
3494                                .any(|prefix| trimmed_line.starts_with(prefix))
3495                        {
3496                            break;
3497                        }
3498                    }
3499
3500                    let line_without_cursor = line.replace(CURSOR_SPAN, "");
3501                    if lines.peek().is_some() {
3502                        if this.line_end {
3503                            chunk.push('\n');
3504                        }
3505
3506                        chunk.push_str(&line_without_cursor);
3507                        this.line_end = true;
3508                        consumed += line.len() + 1;
3509                    } else if this.stream_done {
3510                        if !this.starts_with_code_block
3511                            || !line_without_cursor.trim().ends_with(CODE_BLOCK_DELIMITER)
3512                        {
3513                            if this.line_end {
3514                                chunk.push('\n');
3515                            }
3516
3517                            chunk.push_str(&line);
3518                        }
3519
3520                        consumed += line.len();
3521                    } else {
3522                        let trimmed_line = line.trim();
3523                        if trimmed_line.is_empty()
3524                            || prefixes(CURSOR_SPAN).any(|prefix| trimmed_line.ends_with(prefix))
3525                            || prefixes(CODE_BLOCK_DELIMITER)
3526                                .any(|prefix| trimmed_line.ends_with(prefix))
3527                        {
3528                            break;
3529                        } else {
3530                            if this.line_end {
3531                                chunk.push('\n');
3532                                this.line_end = false;
3533                            }
3534
3535                            chunk.push_str(&line_without_cursor);
3536                            consumed += line.len();
3537                        }
3538                    }
3539                }
3540            }
3541
3542            this.buffer = this.buffer.split_off(consumed);
3543            if !chunk.is_empty() {
3544                return Poll::Ready(Some(Ok(chunk)));
3545            } else if this.stream_done {
3546                return Poll::Ready(None);
3547            }
3548        }
3549    }
3550}
3551
3552struct AssistantCodeActionProvider {
3553    editor: WeakEntity<Editor>,
3554    workspace: WeakEntity<Workspace>,
3555}
3556
3557const ASSISTANT_CODE_ACTION_PROVIDER_ID: &str = "assistant";
3558
3559impl CodeActionProvider for AssistantCodeActionProvider {
3560    fn id(&self) -> Arc<str> {
3561        ASSISTANT_CODE_ACTION_PROVIDER_ID.into()
3562    }
3563
3564    fn code_actions(
3565        &self,
3566        buffer: &Entity<Buffer>,
3567        range: Range<text::Anchor>,
3568        _: &mut Window,
3569        cx: &mut App,
3570    ) -> Task<Result<Vec<CodeAction>>> {
3571        if !Assistant::enabled(cx) {
3572            return Task::ready(Ok(Vec::new()));
3573        }
3574
3575        let snapshot = buffer.read(cx).snapshot();
3576        let mut range = range.to_point(&snapshot);
3577
3578        // Expand the range to line boundaries.
3579        range.start.column = 0;
3580        range.end.column = snapshot.line_len(range.end.row);
3581
3582        let mut has_diagnostics = false;
3583        for diagnostic in snapshot.diagnostics_in_range::<_, Point>(range.clone(), false) {
3584            range.start = cmp::min(range.start, diagnostic.range.start);
3585            range.end = cmp::max(range.end, diagnostic.range.end);
3586            has_diagnostics = true;
3587        }
3588        if has_diagnostics {
3589            if let Some(symbols_containing_start) = snapshot.symbols_containing(range.start, None) {
3590                if let Some(symbol) = symbols_containing_start.last() {
3591                    range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
3592                    range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
3593                }
3594            }
3595
3596            if let Some(symbols_containing_end) = snapshot.symbols_containing(range.end, None) {
3597                if let Some(symbol) = symbols_containing_end.last() {
3598                    range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
3599                    range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
3600                }
3601            }
3602
3603            Task::ready(Ok(vec![CodeAction {
3604                server_id: language::LanguageServerId(0),
3605                range: snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end),
3606                lsp_action: LspAction::Action(Box::new(lsp::CodeAction {
3607                    title: "Fix with Assistant".into(),
3608                    ..Default::default()
3609                })),
3610                resolved: true,
3611            }]))
3612        } else {
3613            Task::ready(Ok(Vec::new()))
3614        }
3615    }
3616
3617    fn apply_code_action(
3618        &self,
3619        buffer: Entity<Buffer>,
3620        action: CodeAction,
3621        excerpt_id: ExcerptId,
3622        _push_to_history: bool,
3623        window: &mut Window,
3624        cx: &mut App,
3625    ) -> Task<Result<ProjectTransaction>> {
3626        let editor = self.editor.clone();
3627        let workspace = self.workspace.clone();
3628        window.spawn(cx, async move |cx| {
3629            let editor = editor.upgrade().context("editor was released")?;
3630            let range = editor
3631                .update(cx, |editor, cx| {
3632                    editor.buffer().update(cx, |multibuffer, cx| {
3633                        let buffer = buffer.read(cx);
3634                        let multibuffer_snapshot = multibuffer.read(cx);
3635
3636                        let old_context_range =
3637                            multibuffer_snapshot.context_range_for_excerpt(excerpt_id)?;
3638                        let mut new_context_range = old_context_range.clone();
3639                        if action
3640                            .range
3641                            .start
3642                            .cmp(&old_context_range.start, buffer)
3643                            .is_lt()
3644                        {
3645                            new_context_range.start = action.range.start;
3646                        }
3647                        if action.range.end.cmp(&old_context_range.end, buffer).is_gt() {
3648                            new_context_range.end = action.range.end;
3649                        }
3650                        drop(multibuffer_snapshot);
3651
3652                        if new_context_range != old_context_range {
3653                            multibuffer.resize_excerpt(excerpt_id, new_context_range, cx);
3654                        }
3655
3656                        let multibuffer_snapshot = multibuffer.read(cx);
3657                        Some(
3658                            multibuffer_snapshot
3659                                .anchor_in_excerpt(excerpt_id, action.range.start)?
3660                                ..multibuffer_snapshot
3661                                    .anchor_in_excerpt(excerpt_id, action.range.end)?,
3662                        )
3663                    })
3664                })?
3665                .context("invalid range")?;
3666            let assistant_panel = workspace.update(cx, |workspace, cx| {
3667                workspace
3668                    .panel::<AssistantPanel>(cx)
3669                    .context("assistant panel was released")
3670            })??;
3671
3672            cx.update_global(|assistant: &mut InlineAssistant, window, cx| {
3673                let assist_id = assistant.suggest_assist(
3674                    &editor,
3675                    range,
3676                    "Fix Diagnostics".into(),
3677                    None,
3678                    true,
3679                    Some(workspace),
3680                    Some(&assistant_panel),
3681                    window,
3682                    cx,
3683                );
3684                assistant.start_assist(assist_id, window, cx);
3685            })?;
3686
3687            Ok(ProjectTransaction::default())
3688        })
3689    }
3690}
3691
3692fn prefixes(text: &str) -> impl Iterator<Item = &str> {
3693    (0..text.len() - 1).map(|ix| &text[..ix + 1])
3694}
3695
3696fn merge_ranges(ranges: &mut Vec<Range<Anchor>>, buffer: &MultiBufferSnapshot) {
3697    ranges.sort_unstable_by(|a, b| {
3698        a.start
3699            .cmp(&b.start, buffer)
3700            .then_with(|| b.end.cmp(&a.end, buffer))
3701    });
3702
3703    let mut ix = 0;
3704    while ix + 1 < ranges.len() {
3705        let b = ranges[ix + 1].clone();
3706        let a = &mut ranges[ix];
3707        if a.end.cmp(&b.start, buffer).is_gt() {
3708            if a.end.cmp(&b.end, buffer).is_lt() {
3709                a.end = b.end;
3710            }
3711            ranges.remove(ix + 1);
3712        } else {
3713            ix += 1;
3714        }
3715    }
3716}
3717
3718#[cfg(test)]
3719mod tests {
3720    use super::*;
3721    use futures::stream::{self};
3722    use gpui::TestAppContext;
3723    use indoc::indoc;
3724    use language::{
3725        Buffer, Language, LanguageConfig, LanguageMatcher, Point, language_settings,
3726        tree_sitter_rust,
3727    };
3728    use language_model::{LanguageModelRegistry, TokenUsage};
3729    use rand::prelude::*;
3730    use serde::Serialize;
3731    use settings::SettingsStore;
3732    use std::{future, sync::Arc};
3733
3734    #[derive(Serialize)]
3735    pub struct DummyCompletionRequest {
3736        pub name: String,
3737    }
3738
3739    #[gpui::test(iterations = 10)]
3740    async fn test_transform_autoindent(cx: &mut TestAppContext, mut rng: StdRng) {
3741        cx.set_global(cx.update(SettingsStore::test));
3742        cx.update(language_model::LanguageModelRegistry::test);
3743        cx.update(language_settings::init);
3744
3745        let text = indoc! {"
3746            fn main() {
3747                let x = 0;
3748                for _ in 0..10 {
3749                    x += 1;
3750                }
3751            }
3752        "};
3753        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
3754        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
3755        let range = buffer.read_with(cx, |buffer, cx| {
3756            let snapshot = buffer.snapshot(cx);
3757            snapshot.anchor_before(Point::new(1, 0))..snapshot.anchor_after(Point::new(4, 5))
3758        });
3759        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3760        let codegen = cx.new(|cx| {
3761            CodegenAlternative::new(
3762                buffer.clone(),
3763                range.clone(),
3764                true,
3765                None,
3766                prompt_builder,
3767                cx,
3768            )
3769        });
3770
3771        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
3772
3773        let mut new_text = concat!(
3774            "       let mut x = 0;\n",
3775            "       while x < 10 {\n",
3776            "           x += 1;\n",
3777            "       }",
3778        );
3779        while !new_text.is_empty() {
3780            let max_len = cmp::min(new_text.len(), 10);
3781            let len = rng.gen_range(1..=max_len);
3782            let (chunk, suffix) = new_text.split_at(len);
3783            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
3784            new_text = suffix;
3785            cx.background_executor.run_until_parked();
3786        }
3787        drop(chunks_tx);
3788        cx.background_executor.run_until_parked();
3789
3790        assert_eq!(
3791            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3792            indoc! {"
3793                fn main() {
3794                    let mut x = 0;
3795                    while x < 10 {
3796                        x += 1;
3797                    }
3798                }
3799            "}
3800        );
3801    }
3802
3803    #[gpui::test(iterations = 10)]
3804    async fn test_autoindent_when_generating_past_indentation(
3805        cx: &mut TestAppContext,
3806        mut rng: StdRng,
3807    ) {
3808        cx.set_global(cx.update(SettingsStore::test));
3809        cx.update(language_settings::init);
3810
3811        let text = indoc! {"
3812            fn main() {
3813                le
3814            }
3815        "};
3816        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
3817        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
3818        let range = buffer.read_with(cx, |buffer, cx| {
3819            let snapshot = buffer.snapshot(cx);
3820            snapshot.anchor_before(Point::new(1, 6))..snapshot.anchor_after(Point::new(1, 6))
3821        });
3822        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3823        let codegen = cx.new(|cx| {
3824            CodegenAlternative::new(
3825                buffer.clone(),
3826                range.clone(),
3827                true,
3828                None,
3829                prompt_builder,
3830                cx,
3831            )
3832        });
3833
3834        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
3835
3836        cx.background_executor.run_until_parked();
3837
3838        let mut new_text = concat!(
3839            "t mut x = 0;\n",
3840            "while x < 10 {\n",
3841            "    x += 1;\n",
3842            "}", //
3843        );
3844        while !new_text.is_empty() {
3845            let max_len = cmp::min(new_text.len(), 10);
3846            let len = rng.gen_range(1..=max_len);
3847            let (chunk, suffix) = new_text.split_at(len);
3848            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
3849            new_text = suffix;
3850            cx.background_executor.run_until_parked();
3851        }
3852        drop(chunks_tx);
3853        cx.background_executor.run_until_parked();
3854
3855        assert_eq!(
3856            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3857            indoc! {"
3858                fn main() {
3859                    let mut x = 0;
3860                    while x < 10 {
3861                        x += 1;
3862                    }
3863                }
3864            "}
3865        );
3866    }
3867
3868    #[gpui::test(iterations = 10)]
3869    async fn test_autoindent_when_generating_before_indentation(
3870        cx: &mut TestAppContext,
3871        mut rng: StdRng,
3872    ) {
3873        cx.update(LanguageModelRegistry::test);
3874        cx.set_global(cx.update(SettingsStore::test));
3875        cx.update(language_settings::init);
3876
3877        let text = concat!(
3878            "fn main() {\n",
3879            "  \n",
3880            "}\n" //
3881        );
3882        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
3883        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
3884        let range = buffer.read_with(cx, |buffer, cx| {
3885            let snapshot = buffer.snapshot(cx);
3886            snapshot.anchor_before(Point::new(1, 2))..snapshot.anchor_after(Point::new(1, 2))
3887        });
3888        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3889        let codegen = cx.new(|cx| {
3890            CodegenAlternative::new(
3891                buffer.clone(),
3892                range.clone(),
3893                true,
3894                None,
3895                prompt_builder,
3896                cx,
3897            )
3898        });
3899
3900        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
3901
3902        cx.background_executor.run_until_parked();
3903
3904        let mut new_text = concat!(
3905            "let mut x = 0;\n",
3906            "while x < 10 {\n",
3907            "    x += 1;\n",
3908            "}", //
3909        );
3910        while !new_text.is_empty() {
3911            let max_len = cmp::min(new_text.len(), 10);
3912            let len = rng.gen_range(1..=max_len);
3913            let (chunk, suffix) = new_text.split_at(len);
3914            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
3915            new_text = suffix;
3916            cx.background_executor.run_until_parked();
3917        }
3918        drop(chunks_tx);
3919        cx.background_executor.run_until_parked();
3920
3921        assert_eq!(
3922            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3923            indoc! {"
3924                fn main() {
3925                    let mut x = 0;
3926                    while x < 10 {
3927                        x += 1;
3928                    }
3929                }
3930            "}
3931        );
3932    }
3933
3934    #[gpui::test(iterations = 10)]
3935    async fn test_autoindent_respects_tabs_in_selection(cx: &mut TestAppContext) {
3936        cx.update(LanguageModelRegistry::test);
3937        cx.set_global(cx.update(SettingsStore::test));
3938        cx.update(language_settings::init);
3939
3940        let text = indoc! {"
3941            func main() {
3942            \tx := 0
3943            \tfor i := 0; i < 10; i++ {
3944            \t\tx++
3945            \t}
3946            }
3947        "};
3948        let buffer = cx.new(|cx| Buffer::local(text, cx));
3949        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
3950        let range = buffer.read_with(cx, |buffer, cx| {
3951            let snapshot = buffer.snapshot(cx);
3952            snapshot.anchor_before(Point::new(0, 0))..snapshot.anchor_after(Point::new(4, 2))
3953        });
3954        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3955        let codegen = cx.new(|cx| {
3956            CodegenAlternative::new(
3957                buffer.clone(),
3958                range.clone(),
3959                true,
3960                None,
3961                prompt_builder,
3962                cx,
3963            )
3964        });
3965
3966        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
3967        let new_text = concat!(
3968            "func main() {\n",
3969            "\tx := 0\n",
3970            "\tfor x < 10 {\n",
3971            "\t\tx++\n",
3972            "\t}", //
3973        );
3974        chunks_tx.unbounded_send(new_text.to_string()).unwrap();
3975        drop(chunks_tx);
3976        cx.background_executor.run_until_parked();
3977
3978        assert_eq!(
3979            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3980            indoc! {"
3981                func main() {
3982                \tx := 0
3983                \tfor x < 10 {
3984                \t\tx++
3985                \t}
3986                }
3987            "}
3988        );
3989    }
3990
3991    #[gpui::test]
3992    async fn test_inactive_codegen_alternative(cx: &mut TestAppContext) {
3993        cx.update(LanguageModelRegistry::test);
3994        cx.set_global(cx.update(SettingsStore::test));
3995        cx.update(language_settings::init);
3996
3997        let text = indoc! {"
3998            fn main() {
3999                let x = 0;
4000            }
4001        "};
4002        let buffer = cx.new(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
4003        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
4004        let range = buffer.read_with(cx, |buffer, cx| {
4005            let snapshot = buffer.snapshot(cx);
4006            snapshot.anchor_before(Point::new(1, 0))..snapshot.anchor_after(Point::new(1, 14))
4007        });
4008        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
4009        let codegen = cx.new(|cx| {
4010            CodegenAlternative::new(
4011                buffer.clone(),
4012                range.clone(),
4013                false,
4014                None,
4015                prompt_builder,
4016                cx,
4017            )
4018        });
4019
4020        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
4021        chunks_tx
4022            .unbounded_send("let mut x = 0;\nx += 1;".to_string())
4023            .unwrap();
4024        drop(chunks_tx);
4025        cx.run_until_parked();
4026
4027        // The codegen is inactive, so the buffer doesn't get modified.
4028        assert_eq!(
4029            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
4030            text
4031        );
4032
4033        // Activating the codegen applies the changes.
4034        codegen.update(cx, |codegen, cx| codegen.set_active(true, cx));
4035        assert_eq!(
4036            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
4037            indoc! {"
4038                fn main() {
4039                    let mut x = 0;
4040                    x += 1;
4041                }
4042            "}
4043        );
4044
4045        // Deactivating the codegen undoes the changes.
4046        codegen.update(cx, |codegen, cx| codegen.set_active(false, cx));
4047        cx.run_until_parked();
4048        assert_eq!(
4049            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
4050            text
4051        );
4052    }
4053
4054    #[gpui::test]
4055    async fn test_strip_invalid_spans_from_codeblock() {
4056        assert_chunks("Lorem ipsum dolor", "Lorem ipsum dolor").await;
4057        assert_chunks("```\nLorem ipsum dolor", "Lorem ipsum dolor").await;
4058        assert_chunks("```\nLorem ipsum dolor\n```", "Lorem ipsum dolor").await;
4059        assert_chunks(
4060            "```html\n```js\nLorem ipsum dolor\n```\n```",
4061            "```js\nLorem ipsum dolor\n```",
4062        )
4063        .await;
4064        assert_chunks("``\nLorem ipsum dolor\n```", "``\nLorem ipsum dolor\n```").await;
4065        assert_chunks("Lorem<|CURSOR|> ipsum", "Lorem ipsum").await;
4066        assert_chunks("Lorem ipsum", "Lorem ipsum").await;
4067        assert_chunks("```\n<|CURSOR|>Lorem ipsum\n```", "Lorem ipsum").await;
4068
4069        async fn assert_chunks(text: &str, expected_text: &str) {
4070            for chunk_size in 1..=text.len() {
4071                let actual_text = StripInvalidSpans::new(chunks(text, chunk_size))
4072                    .map(|chunk| chunk.unwrap())
4073                    .collect::<String>()
4074                    .await;
4075                assert_eq!(
4076                    actual_text, expected_text,
4077                    "failed to strip invalid spans, chunk size: {}",
4078                    chunk_size
4079                );
4080            }
4081        }
4082
4083        fn chunks(text: &str, size: usize) -> impl Stream<Item = Result<String>> {
4084            stream::iter(
4085                text.chars()
4086                    .collect::<Vec<_>>()
4087                    .chunks(size)
4088                    .map(|chunk| Ok(chunk.iter().collect::<String>()))
4089                    .collect::<Vec<_>>(),
4090            )
4091        }
4092    }
4093
4094    fn simulate_response_stream(
4095        codegen: Entity<CodegenAlternative>,
4096        cx: &mut TestAppContext,
4097    ) -> mpsc::UnboundedSender<String> {
4098        let (chunks_tx, chunks_rx) = mpsc::unbounded();
4099        codegen.update(cx, |codegen, cx| {
4100            codegen.handle_stream(
4101                String::new(),
4102                String::new(),
4103                None,
4104                future::ready(Ok(LanguageModelTextStream {
4105                    message_id: None,
4106                    stream: chunks_rx.map(Ok).boxed(),
4107                    last_token_usage: Arc::new(Mutex::new(TokenUsage::default())),
4108                })),
4109                cx,
4110            );
4111        });
4112        chunks_tx
4113    }
4114
4115    fn rust_lang() -> Language {
4116        Language::new(
4117            LanguageConfig {
4118                name: "Rust".into(),
4119                matcher: LanguageMatcher {
4120                    path_suffixes: vec!["rs".to_string()],
4121                    ..Default::default()
4122                },
4123                ..Default::default()
4124            },
4125            Some(tree_sitter_rust::LANGUAGE.into()),
4126        )
4127        .with_indents_query(
4128            r#"
4129            (call_expression) @indent
4130            (field_expression) @indent
4131            (_ "(" ")" @end) @indent
4132            (_ "{" "}" @end) @indent
4133            "#,
4134        )
4135        .unwrap()
4136    }
4137}