inline_assistant.rs

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