inline_assistant.rs

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