inline_assistant.rs

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