inline_assistant.rs

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