inline_assistant.rs

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