inline_assistant.rs

   1use crate::{
   2    assistant_settings::AssistantSettings, humanize_token_count, prompts::PromptBuilder,
   3    AssistantPanel, AssistantPanelEvent, CharOperation, CycleNextInlineAssist,
   4    CyclePreviousInlineAssist, LineDiff, LineOperation, ModelSelector, 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, EventEmitter, FocusHandle,
  28    FocusableView, FontWeight, Global, HighlightStyle, Model, ModelContext, Subscription, Task,
  29    TextStyle, UpdateGlobal, View, ViewContext, WeakView, WindowContext,
  30};
  31use language::{Buffer, IndentKind, Point, Selection, TransactionId};
  32use language_model::{
  33    logging::report_assistant_event, LanguageModel, LanguageModelRegistry, LanguageModelRequest,
  34    LanguageModelRequestMessage, LanguageModelTextStream, Role,
  35};
  36use multi_buffer::MultiBufferRow;
  37use parking_lot::Mutex;
  38use project::{CodeAction, ProjectTransaction};
  39use rope::Rope;
  40use settings::{Settings, SettingsStore};
  41use smol::future::FutureExt;
  42use std::{
  43    cmp,
  44    future::{self, Future},
  45    iter, mem,
  46    ops::{Range, RangeInclusive},
  47    pin::Pin,
  48    sync::Arc,
  49    task::{self, Poll},
  50    time::{Duration, Instant},
  51};
  52use telemetry_events::{AssistantEvent, AssistantKind, AssistantPhase};
  53use terminal_view::terminal_panel::TerminalPanel;
  54use text::{OffsetRangeExt, ToPoint as _};
  55use theme::ThemeSettings;
  56use ui::{
  57    prelude::*, text_for_action, CheckboxWithLabel, IconButtonShape, KeyBinding, Popover, Tooltip,
  58};
  59use util::{RangeExt, ResultExt};
  60use workspace::{notifications::NotificationId, ItemHandle, Toast, Workspace};
  61
  62pub fn init(
  63    fs: Arc<dyn Fs>,
  64    prompt_builder: Arc<PromptBuilder>,
  65    telemetry: Arc<Telemetry>,
  66    cx: &mut AppContext,
  67) {
  68    cx.set_global(InlineAssistant::new(fs, prompt_builder, telemetry));
  69    cx.observe_new_views(|_, cx| {
  70        let workspace = cx.view().clone();
  71        InlineAssistant::update_global(cx, |inline_assistant, cx| {
  72            inline_assistant.register_workspace(&workspace, cx)
  73        })
  74    })
  75    .detach();
  76}
  77
  78const PROMPT_HISTORY_MAX_LEN: usize = 20;
  79
  80pub struct InlineAssistant {
  81    next_assist_id: InlineAssistId,
  82    next_assist_group_id: InlineAssistGroupId,
  83    assists: HashMap<InlineAssistId, InlineAssist>,
  84    assists_by_editor: HashMap<WeakView<Editor>, EditorInlineAssists>,
  85    assist_groups: HashMap<InlineAssistGroupId, InlineAssistGroup>,
  86    confirmed_assists: HashMap<InlineAssistId, Model<CodegenAlternative>>,
  87    prompt_history: VecDeque<String>,
  88    prompt_builder: Arc<PromptBuilder>,
  89    telemetry: Option<Arc<Telemetry>>,
  90    fs: Arc<dyn Fs>,
  91}
  92
  93impl Global for InlineAssistant {}
  94
  95impl InlineAssistant {
  96    pub fn new(
  97        fs: Arc<dyn Fs>,
  98        prompt_builder: Arc<PromptBuilder>,
  99        telemetry: Arc<Telemetry>,
 100    ) -> Self {
 101        Self {
 102            next_assist_id: InlineAssistId::default(),
 103            next_assist_group_id: InlineAssistGroupId::default(),
 104            assists: HashMap::default(),
 105            assists_by_editor: HashMap::default(),
 106            assist_groups: HashMap::default(),
 107            confirmed_assists: HashMap::default(),
 108            prompt_history: VecDeque::default(),
 109            prompt_builder,
 110            telemetry: Some(telemetry),
 111            fs,
 112        }
 113    }
 114
 115    pub fn register_workspace(&mut self, workspace: &View<Workspace>, cx: &mut WindowContext) {
 116        cx.subscribe(workspace, |workspace, event, cx| {
 117            Self::update_global(cx, |this, cx| {
 118                this.handle_workspace_event(workspace, event, cx)
 119            });
 120        })
 121        .detach();
 122
 123        let workspace = workspace.downgrade();
 124        cx.observe_global::<SettingsStore>(move |cx| {
 125            let Some(workspace) = workspace.upgrade() else {
 126                return;
 127            };
 128            let Some(terminal_panel) = workspace.read(cx).panel::<TerminalPanel>(cx) else {
 129                return;
 130            };
 131            let enabled = AssistantSettings::get_global(cx).enabled;
 132            terminal_panel.update(cx, |terminal_panel, cx| {
 133                terminal_panel.asssistant_enabled(enabled, cx)
 134            });
 135        })
 136        .detach();
 137    }
 138
 139    fn handle_workspace_event(
 140        &mut self,
 141        workspace: View<Workspace>,
 142        event: &workspace::Event,
 143        cx: &mut WindowContext,
 144    ) {
 145        match event {
 146            workspace::Event::UserSavedItem { item, .. } => {
 147                // When the user manually saves an editor, automatically accepts all finished transformations.
 148                if let Some(editor) = item.upgrade().and_then(|item| item.act_as::<Editor>(cx)) {
 149                    if let Some(editor_assists) = self.assists_by_editor.get(&editor.downgrade()) {
 150                        for assist_id in editor_assists.assist_ids.clone() {
 151                            let assist = &self.assists[&assist_id];
 152                            if let CodegenStatus::Done = assist.codegen.read(cx).status(cx) {
 153                                self.finish_assist(assist_id, false, cx)
 154                            }
 155                        }
 156                    }
 157                }
 158            }
 159            workspace::Event::ItemAdded { item } => {
 160                self.register_workspace_item(&workspace, item.as_ref(), cx);
 161            }
 162            _ => (),
 163        }
 164    }
 165
 166    fn register_workspace_item(
 167        &mut self,
 168        workspace: &View<Workspace>,
 169        item: &dyn ItemHandle,
 170        cx: &mut WindowContext,
 171    ) {
 172        if let Some(editor) = item.act_as::<Editor>(cx) {
 173            editor.update(cx, |editor, cx| {
 174                editor.push_code_action_provider(
 175                    Arc::new(AssistantCodeActionProvider {
 176                        editor: cx.view().downgrade(),
 177                        workspace: workspace.downgrade(),
 178                    }),
 179                    cx,
 180                );
 181            });
 182        }
 183    }
 184
 185    pub fn assist(
 186        &mut self,
 187        editor: &View<Editor>,
 188        workspace: Option<WeakView<Workspace>>,
 189        assistant_panel: Option<&View<AssistantPanel>>,
 190        initial_prompt: Option<String>,
 191        cx: &mut WindowContext,
 192    ) {
 193        let (snapshot, initial_selections) = editor.update(cx, |editor, cx| {
 194            (
 195                editor.buffer().read(cx).snapshot(cx),
 196                editor.selections.all::<Point>(cx),
 197            )
 198        });
 199
 200        let mut selections = Vec::<Selection<Point>>::new();
 201        let mut newest_selection = None;
 202        for mut selection in initial_selections {
 203            if selection.end > selection.start {
 204                selection.start.column = 0;
 205                // If the selection ends at the start of the line, we don't want to include it.
 206                if selection.end.column == 0 {
 207                    selection.end.row -= 1;
 208                }
 209                selection.end.column = snapshot.line_len(MultiBufferRow(selection.end.row));
 210            }
 211
 212            if let Some(prev_selection) = selections.last_mut() {
 213                if selection.start <= prev_selection.end {
 214                    prev_selection.end = selection.end;
 215                    continue;
 216                }
 217            }
 218
 219            let latest_selection = newest_selection.get_or_insert_with(|| selection.clone());
 220            if selection.id > latest_selection.id {
 221                *latest_selection = selection.clone();
 222            }
 223            selections.push(selection);
 224        }
 225        let newest_selection = newest_selection.unwrap();
 226
 227        let mut codegen_ranges = Vec::new();
 228        for (excerpt_id, buffer, buffer_range) in
 229            snapshot.excerpts_in_ranges(selections.iter().map(|selection| {
 230                snapshot.anchor_before(selection.start)..snapshot.anchor_after(selection.end)
 231            }))
 232        {
 233            let start = Anchor {
 234                buffer_id: Some(buffer.remote_id()),
 235                excerpt_id,
 236                text_anchor: buffer.anchor_before(buffer_range.start),
 237            };
 238            let end = Anchor {
 239                buffer_id: Some(buffer.remote_id()),
 240                excerpt_id,
 241                text_anchor: buffer.anchor_after(buffer_range.end),
 242            };
 243            codegen_ranges.push(start..end);
 244
 245            if let Some(model) = LanguageModelRegistry::read_global(cx).active_model() {
 246                if let Some(telemetry) = self.telemetry.as_ref() {
 247                    telemetry.report_assistant_event(AssistantEvent {
 248                        conversation_id: None,
 249                        kind: AssistantKind::Inline,
 250                        phase: AssistantPhase::Invoked,
 251                        message_id: None,
 252                        model: model.telemetry_id(),
 253                        model_provider: model.provider_id().to_string(),
 254                        response_latency: None,
 255                        error_message: None,
 256                        language_name: buffer.language().map(|language| language.name().to_proto()),
 257                    });
 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: Box::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                    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: Box::new(move |cx| {
1203                        div()
1204                            .bg(cx.theme().status().deleted_background)
1205                            .size_full()
1206                            .h(height as f32 * cx.line_height())
1207                            .pl(cx.gutter_dimensions.full_width())
1208                            .child(deleted_lines_editor.clone())
1209                            .into_any_element()
1210                    }),
1211                    priority: 0,
1212                });
1213            }
1214
1215            decorations.removed_line_block_ids = editor
1216                .insert_blocks(new_blocks, None, cx)
1217                .into_iter()
1218                .collect();
1219        })
1220    }
1221}
1222
1223struct EditorInlineAssists {
1224    assist_ids: Vec<InlineAssistId>,
1225    scroll_lock: Option<InlineAssistScrollLock>,
1226    highlight_updates: async_watch::Sender<()>,
1227    _update_highlights: Task<Result<()>>,
1228    _subscriptions: Vec<gpui::Subscription>,
1229}
1230
1231struct InlineAssistScrollLock {
1232    assist_id: InlineAssistId,
1233    distance_from_top: f32,
1234}
1235
1236impl EditorInlineAssists {
1237    #[allow(clippy::too_many_arguments)]
1238    fn new(editor: &View<Editor>, cx: &mut WindowContext) -> Self {
1239        let (highlight_updates_tx, mut highlight_updates_rx) = async_watch::channel(());
1240        Self {
1241            assist_ids: Vec::new(),
1242            scroll_lock: None,
1243            highlight_updates: highlight_updates_tx,
1244            _update_highlights: cx.spawn(|mut cx| {
1245                let editor = editor.downgrade();
1246                async move {
1247                    while let Ok(()) = highlight_updates_rx.changed().await {
1248                        let editor = editor.upgrade().context("editor was dropped")?;
1249                        cx.update_global(|assistant: &mut InlineAssistant, cx| {
1250                            assistant.update_editor_highlights(&editor, cx);
1251                        })?;
1252                    }
1253                    Ok(())
1254                }
1255            }),
1256            _subscriptions: vec![
1257                cx.observe_release(editor, {
1258                    let editor = editor.downgrade();
1259                    |_, cx| {
1260                        InlineAssistant::update_global(cx, |this, cx| {
1261                            this.handle_editor_release(editor, cx);
1262                        })
1263                    }
1264                }),
1265                cx.observe(editor, move |editor, cx| {
1266                    InlineAssistant::update_global(cx, |this, cx| {
1267                        this.handle_editor_change(editor, cx)
1268                    })
1269                }),
1270                cx.subscribe(editor, move |editor, event, cx| {
1271                    InlineAssistant::update_global(cx, |this, cx| {
1272                        this.handle_editor_event(editor, event, cx)
1273                    })
1274                }),
1275                editor.update(cx, |editor, cx| {
1276                    let editor_handle = cx.view().downgrade();
1277                    editor.register_action(
1278                        move |_: &editor::actions::Newline, cx: &mut WindowContext| {
1279                            InlineAssistant::update_global(cx, |this, cx| {
1280                                if let Some(editor) = editor_handle.upgrade() {
1281                                    this.handle_editor_newline(editor, cx)
1282                                }
1283                            })
1284                        },
1285                    )
1286                }),
1287                editor.update(cx, |editor, cx| {
1288                    let editor_handle = cx.view().downgrade();
1289                    editor.register_action(
1290                        move |_: &editor::actions::Cancel, cx: &mut WindowContext| {
1291                            InlineAssistant::update_global(cx, |this, cx| {
1292                                if let Some(editor) = editor_handle.upgrade() {
1293                                    this.handle_editor_cancel(editor, cx)
1294                                }
1295                            })
1296                        },
1297                    )
1298                }),
1299            ],
1300        }
1301    }
1302}
1303
1304struct InlineAssistGroup {
1305    assist_ids: Vec<InlineAssistId>,
1306    linked: bool,
1307    active_assist_id: Option<InlineAssistId>,
1308}
1309
1310impl InlineAssistGroup {
1311    fn new() -> Self {
1312        Self {
1313            assist_ids: Vec::new(),
1314            linked: true,
1315            active_assist_id: None,
1316        }
1317    }
1318}
1319
1320fn build_assist_editor_renderer(editor: &View<PromptEditor>) -> RenderBlock {
1321    let editor = editor.clone();
1322    Box::new(move |cx: &mut BlockContext| {
1323        *editor.read(cx).gutter_dimensions.lock() = *cx.gutter_dimensions;
1324        editor.clone().into_any_element()
1325    })
1326}
1327
1328#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
1329pub struct InlineAssistId(usize);
1330
1331impl InlineAssistId {
1332    fn post_inc(&mut self) -> InlineAssistId {
1333        let id = *self;
1334        self.0 += 1;
1335        id
1336    }
1337}
1338
1339#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
1340struct InlineAssistGroupId(usize);
1341
1342impl InlineAssistGroupId {
1343    fn post_inc(&mut self) -> InlineAssistGroupId {
1344        let id = *self;
1345        self.0 += 1;
1346        id
1347    }
1348}
1349
1350enum PromptEditorEvent {
1351    StartRequested,
1352    StopRequested,
1353    ConfirmRequested,
1354    CancelRequested,
1355    DismissRequested,
1356}
1357
1358struct PromptEditor {
1359    id: InlineAssistId,
1360    fs: Arc<dyn Fs>,
1361    editor: View<Editor>,
1362    edited_since_done: bool,
1363    gutter_dimensions: Arc<Mutex<GutterDimensions>>,
1364    prompt_history: VecDeque<String>,
1365    prompt_history_ix: Option<usize>,
1366    pending_prompt: String,
1367    codegen: Model<Codegen>,
1368    _codegen_subscription: Subscription,
1369    editor_subscriptions: Vec<Subscription>,
1370    pending_token_count: Task<Result<()>>,
1371    token_counts: Option<TokenCounts>,
1372    _token_count_subscriptions: Vec<Subscription>,
1373    workspace: Option<WeakView<Workspace>>,
1374    show_rate_limit_notice: bool,
1375}
1376
1377#[derive(Copy, Clone)]
1378pub struct TokenCounts {
1379    total: usize,
1380    assistant_panel: usize,
1381}
1382
1383impl EventEmitter<PromptEditorEvent> for PromptEditor {}
1384
1385impl Render for PromptEditor {
1386    fn render(&mut self, cx: &mut ViewContext<Self>) -> impl IntoElement {
1387        let gutter_dimensions = *self.gutter_dimensions.lock();
1388        let codegen = self.codegen.read(cx);
1389
1390        let mut buttons = Vec::new();
1391        if codegen.alternative_count(cx) > 1 {
1392            buttons.push(self.render_cycle_controls(cx));
1393        }
1394
1395        let status = codegen.status(cx);
1396        buttons.extend(match status {
1397            CodegenStatus::Idle => {
1398                vec![
1399                    IconButton::new("cancel", IconName::Close)
1400                        .icon_color(Color::Muted)
1401                        .shape(IconButtonShape::Square)
1402                        .tooltip(|cx| Tooltip::for_action("Cancel Assist", &menu::Cancel, cx))
1403                        .on_click(
1404                            cx.listener(|_, _, cx| cx.emit(PromptEditorEvent::CancelRequested)),
1405                        )
1406                        .into_any_element(),
1407                    IconButton::new("start", IconName::SparkleAlt)
1408                        .icon_color(Color::Muted)
1409                        .shape(IconButtonShape::Square)
1410                        .tooltip(|cx| Tooltip::for_action("Transform", &menu::Confirm, cx))
1411                        .on_click(
1412                            cx.listener(|_, _, cx| cx.emit(PromptEditorEvent::StartRequested)),
1413                        )
1414                        .into_any_element(),
1415                ]
1416            }
1417            CodegenStatus::Pending => {
1418                vec![
1419                    IconButton::new("cancel", IconName::Close)
1420                        .icon_color(Color::Muted)
1421                        .shape(IconButtonShape::Square)
1422                        .tooltip(|cx| Tooltip::text("Cancel Assist", cx))
1423                        .on_click(
1424                            cx.listener(|_, _, cx| cx.emit(PromptEditorEvent::CancelRequested)),
1425                        )
1426                        .into_any_element(),
1427                    IconButton::new("stop", IconName::Stop)
1428                        .icon_color(Color::Error)
1429                        .shape(IconButtonShape::Square)
1430                        .tooltip(|cx| {
1431                            Tooltip::with_meta(
1432                                "Interrupt Transformation",
1433                                Some(&menu::Cancel),
1434                                "Changes won't be discarded",
1435                                cx,
1436                            )
1437                        })
1438                        .on_click(cx.listener(|_, _, cx| cx.emit(PromptEditorEvent::StopRequested)))
1439                        .into_any_element(),
1440                ]
1441            }
1442            CodegenStatus::Error(_) | CodegenStatus::Done => {
1443                vec![
1444                    IconButton::new("cancel", IconName::Close)
1445                        .icon_color(Color::Muted)
1446                        .shape(IconButtonShape::Square)
1447                        .tooltip(|cx| Tooltip::for_action("Cancel Assist", &menu::Cancel, cx))
1448                        .on_click(
1449                            cx.listener(|_, _, cx| cx.emit(PromptEditorEvent::CancelRequested)),
1450                        )
1451                        .into_any_element(),
1452                    if self.edited_since_done || matches!(status, CodegenStatus::Error(_)) {
1453                        IconButton::new("restart", IconName::RotateCw)
1454                            .icon_color(Color::Info)
1455                            .shape(IconButtonShape::Square)
1456                            .tooltip(|cx| {
1457                                Tooltip::with_meta(
1458                                    "Restart Transformation",
1459                                    Some(&menu::Confirm),
1460                                    "Changes will be discarded",
1461                                    cx,
1462                                )
1463                            })
1464                            .on_click(cx.listener(|_, _, cx| {
1465                                cx.emit(PromptEditorEvent::StartRequested);
1466                            }))
1467                            .into_any_element()
1468                    } else {
1469                        IconButton::new("confirm", IconName::Check)
1470                            .icon_color(Color::Info)
1471                            .shape(IconButtonShape::Square)
1472                            .tooltip(|cx| Tooltip::for_action("Confirm Assist", &menu::Confirm, cx))
1473                            .on_click(cx.listener(|_, _, cx| {
1474                                cx.emit(PromptEditorEvent::ConfirmRequested);
1475                            }))
1476                            .into_any_element()
1477                    },
1478                ]
1479            }
1480        });
1481
1482        h_flex()
1483            .key_context("PromptEditor")
1484            .bg(cx.theme().colors().editor_background)
1485            .border_y_1()
1486            .border_color(cx.theme().status().info_border)
1487            .size_full()
1488            .py(cx.line_height() / 2.5)
1489            .on_action(cx.listener(Self::confirm))
1490            .on_action(cx.listener(Self::cancel))
1491            .on_action(cx.listener(Self::move_up))
1492            .on_action(cx.listener(Self::move_down))
1493            .capture_action(cx.listener(Self::cycle_prev))
1494            .capture_action(cx.listener(Self::cycle_next))
1495            .child(
1496                h_flex()
1497                    .w(gutter_dimensions.full_width() + (gutter_dimensions.margin / 2.0))
1498                    .justify_center()
1499                    .gap_2()
1500                    .child(
1501                        ModelSelector::new(
1502                            self.fs.clone(),
1503                            IconButton::new("context", IconName::SettingsAlt)
1504                                .shape(IconButtonShape::Square)
1505                                .icon_size(IconSize::Small)
1506                                .icon_color(Color::Muted)
1507                                .tooltip(move |cx| {
1508                                    Tooltip::with_meta(
1509                                        format!(
1510                                            "Using {}",
1511                                            LanguageModelRegistry::read_global(cx)
1512                                                .active_model()
1513                                                .map(|model| model.name().0)
1514                                                .unwrap_or_else(|| "No model selected".into()),
1515                                        ),
1516                                        None,
1517                                        "Change Model",
1518                                        cx,
1519                                    )
1520                                }),
1521                        )
1522                        .with_info_text(
1523                            "Inline edits use context\n\
1524                            from the currently selected\n\
1525                            assistant panel tab.",
1526                        ),
1527                    )
1528                    .map(|el| {
1529                        let CodegenStatus::Error(error) = self.codegen.read(cx).status(cx) else {
1530                            return el;
1531                        };
1532
1533                        let error_message = SharedString::from(error.to_string());
1534                        if error.error_code() == proto::ErrorCode::RateLimitExceeded
1535                            && cx.has_flag::<ZedPro>()
1536                        {
1537                            el.child(
1538                                v_flex()
1539                                    .child(
1540                                        IconButton::new("rate-limit-error", IconName::XCircle)
1541                                            .selected(self.show_rate_limit_notice)
1542                                            .shape(IconButtonShape::Square)
1543                                            .icon_size(IconSize::Small)
1544                                            .on_click(cx.listener(Self::toggle_rate_limit_notice)),
1545                                    )
1546                                    .children(self.show_rate_limit_notice.then(|| {
1547                                        deferred(
1548                                            anchored()
1549                                                .position_mode(gpui::AnchoredPositionMode::Local)
1550                                                .position(point(px(0.), px(24.)))
1551                                                .anchor(gpui::AnchorCorner::TopLeft)
1552                                                .child(self.render_rate_limit_notice(cx)),
1553                                        )
1554                                    })),
1555                            )
1556                        } else {
1557                            el.child(
1558                                div()
1559                                    .id("error")
1560                                    .tooltip(move |cx| Tooltip::text(error_message.clone(), cx))
1561                                    .child(
1562                                        Icon::new(IconName::XCircle)
1563                                            .size(IconSize::Small)
1564                                            .color(Color::Error),
1565                                    ),
1566                            )
1567                        }
1568                    }),
1569            )
1570            .child(div().flex_1().child(self.render_prompt_editor(cx)))
1571            .child(
1572                h_flex()
1573                    .gap_2()
1574                    .pr_6()
1575                    .children(self.render_token_count(cx))
1576                    .children(buttons),
1577            )
1578    }
1579}
1580
1581impl FocusableView for PromptEditor {
1582    fn focus_handle(&self, cx: &AppContext) -> FocusHandle {
1583        self.editor.focus_handle(cx)
1584    }
1585}
1586
1587impl PromptEditor {
1588    const MAX_LINES: u8 = 8;
1589
1590    #[allow(clippy::too_many_arguments)]
1591    fn new(
1592        id: InlineAssistId,
1593        gutter_dimensions: Arc<Mutex<GutterDimensions>>,
1594        prompt_history: VecDeque<String>,
1595        prompt_buffer: Model<MultiBuffer>,
1596        codegen: Model<Codegen>,
1597        parent_editor: &View<Editor>,
1598        assistant_panel: Option<&View<AssistantPanel>>,
1599        workspace: Option<WeakView<Workspace>>,
1600        fs: Arc<dyn Fs>,
1601        cx: &mut ViewContext<Self>,
1602    ) -> Self {
1603        let prompt_editor = cx.new_view(|cx| {
1604            let mut editor = Editor::new(
1605                EditorMode::AutoHeight {
1606                    max_lines: Self::MAX_LINES as usize,
1607                },
1608                prompt_buffer,
1609                None,
1610                false,
1611                cx,
1612            );
1613            editor.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
1614            // Since the prompt editors for all inline assistants are linked,
1615            // always show the cursor (even when it isn't focused) because
1616            // typing in one will make what you typed appear in all of them.
1617            editor.set_show_cursor_when_unfocused(true, cx);
1618            editor.set_placeholder_text(Self::placeholder_text(codegen.read(cx), cx), cx);
1619            editor
1620        });
1621
1622        let mut token_count_subscriptions = Vec::new();
1623        token_count_subscriptions
1624            .push(cx.subscribe(parent_editor, Self::handle_parent_editor_event));
1625        if let Some(assistant_panel) = assistant_panel {
1626            token_count_subscriptions
1627                .push(cx.subscribe(assistant_panel, Self::handle_assistant_panel_event));
1628        }
1629
1630        let mut this = Self {
1631            id,
1632            editor: prompt_editor,
1633            edited_since_done: false,
1634            gutter_dimensions,
1635            prompt_history,
1636            prompt_history_ix: None,
1637            pending_prompt: String::new(),
1638            _codegen_subscription: cx.observe(&codegen, Self::handle_codegen_changed),
1639            editor_subscriptions: Vec::new(),
1640            codegen,
1641            fs,
1642            pending_token_count: Task::ready(Ok(())),
1643            token_counts: None,
1644            _token_count_subscriptions: token_count_subscriptions,
1645            workspace,
1646            show_rate_limit_notice: false,
1647        };
1648        this.count_tokens(cx);
1649        this.subscribe_to_editor(cx);
1650        this
1651    }
1652
1653    fn subscribe_to_editor(&mut self, cx: &mut ViewContext<Self>) {
1654        self.editor_subscriptions.clear();
1655        self.editor_subscriptions
1656            .push(cx.subscribe(&self.editor, Self::handle_prompt_editor_events));
1657    }
1658
1659    fn set_show_cursor_when_unfocused(
1660        &mut self,
1661        show_cursor_when_unfocused: bool,
1662        cx: &mut ViewContext<Self>,
1663    ) {
1664        self.editor.update(cx, |editor, cx| {
1665            editor.set_show_cursor_when_unfocused(show_cursor_when_unfocused, cx)
1666        });
1667    }
1668
1669    fn unlink(&mut self, cx: &mut ViewContext<Self>) {
1670        let prompt = self.prompt(cx);
1671        let focus = self.editor.focus_handle(cx).contains_focused(cx);
1672        self.editor = cx.new_view(|cx| {
1673            let mut editor = Editor::auto_height(Self::MAX_LINES as usize, cx);
1674            editor.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
1675            editor.set_placeholder_text(Self::placeholder_text(self.codegen.read(cx), cx), cx);
1676            editor.set_placeholder_text("Add a prompt…", cx);
1677            editor.set_text(prompt, cx);
1678            if focus {
1679                editor.focus(cx);
1680            }
1681            editor
1682        });
1683        self.subscribe_to_editor(cx);
1684    }
1685
1686    fn placeholder_text(codegen: &Codegen, cx: &WindowContext) -> String {
1687        let context_keybinding = text_for_action(&crate::ToggleFocus, cx)
1688            .map(|keybinding| format!("{keybinding} for context"))
1689            .unwrap_or_default();
1690
1691        let action = if codegen.is_insertion {
1692            "Generate"
1693        } else {
1694            "Transform"
1695        };
1696
1697        format!("{action}{context_keybinding} • ↓↑ for history")
1698    }
1699
1700    fn prompt(&self, cx: &AppContext) -> String {
1701        self.editor.read(cx).text(cx)
1702    }
1703
1704    fn toggle_rate_limit_notice(&mut self, _: &ClickEvent, cx: &mut ViewContext<Self>) {
1705        self.show_rate_limit_notice = !self.show_rate_limit_notice;
1706        if self.show_rate_limit_notice {
1707            cx.focus_view(&self.editor);
1708        }
1709        cx.notify();
1710    }
1711
1712    fn handle_parent_editor_event(
1713        &mut self,
1714        _: View<Editor>,
1715        event: &EditorEvent,
1716        cx: &mut ViewContext<Self>,
1717    ) {
1718        if let EditorEvent::BufferEdited { .. } = event {
1719            self.count_tokens(cx);
1720        }
1721    }
1722
1723    fn handle_assistant_panel_event(
1724        &mut self,
1725        _: View<AssistantPanel>,
1726        event: &AssistantPanelEvent,
1727        cx: &mut ViewContext<Self>,
1728    ) {
1729        let AssistantPanelEvent::ContextEdited { .. } = event;
1730        self.count_tokens(cx);
1731    }
1732
1733    fn count_tokens(&mut self, cx: &mut ViewContext<Self>) {
1734        let assist_id = self.id;
1735        self.pending_token_count = cx.spawn(|this, mut cx| async move {
1736            cx.background_executor().timer(Duration::from_secs(1)).await;
1737            let token_count = cx
1738                .update_global(|inline_assistant: &mut InlineAssistant, cx| {
1739                    let assist = inline_assistant
1740                        .assists
1741                        .get(&assist_id)
1742                        .context("assist not found")?;
1743                    anyhow::Ok(assist.count_tokens(cx))
1744                })??
1745                .await?;
1746
1747            this.update(&mut cx, |this, cx| {
1748                this.token_counts = Some(token_count);
1749                cx.notify();
1750            })
1751        })
1752    }
1753
1754    fn handle_prompt_editor_events(
1755        &mut self,
1756        _: View<Editor>,
1757        event: &EditorEvent,
1758        cx: &mut ViewContext<Self>,
1759    ) {
1760        match event {
1761            EditorEvent::Edited { .. } => {
1762                let prompt = self.editor.read(cx).text(cx);
1763                if self
1764                    .prompt_history_ix
1765                    .map_or(true, |ix| self.prompt_history[ix] != prompt)
1766                {
1767                    self.prompt_history_ix.take();
1768                    self.pending_prompt = prompt;
1769                }
1770
1771                self.edited_since_done = true;
1772                cx.notify();
1773            }
1774            EditorEvent::BufferEdited => {
1775                self.count_tokens(cx);
1776            }
1777            EditorEvent::Blurred => {
1778                if self.show_rate_limit_notice {
1779                    self.show_rate_limit_notice = false;
1780                    cx.notify();
1781                }
1782            }
1783            _ => {}
1784        }
1785    }
1786
1787    fn handle_codegen_changed(&mut self, _: Model<Codegen>, cx: &mut ViewContext<Self>) {
1788        match self.codegen.read(cx).status(cx) {
1789            CodegenStatus::Idle => {
1790                self.editor
1791                    .update(cx, |editor, _| editor.set_read_only(false));
1792            }
1793            CodegenStatus::Pending => {
1794                self.editor
1795                    .update(cx, |editor, _| editor.set_read_only(true));
1796            }
1797            CodegenStatus::Done => {
1798                self.edited_since_done = false;
1799                self.editor
1800                    .update(cx, |editor, _| editor.set_read_only(false));
1801            }
1802            CodegenStatus::Error(error) => {
1803                if cx.has_flag::<ZedPro>()
1804                    && error.error_code() == proto::ErrorCode::RateLimitExceeded
1805                    && !dismissed_rate_limit_notice()
1806                {
1807                    self.show_rate_limit_notice = true;
1808                    cx.notify();
1809                }
1810
1811                self.edited_since_done = false;
1812                self.editor
1813                    .update(cx, |editor, _| editor.set_read_only(false));
1814            }
1815        }
1816    }
1817
1818    fn cancel(&mut self, _: &editor::actions::Cancel, cx: &mut ViewContext<Self>) {
1819        match self.codegen.read(cx).status(cx) {
1820            CodegenStatus::Idle | CodegenStatus::Done | CodegenStatus::Error(_) => {
1821                cx.emit(PromptEditorEvent::CancelRequested);
1822            }
1823            CodegenStatus::Pending => {
1824                cx.emit(PromptEditorEvent::StopRequested);
1825            }
1826        }
1827    }
1828
1829    fn confirm(&mut self, _: &menu::Confirm, cx: &mut ViewContext<Self>) {
1830        match self.codegen.read(cx).status(cx) {
1831            CodegenStatus::Idle => {
1832                cx.emit(PromptEditorEvent::StartRequested);
1833            }
1834            CodegenStatus::Pending => {
1835                cx.emit(PromptEditorEvent::DismissRequested);
1836            }
1837            CodegenStatus::Done => {
1838                if self.edited_since_done {
1839                    cx.emit(PromptEditorEvent::StartRequested);
1840                } else {
1841                    cx.emit(PromptEditorEvent::ConfirmRequested);
1842                }
1843            }
1844            CodegenStatus::Error(_) => {
1845                cx.emit(PromptEditorEvent::StartRequested);
1846            }
1847        }
1848    }
1849
1850    fn move_up(&mut self, _: &MoveUp, cx: &mut ViewContext<Self>) {
1851        if let Some(ix) = self.prompt_history_ix {
1852            if ix > 0 {
1853                self.prompt_history_ix = Some(ix - 1);
1854                let prompt = self.prompt_history[ix - 1].as_str();
1855                self.editor.update(cx, |editor, cx| {
1856                    editor.set_text(prompt, cx);
1857                    editor.move_to_beginning(&Default::default(), cx);
1858                });
1859            }
1860        } else if !self.prompt_history.is_empty() {
1861            self.prompt_history_ix = Some(self.prompt_history.len() - 1);
1862            let prompt = self.prompt_history[self.prompt_history.len() - 1].as_str();
1863            self.editor.update(cx, |editor, cx| {
1864                editor.set_text(prompt, cx);
1865                editor.move_to_beginning(&Default::default(), cx);
1866            });
1867        }
1868    }
1869
1870    fn move_down(&mut self, _: &MoveDown, cx: &mut ViewContext<Self>) {
1871        if let Some(ix) = self.prompt_history_ix {
1872            if ix < self.prompt_history.len() - 1 {
1873                self.prompt_history_ix = Some(ix + 1);
1874                let prompt = self.prompt_history[ix + 1].as_str();
1875                self.editor.update(cx, |editor, cx| {
1876                    editor.set_text(prompt, cx);
1877                    editor.move_to_end(&Default::default(), cx)
1878                });
1879            } else {
1880                self.prompt_history_ix = None;
1881                let prompt = self.pending_prompt.as_str();
1882                self.editor.update(cx, |editor, cx| {
1883                    editor.set_text(prompt, cx);
1884                    editor.move_to_end(&Default::default(), cx)
1885                });
1886            }
1887        }
1888    }
1889
1890    fn cycle_prev(&mut self, _: &CyclePreviousInlineAssist, cx: &mut ViewContext<Self>) {
1891        self.codegen
1892            .update(cx, |codegen, cx| codegen.cycle_prev(cx));
1893    }
1894
1895    fn cycle_next(&mut self, _: &CycleNextInlineAssist, cx: &mut ViewContext<Self>) {
1896        self.codegen
1897            .update(cx, |codegen, cx| codegen.cycle_next(cx));
1898    }
1899
1900    fn render_cycle_controls(&self, cx: &ViewContext<Self>) -> AnyElement {
1901        let codegen = self.codegen.read(cx);
1902        let disabled = matches!(codegen.status(cx), CodegenStatus::Idle);
1903
1904        let model_registry = LanguageModelRegistry::read_global(cx);
1905        let default_model = model_registry.active_model();
1906        let alternative_models = model_registry.inline_alternative_models();
1907
1908        let get_model_name = |index: usize| -> String {
1909            let name = |model: &Arc<dyn LanguageModel>| model.name().0.to_string();
1910
1911            match index {
1912                0 => default_model.as_ref().map_or_else(String::new, name),
1913                index if index <= alternative_models.len() => alternative_models
1914                    .get(index - 1)
1915                    .map_or_else(String::new, name),
1916                _ => String::new(),
1917            }
1918        };
1919
1920        let total_models = alternative_models.len() + 1;
1921
1922        if total_models <= 1 {
1923            return div().into_any_element();
1924        }
1925
1926        let current_index = codegen.active_alternative;
1927        let prev_index = (current_index + total_models - 1) % total_models;
1928        let next_index = (current_index + 1) % total_models;
1929
1930        let prev_model_name = get_model_name(prev_index);
1931        let next_model_name = get_model_name(next_index);
1932
1933        h_flex()
1934            .child(
1935                IconButton::new("previous", IconName::ChevronLeft)
1936                    .icon_color(Color::Muted)
1937                    .disabled(disabled || current_index == 0)
1938                    .shape(IconButtonShape::Square)
1939                    .tooltip({
1940                        let focus_handle = self.editor.focus_handle(cx);
1941                        move |cx| {
1942                            cx.new_view(|cx| {
1943                                let mut tooltip = Tooltip::new("Previous Alternative").key_binding(
1944                                    KeyBinding::for_action_in(
1945                                        &CyclePreviousInlineAssist,
1946                                        &focus_handle,
1947                                        cx,
1948                                    ),
1949                                );
1950                                if !disabled && current_index != 0 {
1951                                    tooltip = tooltip.meta(prev_model_name.clone());
1952                                }
1953                                tooltip
1954                            })
1955                            .into()
1956                        }
1957                    })
1958                    .on_click(cx.listener(|this, _, cx| {
1959                        this.codegen
1960                            .update(cx, |codegen, cx| codegen.cycle_prev(cx))
1961                    })),
1962            )
1963            .child(
1964                Label::new(format!(
1965                    "{}/{}",
1966                    codegen.active_alternative + 1,
1967                    codegen.alternative_count(cx)
1968                ))
1969                .size(LabelSize::Small)
1970                .color(if disabled {
1971                    Color::Disabled
1972                } else {
1973                    Color::Muted
1974                }),
1975            )
1976            .child(
1977                IconButton::new("next", IconName::ChevronRight)
1978                    .icon_color(Color::Muted)
1979                    .disabled(disabled || current_index == total_models - 1)
1980                    .shape(IconButtonShape::Square)
1981                    .tooltip({
1982                        let focus_handle = self.editor.focus_handle(cx);
1983                        move |cx| {
1984                            cx.new_view(|cx| {
1985                                let mut tooltip = Tooltip::new("Next Alternative").key_binding(
1986                                    KeyBinding::for_action_in(
1987                                        &CycleNextInlineAssist,
1988                                        &focus_handle,
1989                                        cx,
1990                                    ),
1991                                );
1992                                if !disabled && current_index != total_models - 1 {
1993                                    tooltip = tooltip.meta(next_model_name.clone());
1994                                }
1995                                tooltip
1996                            })
1997                            .into()
1998                        }
1999                    })
2000                    .on_click(cx.listener(|this, _, cx| {
2001                        this.codegen
2002                            .update(cx, |codegen, cx| codegen.cycle_next(cx))
2003                    })),
2004            )
2005            .into_any_element()
2006    }
2007
2008    fn render_token_count(&self, cx: &mut ViewContext<Self>) -> Option<impl IntoElement> {
2009        let model = LanguageModelRegistry::read_global(cx).active_model()?;
2010        let token_counts = self.token_counts?;
2011        let max_token_count = model.max_token_count();
2012
2013        let remaining_tokens = max_token_count as isize - token_counts.total as isize;
2014        let token_count_color = if remaining_tokens <= 0 {
2015            Color::Error
2016        } else if token_counts.total as f32 / max_token_count as f32 >= 0.8 {
2017            Color::Warning
2018        } else {
2019            Color::Muted
2020        };
2021
2022        let mut token_count = h_flex()
2023            .id("token_count")
2024            .gap_0p5()
2025            .child(
2026                Label::new(humanize_token_count(token_counts.total))
2027                    .size(LabelSize::Small)
2028                    .color(token_count_color),
2029            )
2030            .child(Label::new("/").size(LabelSize::Small).color(Color::Muted))
2031            .child(
2032                Label::new(humanize_token_count(max_token_count))
2033                    .size(LabelSize::Small)
2034                    .color(Color::Muted),
2035            );
2036        if let Some(workspace) = self.workspace.clone() {
2037            token_count = token_count
2038                .tooltip(move |cx| {
2039                    Tooltip::with_meta(
2040                        format!(
2041                            "Tokens Used ({} from the Assistant Panel)",
2042                            humanize_token_count(token_counts.assistant_panel)
2043                        ),
2044                        None,
2045                        "Click to open the Assistant Panel",
2046                        cx,
2047                    )
2048                })
2049                .cursor_pointer()
2050                .on_mouse_down(gpui::MouseButton::Left, |_, cx| cx.stop_propagation())
2051                .on_click(move |_, cx| {
2052                    cx.stop_propagation();
2053                    workspace
2054                        .update(cx, |workspace, cx| {
2055                            workspace.focus_panel::<AssistantPanel>(cx)
2056                        })
2057                        .ok();
2058                });
2059        } else {
2060            token_count = token_count
2061                .cursor_default()
2062                .tooltip(|cx| Tooltip::text("Tokens used", cx));
2063        }
2064
2065        Some(token_count)
2066    }
2067
2068    fn render_prompt_editor(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
2069        let settings = ThemeSettings::get_global(cx);
2070        let text_style = TextStyle {
2071            color: if self.editor.read(cx).read_only(cx) {
2072                cx.theme().colors().text_disabled
2073            } else {
2074                cx.theme().colors().text
2075            },
2076            font_family: settings.buffer_font.family.clone(),
2077            font_fallbacks: settings.buffer_font.fallbacks.clone(),
2078            font_size: settings.buffer_font_size.into(),
2079            font_weight: settings.buffer_font.weight,
2080            line_height: relative(settings.buffer_line_height.value()),
2081            ..Default::default()
2082        };
2083        EditorElement::new(
2084            &self.editor,
2085            EditorStyle {
2086                background: cx.theme().colors().editor_background,
2087                local_player: cx.theme().players().local(),
2088                text: text_style,
2089                ..Default::default()
2090            },
2091        )
2092    }
2093
2094    fn render_rate_limit_notice(&self, cx: &mut ViewContext<Self>) -> impl IntoElement {
2095        Popover::new().child(
2096            v_flex()
2097                .occlude()
2098                .p_2()
2099                .child(
2100                    Label::new("Out of Tokens")
2101                        .size(LabelSize::Small)
2102                        .weight(FontWeight::BOLD),
2103                )
2104                .child(Label::new(
2105                    "Try Zed Pro for higher limits, a wider range of models, and more.",
2106                ))
2107                .child(
2108                    h_flex()
2109                        .justify_between()
2110                        .child(CheckboxWithLabel::new(
2111                            "dont-show-again",
2112                            Label::new("Don't show again"),
2113                            if dismissed_rate_limit_notice() {
2114                                ui::Selection::Selected
2115                            } else {
2116                                ui::Selection::Unselected
2117                            },
2118                            |selection, cx| {
2119                                let is_dismissed = match selection {
2120                                    ui::Selection::Unselected => false,
2121                                    ui::Selection::Indeterminate => return,
2122                                    ui::Selection::Selected => true,
2123                                };
2124
2125                                set_rate_limit_notice_dismissed(is_dismissed, cx)
2126                            },
2127                        ))
2128                        .child(
2129                            h_flex()
2130                                .gap_2()
2131                                .child(
2132                                    Button::new("dismiss", "Dismiss")
2133                                        .style(ButtonStyle::Transparent)
2134                                        .on_click(cx.listener(Self::toggle_rate_limit_notice)),
2135                                )
2136                                .child(Button::new("more-info", "More Info").on_click(
2137                                    |_event, cx| {
2138                                        cx.dispatch_action(Box::new(
2139                                            zed_actions::OpenAccountSettings,
2140                                        ))
2141                                    },
2142                                )),
2143                        ),
2144                ),
2145        )
2146    }
2147}
2148
2149const DISMISSED_RATE_LIMIT_NOTICE_KEY: &str = "dismissed-rate-limit-notice";
2150
2151fn dismissed_rate_limit_notice() -> bool {
2152    db::kvp::KEY_VALUE_STORE
2153        .read_kvp(DISMISSED_RATE_LIMIT_NOTICE_KEY)
2154        .log_err()
2155        .map_or(false, |s| s.is_some())
2156}
2157
2158fn set_rate_limit_notice_dismissed(is_dismissed: bool, cx: &mut AppContext) {
2159    db::write_and_log(cx, move || async move {
2160        if is_dismissed {
2161            db::kvp::KEY_VALUE_STORE
2162                .write_kvp(DISMISSED_RATE_LIMIT_NOTICE_KEY.into(), "1".into())
2163                .await
2164        } else {
2165            db::kvp::KEY_VALUE_STORE
2166                .delete_kvp(DISMISSED_RATE_LIMIT_NOTICE_KEY.into())
2167                .await
2168        }
2169    })
2170}
2171
2172struct InlineAssist {
2173    group_id: InlineAssistGroupId,
2174    range: Range<Anchor>,
2175    editor: WeakView<Editor>,
2176    decorations: Option<InlineAssistDecorations>,
2177    codegen: Model<Codegen>,
2178    _subscriptions: Vec<Subscription>,
2179    workspace: Option<WeakView<Workspace>>,
2180    include_context: bool,
2181}
2182
2183impl InlineAssist {
2184    #[allow(clippy::too_many_arguments)]
2185    fn new(
2186        assist_id: InlineAssistId,
2187        group_id: InlineAssistGroupId,
2188        include_context: bool,
2189        editor: &View<Editor>,
2190        prompt_editor: &View<PromptEditor>,
2191        prompt_block_id: CustomBlockId,
2192        end_block_id: CustomBlockId,
2193        range: Range<Anchor>,
2194        codegen: Model<Codegen>,
2195        workspace: Option<WeakView<Workspace>>,
2196        cx: &mut WindowContext,
2197    ) -> Self {
2198        let prompt_editor_focus_handle = prompt_editor.focus_handle(cx);
2199        InlineAssist {
2200            group_id,
2201            include_context,
2202            editor: editor.downgrade(),
2203            decorations: Some(InlineAssistDecorations {
2204                prompt_block_id,
2205                prompt_editor: prompt_editor.clone(),
2206                removed_line_block_ids: HashSet::default(),
2207                end_block_id,
2208            }),
2209            range,
2210            codegen: codegen.clone(),
2211            workspace: workspace.clone(),
2212            _subscriptions: vec![
2213                cx.on_focus_in(&prompt_editor_focus_handle, move |cx| {
2214                    InlineAssistant::update_global(cx, |this, cx| {
2215                        this.handle_prompt_editor_focus_in(assist_id, cx)
2216                    })
2217                }),
2218                cx.on_focus_out(&prompt_editor_focus_handle, move |_, cx| {
2219                    InlineAssistant::update_global(cx, |this, cx| {
2220                        this.handle_prompt_editor_focus_out(assist_id, cx)
2221                    })
2222                }),
2223                cx.subscribe(prompt_editor, |prompt_editor, event, cx| {
2224                    InlineAssistant::update_global(cx, |this, cx| {
2225                        this.handle_prompt_editor_event(prompt_editor, event, cx)
2226                    })
2227                }),
2228                cx.observe(&codegen, {
2229                    let editor = editor.downgrade();
2230                    move |_, cx| {
2231                        if let Some(editor) = editor.upgrade() {
2232                            InlineAssistant::update_global(cx, |this, cx| {
2233                                if let Some(editor_assists) =
2234                                    this.assists_by_editor.get(&editor.downgrade())
2235                                {
2236                                    editor_assists.highlight_updates.send(()).ok();
2237                                }
2238
2239                                this.update_editor_blocks(&editor, assist_id, cx);
2240                            })
2241                        }
2242                    }
2243                }),
2244                cx.subscribe(&codegen, move |codegen, event, cx| {
2245                    InlineAssistant::update_global(cx, |this, cx| match event {
2246                        CodegenEvent::Undone => this.finish_assist(assist_id, false, cx),
2247                        CodegenEvent::Finished => {
2248                            let assist = if let Some(assist) = this.assists.get(&assist_id) {
2249                                assist
2250                            } else {
2251                                return;
2252                            };
2253
2254                            if let CodegenStatus::Error(error) = codegen.read(cx).status(cx) {
2255                                if assist.decorations.is_none() {
2256                                    if let Some(workspace) = assist
2257                                        .workspace
2258                                        .as_ref()
2259                                        .and_then(|workspace| workspace.upgrade())
2260                                    {
2261                                        let error = format!("Inline assistant error: {}", error);
2262                                        workspace.update(cx, |workspace, cx| {
2263                                            struct InlineAssistantError;
2264
2265                                            let id =
2266                                                NotificationId::composite::<InlineAssistantError>(
2267                                                    assist_id.0,
2268                                                );
2269
2270                                            workspace.show_toast(Toast::new(id, error), cx);
2271                                        })
2272                                    }
2273                                }
2274                            }
2275
2276                            if assist.decorations.is_none() {
2277                                this.finish_assist(assist_id, false, cx);
2278                            }
2279                        }
2280                    })
2281                }),
2282            ],
2283        }
2284    }
2285
2286    fn user_prompt(&self, cx: &AppContext) -> Option<String> {
2287        let decorations = self.decorations.as_ref()?;
2288        Some(decorations.prompt_editor.read(cx).prompt(cx))
2289    }
2290
2291    fn assistant_panel_context(&self, cx: &WindowContext) -> Option<LanguageModelRequest> {
2292        if self.include_context {
2293            let workspace = self.workspace.as_ref()?;
2294            let workspace = workspace.upgrade()?.read(cx);
2295            let assistant_panel = workspace.panel::<AssistantPanel>(cx)?;
2296            Some(
2297                assistant_panel
2298                    .read(cx)
2299                    .active_context(cx)?
2300                    .read(cx)
2301                    .to_completion_request(RequestType::Chat, cx),
2302            )
2303        } else {
2304            None
2305        }
2306    }
2307
2308    pub fn count_tokens(&self, cx: &WindowContext) -> BoxFuture<'static, Result<TokenCounts>> {
2309        let Some(user_prompt) = self.user_prompt(cx) else {
2310            return future::ready(Err(anyhow!("no user prompt"))).boxed();
2311        };
2312        let assistant_panel_context = self.assistant_panel_context(cx);
2313        self.codegen
2314            .read(cx)
2315            .count_tokens(user_prompt, assistant_panel_context, cx)
2316    }
2317}
2318
2319struct InlineAssistDecorations {
2320    prompt_block_id: CustomBlockId,
2321    prompt_editor: View<PromptEditor>,
2322    removed_line_block_ids: HashSet<CustomBlockId>,
2323    end_block_id: CustomBlockId,
2324}
2325
2326#[derive(Copy, Clone, Debug)]
2327pub enum CodegenEvent {
2328    Finished,
2329    Undone,
2330}
2331
2332pub struct Codegen {
2333    alternatives: Vec<Model<CodegenAlternative>>,
2334    active_alternative: usize,
2335    seen_alternatives: HashSet<usize>,
2336    subscriptions: Vec<Subscription>,
2337    buffer: Model<MultiBuffer>,
2338    range: Range<Anchor>,
2339    initial_transaction_id: Option<TransactionId>,
2340    telemetry: Option<Arc<Telemetry>>,
2341    builder: Arc<PromptBuilder>,
2342    is_insertion: bool,
2343}
2344
2345impl Codegen {
2346    pub fn new(
2347        buffer: Model<MultiBuffer>,
2348        range: Range<Anchor>,
2349        initial_transaction_id: Option<TransactionId>,
2350        telemetry: Option<Arc<Telemetry>>,
2351        builder: Arc<PromptBuilder>,
2352        cx: &mut ModelContext<Self>,
2353    ) -> Self {
2354        let codegen = cx.new_model(|cx| {
2355            CodegenAlternative::new(
2356                buffer.clone(),
2357                range.clone(),
2358                false,
2359                telemetry.clone(),
2360                builder.clone(),
2361                cx,
2362            )
2363        });
2364        let mut this = Self {
2365            is_insertion: range.to_offset(&buffer.read(cx).snapshot(cx)).is_empty(),
2366            alternatives: vec![codegen],
2367            active_alternative: 0,
2368            seen_alternatives: HashSet::default(),
2369            subscriptions: Vec::new(),
2370            buffer,
2371            range,
2372            initial_transaction_id,
2373            telemetry,
2374            builder,
2375        };
2376        this.activate(0, cx);
2377        this
2378    }
2379
2380    fn subscribe_to_alternative(&mut self, cx: &mut ModelContext<Self>) {
2381        let codegen = self.active_alternative().clone();
2382        self.subscriptions.clear();
2383        self.subscriptions
2384            .push(cx.observe(&codegen, |_, _, cx| cx.notify()));
2385        self.subscriptions
2386            .push(cx.subscribe(&codegen, |_, _, event, cx| cx.emit(*event)));
2387    }
2388
2389    fn active_alternative(&self) -> &Model<CodegenAlternative> {
2390        &self.alternatives[self.active_alternative]
2391    }
2392
2393    fn status<'a>(&self, cx: &'a AppContext) -> &'a CodegenStatus {
2394        &self.active_alternative().read(cx).status
2395    }
2396
2397    fn alternative_count(&self, cx: &AppContext) -> usize {
2398        LanguageModelRegistry::read_global(cx)
2399            .inline_alternative_models()
2400            .len()
2401            + 1
2402    }
2403
2404    pub fn cycle_prev(&mut self, cx: &mut ModelContext<Self>) {
2405        let next_active_ix = if self.active_alternative == 0 {
2406            self.alternatives.len() - 1
2407        } else {
2408            self.active_alternative - 1
2409        };
2410        self.activate(next_active_ix, cx);
2411    }
2412
2413    pub fn cycle_next(&mut self, cx: &mut ModelContext<Self>) {
2414        let next_active_ix = (self.active_alternative + 1) % self.alternatives.len();
2415        self.activate(next_active_ix, cx);
2416    }
2417
2418    fn activate(&mut self, index: usize, cx: &mut ModelContext<Self>) {
2419        self.active_alternative()
2420            .update(cx, |codegen, cx| codegen.set_active(false, cx));
2421        self.seen_alternatives.insert(index);
2422        self.active_alternative = index;
2423        self.active_alternative()
2424            .update(cx, |codegen, cx| codegen.set_active(true, cx));
2425        self.subscribe_to_alternative(cx);
2426        cx.notify();
2427    }
2428
2429    pub fn start(
2430        &mut self,
2431        user_prompt: String,
2432        assistant_panel_context: Option<LanguageModelRequest>,
2433        cx: &mut ModelContext<Self>,
2434    ) -> Result<()> {
2435        let alternative_models = LanguageModelRegistry::read_global(cx)
2436            .inline_alternative_models()
2437            .to_vec();
2438
2439        self.active_alternative()
2440            .update(cx, |alternative, cx| alternative.undo(cx));
2441        self.activate(0, cx);
2442        self.alternatives.truncate(1);
2443
2444        for _ in 0..alternative_models.len() {
2445            self.alternatives.push(cx.new_model(|cx| {
2446                CodegenAlternative::new(
2447                    self.buffer.clone(),
2448                    self.range.clone(),
2449                    false,
2450                    self.telemetry.clone(),
2451                    self.builder.clone(),
2452                    cx,
2453                )
2454            }));
2455        }
2456
2457        let primary_model = LanguageModelRegistry::read_global(cx)
2458            .active_model()
2459            .context("no active model")?;
2460
2461        for (model, alternative) in iter::once(primary_model)
2462            .chain(alternative_models)
2463            .zip(&self.alternatives)
2464        {
2465            alternative.update(cx, |alternative, cx| {
2466                alternative.start(
2467                    user_prompt.clone(),
2468                    assistant_panel_context.clone(),
2469                    model.clone(),
2470                    cx,
2471                )
2472            })?;
2473        }
2474
2475        Ok(())
2476    }
2477
2478    pub fn stop(&mut self, cx: &mut ModelContext<Self>) {
2479        for codegen in &self.alternatives {
2480            codegen.update(cx, |codegen, cx| codegen.stop(cx));
2481        }
2482    }
2483
2484    pub fn undo(&mut self, cx: &mut ModelContext<Self>) {
2485        self.active_alternative()
2486            .update(cx, |codegen, cx| codegen.undo(cx));
2487
2488        self.buffer.update(cx, |buffer, cx| {
2489            if let Some(transaction_id) = self.initial_transaction_id.take() {
2490                buffer.undo_transaction(transaction_id, cx);
2491                buffer.refresh_preview(cx);
2492            }
2493        });
2494    }
2495
2496    pub fn count_tokens(
2497        &self,
2498        user_prompt: String,
2499        assistant_panel_context: Option<LanguageModelRequest>,
2500        cx: &AppContext,
2501    ) -> BoxFuture<'static, Result<TokenCounts>> {
2502        self.active_alternative()
2503            .read(cx)
2504            .count_tokens(user_prompt, assistant_panel_context, cx)
2505    }
2506
2507    pub fn buffer(&self, cx: &AppContext) -> Model<MultiBuffer> {
2508        self.active_alternative().read(cx).buffer.clone()
2509    }
2510
2511    pub fn old_buffer(&self, cx: &AppContext) -> Model<Buffer> {
2512        self.active_alternative().read(cx).old_buffer.clone()
2513    }
2514
2515    pub fn snapshot(&self, cx: &AppContext) -> MultiBufferSnapshot {
2516        self.active_alternative().read(cx).snapshot.clone()
2517    }
2518
2519    pub fn edit_position(&self, cx: &AppContext) -> Option<Anchor> {
2520        self.active_alternative().read(cx).edit_position
2521    }
2522
2523    fn diff<'a>(&self, cx: &'a AppContext) -> &'a Diff {
2524        &self.active_alternative().read(cx).diff
2525    }
2526
2527    pub fn last_equal_ranges<'a>(&self, cx: &'a AppContext) -> &'a [Range<Anchor>] {
2528        self.active_alternative().read(cx).last_equal_ranges()
2529    }
2530}
2531
2532impl EventEmitter<CodegenEvent> for Codegen {}
2533
2534pub struct CodegenAlternative {
2535    buffer: Model<MultiBuffer>,
2536    old_buffer: Model<Buffer>,
2537    snapshot: MultiBufferSnapshot,
2538    edit_position: Option<Anchor>,
2539    range: Range<Anchor>,
2540    last_equal_ranges: Vec<Range<Anchor>>,
2541    transformation_transaction_id: Option<TransactionId>,
2542    status: CodegenStatus,
2543    generation: Task<()>,
2544    diff: Diff,
2545    telemetry: Option<Arc<Telemetry>>,
2546    _subscription: gpui::Subscription,
2547    builder: Arc<PromptBuilder>,
2548    active: bool,
2549    edits: Vec<(Range<Anchor>, String)>,
2550    line_operations: Vec<LineOperation>,
2551    request: Option<LanguageModelRequest>,
2552    elapsed_time: Option<f64>,
2553    message_id: Option<String>,
2554}
2555
2556enum CodegenStatus {
2557    Idle,
2558    Pending,
2559    Done,
2560    Error(anyhow::Error),
2561}
2562
2563#[derive(Default)]
2564struct Diff {
2565    deleted_row_ranges: Vec<(Anchor, RangeInclusive<u32>)>,
2566    inserted_row_ranges: Vec<Range<Anchor>>,
2567}
2568
2569impl Diff {
2570    fn is_empty(&self) -> bool {
2571        self.deleted_row_ranges.is_empty() && self.inserted_row_ranges.is_empty()
2572    }
2573}
2574
2575impl EventEmitter<CodegenEvent> for CodegenAlternative {}
2576
2577impl CodegenAlternative {
2578    pub fn new(
2579        buffer: Model<MultiBuffer>,
2580        range: Range<Anchor>,
2581        active: bool,
2582        telemetry: Option<Arc<Telemetry>>,
2583        builder: Arc<PromptBuilder>,
2584        cx: &mut ModelContext<Self>,
2585    ) -> Self {
2586        let snapshot = buffer.read(cx).snapshot(cx);
2587
2588        let (old_buffer, _, _) = buffer
2589            .read(cx)
2590            .range_to_buffer_ranges(range.clone(), cx)
2591            .pop()
2592            .unwrap();
2593        let old_buffer = cx.new_model(|cx| {
2594            let old_buffer = old_buffer.read(cx);
2595            let text = old_buffer.as_rope().clone();
2596            let line_ending = old_buffer.line_ending();
2597            let language = old_buffer.language().cloned();
2598            let language_registry = old_buffer.language_registry();
2599
2600            let mut buffer = Buffer::local_normalized(text, line_ending, cx);
2601            buffer.set_language(language, cx);
2602            if let Some(language_registry) = language_registry {
2603                buffer.set_language_registry(language_registry)
2604            }
2605            buffer
2606        });
2607
2608        Self {
2609            buffer: buffer.clone(),
2610            old_buffer,
2611            edit_position: None,
2612            message_id: None,
2613            snapshot,
2614            last_equal_ranges: Default::default(),
2615            transformation_transaction_id: None,
2616            status: CodegenStatus::Idle,
2617            generation: Task::ready(()),
2618            diff: Diff::default(),
2619            telemetry,
2620            _subscription: cx.subscribe(&buffer, Self::handle_buffer_event),
2621            builder,
2622            active,
2623            edits: Vec::new(),
2624            line_operations: Vec::new(),
2625            range,
2626            request: None,
2627            elapsed_time: None,
2628        }
2629    }
2630
2631    fn set_active(&mut self, active: bool, cx: &mut ModelContext<Self>) {
2632        if active != self.active {
2633            self.active = active;
2634
2635            if self.active {
2636                let edits = self.edits.clone();
2637                self.apply_edits(edits, cx);
2638                if matches!(self.status, CodegenStatus::Pending) {
2639                    let line_operations = self.line_operations.clone();
2640                    self.reapply_line_based_diff(line_operations, cx);
2641                } else {
2642                    self.reapply_batch_diff(cx).detach();
2643                }
2644            } else if let Some(transaction_id) = self.transformation_transaction_id.take() {
2645                self.buffer.update(cx, |buffer, cx| {
2646                    buffer.undo_transaction(transaction_id, cx);
2647                    buffer.forget_transaction(transaction_id, cx);
2648                });
2649            }
2650        }
2651    }
2652
2653    fn handle_buffer_event(
2654        &mut self,
2655        _buffer: Model<MultiBuffer>,
2656        event: &multi_buffer::Event,
2657        cx: &mut ModelContext<Self>,
2658    ) {
2659        if let multi_buffer::Event::TransactionUndone { transaction_id } = event {
2660            if self.transformation_transaction_id == Some(*transaction_id) {
2661                self.transformation_transaction_id = None;
2662                self.generation = Task::ready(());
2663                cx.emit(CodegenEvent::Undone);
2664            }
2665        }
2666    }
2667
2668    pub fn last_equal_ranges(&self) -> &[Range<Anchor>] {
2669        &self.last_equal_ranges
2670    }
2671
2672    pub fn count_tokens(
2673        &self,
2674        user_prompt: String,
2675        assistant_panel_context: Option<LanguageModelRequest>,
2676        cx: &AppContext,
2677    ) -> BoxFuture<'static, Result<TokenCounts>> {
2678        if let Some(model) = LanguageModelRegistry::read_global(cx).active_model() {
2679            let request = self.build_request(user_prompt, assistant_panel_context.clone(), cx);
2680            match request {
2681                Ok(request) => {
2682                    let total_count = model.count_tokens(request.clone(), cx);
2683                    let assistant_panel_count = assistant_panel_context
2684                        .map(|context| model.count_tokens(context, cx))
2685                        .unwrap_or_else(|| future::ready(Ok(0)).boxed());
2686
2687                    async move {
2688                        Ok(TokenCounts {
2689                            total: total_count.await?,
2690                            assistant_panel: assistant_panel_count.await?,
2691                        })
2692                    }
2693                    .boxed()
2694                }
2695                Err(error) => futures::future::ready(Err(error)).boxed(),
2696            }
2697        } else {
2698            future::ready(Err(anyhow!("no active model"))).boxed()
2699        }
2700    }
2701
2702    pub fn start(
2703        &mut self,
2704        user_prompt: String,
2705        assistant_panel_context: Option<LanguageModelRequest>,
2706        model: Arc<dyn LanguageModel>,
2707        cx: &mut ModelContext<Self>,
2708    ) -> Result<()> {
2709        if let Some(transformation_transaction_id) = self.transformation_transaction_id.take() {
2710            self.buffer.update(cx, |buffer, cx| {
2711                buffer.undo_transaction(transformation_transaction_id, cx);
2712            });
2713        }
2714
2715        self.edit_position = Some(self.range.start.bias_right(&self.snapshot));
2716
2717        let api_key = model.api_key(cx);
2718        let telemetry_id = model.telemetry_id();
2719        let provider_id = model.provider_id();
2720        let stream: LocalBoxFuture<Result<LanguageModelTextStream>> =
2721            if user_prompt.trim().to_lowercase() == "delete" {
2722                async { Ok(LanguageModelTextStream::default()) }.boxed_local()
2723            } else {
2724                let request = self.build_request(user_prompt, assistant_panel_context, cx)?;
2725                self.request = Some(request.clone());
2726
2727                cx.spawn(|_, cx| async move { model.stream_completion_text(request, &cx).await })
2728                    .boxed_local()
2729            };
2730        self.handle_stream(telemetry_id, provider_id.to_string(), api_key, stream, cx);
2731        Ok(())
2732    }
2733
2734    fn build_request(
2735        &self,
2736        user_prompt: String,
2737        assistant_panel_context: Option<LanguageModelRequest>,
2738        cx: &AppContext,
2739    ) -> Result<LanguageModelRequest> {
2740        let buffer = self.buffer.read(cx).snapshot(cx);
2741        let language = buffer.language_at(self.range.start);
2742        let language_name = if let Some(language) = language.as_ref() {
2743            if Arc::ptr_eq(language, &language::PLAIN_TEXT) {
2744                None
2745            } else {
2746                Some(language.name())
2747            }
2748        } else {
2749            None
2750        };
2751
2752        let language_name = language_name.as_ref();
2753        let start = buffer.point_to_buffer_offset(self.range.start);
2754        let end = buffer.point_to_buffer_offset(self.range.end);
2755        let (buffer, range) = if let Some((start, end)) = start.zip(end) {
2756            let (start_buffer, start_buffer_offset) = start;
2757            let (end_buffer, end_buffer_offset) = end;
2758            if start_buffer.remote_id() == end_buffer.remote_id() {
2759                (start_buffer.clone(), start_buffer_offset..end_buffer_offset)
2760            } else {
2761                return Err(anyhow::anyhow!("invalid transformation range"));
2762            }
2763        } else {
2764            return Err(anyhow::anyhow!("invalid transformation range"));
2765        };
2766
2767        let prompt = self
2768            .builder
2769            .generate_inline_transformation_prompt(user_prompt, language_name, buffer, range)
2770            .map_err(|e| anyhow::anyhow!("Failed to generate content prompt: {}", e))?;
2771
2772        let mut messages = Vec::new();
2773        if let Some(context_request) = assistant_panel_context {
2774            messages = context_request.messages;
2775        }
2776
2777        messages.push(LanguageModelRequestMessage {
2778            role: Role::User,
2779            content: vec![prompt.into()],
2780            cache: false,
2781        });
2782
2783        Ok(LanguageModelRequest {
2784            messages,
2785            tools: Vec::new(),
2786            stop: Vec::new(),
2787            temperature: None,
2788        })
2789    }
2790
2791    pub fn handle_stream(
2792        &mut self,
2793        model_telemetry_id: String,
2794        model_provider_id: String,
2795        model_api_key: Option<String>,
2796        stream: impl 'static + Future<Output = Result<LanguageModelTextStream>>,
2797        cx: &mut ModelContext<Self>,
2798    ) {
2799        let start_time = Instant::now();
2800        let snapshot = self.snapshot.clone();
2801        let selected_text = snapshot
2802            .text_for_range(self.range.start..self.range.end)
2803            .collect::<Rope>();
2804
2805        let selection_start = self.range.start.to_point(&snapshot);
2806
2807        // Start with the indentation of the first line in the selection
2808        let mut suggested_line_indent = snapshot
2809            .suggested_indents(selection_start.row..=selection_start.row, cx)
2810            .into_values()
2811            .next()
2812            .unwrap_or_else(|| snapshot.indent_size_for_line(MultiBufferRow(selection_start.row)));
2813
2814        // If the first line in the selection does not have indentation, check the following lines
2815        if suggested_line_indent.len == 0 && suggested_line_indent.kind == IndentKind::Space {
2816            for row in selection_start.row..=self.range.end.to_point(&snapshot).row {
2817                let line_indent = snapshot.indent_size_for_line(MultiBufferRow(row));
2818                // Prefer tabs if a line in the selection uses tabs as indentation
2819                if line_indent.kind == IndentKind::Tab {
2820                    suggested_line_indent.kind = IndentKind::Tab;
2821                    break;
2822                }
2823            }
2824        }
2825
2826        let http_client = cx.http_client().clone();
2827        let telemetry = self.telemetry.clone();
2828        let language_name = {
2829            let multibuffer = self.buffer.read(cx);
2830            let ranges = multibuffer.range_to_buffer_ranges(self.range.clone(), cx);
2831            ranges
2832                .first()
2833                .and_then(|(buffer, _, _)| buffer.read(cx).language())
2834                .map(|language| language.name())
2835        };
2836
2837        self.diff = Diff::default();
2838        self.status = CodegenStatus::Pending;
2839        let mut edit_start = self.range.start.to_offset(&snapshot);
2840        self.generation = cx.spawn(|codegen, mut cx| {
2841            async move {
2842                let stream = stream.await;
2843                let message_id = stream
2844                    .as_ref()
2845                    .ok()
2846                    .and_then(|stream| stream.message_id.clone());
2847                let generate = async {
2848                    let (mut diff_tx, mut diff_rx) = mpsc::channel(1);
2849                    let executor = cx.background_executor().clone();
2850                    let message_id = message_id.clone();
2851                    let line_based_stream_diff: Task<anyhow::Result<()>> =
2852                        cx.background_executor().spawn(async move {
2853                            let mut response_latency = None;
2854                            let request_start = Instant::now();
2855                            let diff = async {
2856                                let chunks = StripInvalidSpans::new(stream?.stream);
2857                                futures::pin_mut!(chunks);
2858                                let mut diff = StreamingDiff::new(selected_text.to_string());
2859                                let mut line_diff = LineDiff::default();
2860
2861                                let mut new_text = String::new();
2862                                let mut base_indent = None;
2863                                let mut line_indent = None;
2864                                let mut first_line = true;
2865
2866                                while let Some(chunk) = chunks.next().await {
2867                                    if response_latency.is_none() {
2868                                        response_latency = Some(request_start.elapsed());
2869                                    }
2870                                    let chunk = chunk?;
2871
2872                                    let mut lines = chunk.split('\n').peekable();
2873                                    while let Some(line) = lines.next() {
2874                                        new_text.push_str(line);
2875                                        if line_indent.is_none() {
2876                                            if let Some(non_whitespace_ch_ix) =
2877                                                new_text.find(|ch: char| !ch.is_whitespace())
2878                                            {
2879                                                line_indent = Some(non_whitespace_ch_ix);
2880                                                base_indent = base_indent.or(line_indent);
2881
2882                                                let line_indent = line_indent.unwrap();
2883                                                let base_indent = base_indent.unwrap();
2884                                                let indent_delta =
2885                                                    line_indent as i32 - base_indent as i32;
2886                                                let mut corrected_indent_len = cmp::max(
2887                                                    0,
2888                                                    suggested_line_indent.len as i32 + indent_delta,
2889                                                )
2890                                                    as usize;
2891                                                if first_line {
2892                                                    corrected_indent_len = corrected_indent_len
2893                                                        .saturating_sub(
2894                                                            selection_start.column as usize,
2895                                                        );
2896                                                }
2897
2898                                                let indent_char = suggested_line_indent.char();
2899                                                let mut indent_buffer = [0; 4];
2900                                                let indent_str =
2901                                                    indent_char.encode_utf8(&mut indent_buffer);
2902                                                new_text.replace_range(
2903                                                    ..line_indent,
2904                                                    &indent_str.repeat(corrected_indent_len),
2905                                                );
2906                                            }
2907                                        }
2908
2909                                        if line_indent.is_some() {
2910                                            let char_ops = diff.push_new(&new_text);
2911                                            line_diff
2912                                                .push_char_operations(&char_ops, &selected_text);
2913                                            diff_tx
2914                                                .send((char_ops, line_diff.line_operations()))
2915                                                .await?;
2916                                            new_text.clear();
2917                                        }
2918
2919                                        if lines.peek().is_some() {
2920                                            let char_ops = diff.push_new("\n");
2921                                            line_diff
2922                                                .push_char_operations(&char_ops, &selected_text);
2923                                            diff_tx
2924                                                .send((char_ops, line_diff.line_operations()))
2925                                                .await?;
2926                                            if line_indent.is_none() {
2927                                                // Don't write out the leading indentation in empty lines on the next line
2928                                                // This is the case where the above if statement didn't clear the buffer
2929                                                new_text.clear();
2930                                            }
2931                                            line_indent = None;
2932                                            first_line = false;
2933                                        }
2934                                    }
2935                                }
2936
2937                                let mut char_ops = diff.push_new(&new_text);
2938                                char_ops.extend(diff.finish());
2939                                line_diff.push_char_operations(&char_ops, &selected_text);
2940                                line_diff.finish(&selected_text);
2941                                diff_tx
2942                                    .send((char_ops, line_diff.line_operations()))
2943                                    .await?;
2944
2945                                anyhow::Ok(())
2946                            };
2947
2948                            let result = diff.await;
2949
2950                            let error_message =
2951                                result.as_ref().err().map(|error| error.to_string());
2952                            report_assistant_event(
2953                                AssistantEvent {
2954                                    conversation_id: None,
2955                                    message_id,
2956                                    kind: AssistantKind::Inline,
2957                                    phase: AssistantPhase::Response,
2958                                    model: model_telemetry_id,
2959                                    model_provider: model_provider_id.to_string(),
2960                                    response_latency,
2961                                    error_message,
2962                                    language_name: language_name.map(|name| name.to_proto()),
2963                                },
2964                                telemetry,
2965                                http_client,
2966                                model_api_key,
2967                                &executor,
2968                            );
2969
2970                            result?;
2971                            Ok(())
2972                        });
2973
2974                    while let Some((char_ops, line_ops)) = diff_rx.next().await {
2975                        codegen.update(&mut cx, |codegen, cx| {
2976                            codegen.last_equal_ranges.clear();
2977
2978                            let edits = char_ops
2979                                .into_iter()
2980                                .filter_map(|operation| match operation {
2981                                    CharOperation::Insert { text } => {
2982                                        let edit_start = snapshot.anchor_after(edit_start);
2983                                        Some((edit_start..edit_start, text))
2984                                    }
2985                                    CharOperation::Delete { bytes } => {
2986                                        let edit_end = edit_start + bytes;
2987                                        let edit_range = snapshot.anchor_after(edit_start)
2988                                            ..snapshot.anchor_before(edit_end);
2989                                        edit_start = edit_end;
2990                                        Some((edit_range, String::new()))
2991                                    }
2992                                    CharOperation::Keep { bytes } => {
2993                                        let edit_end = edit_start + bytes;
2994                                        let edit_range = snapshot.anchor_after(edit_start)
2995                                            ..snapshot.anchor_before(edit_end);
2996                                        edit_start = edit_end;
2997                                        codegen.last_equal_ranges.push(edit_range);
2998                                        None
2999                                    }
3000                                })
3001                                .collect::<Vec<_>>();
3002
3003                            if codegen.active {
3004                                codegen.apply_edits(edits.iter().cloned(), cx);
3005                                codegen.reapply_line_based_diff(line_ops.iter().cloned(), cx);
3006                            }
3007                            codegen.edits.extend(edits);
3008                            codegen.line_operations = line_ops;
3009                            codegen.edit_position = Some(snapshot.anchor_after(edit_start));
3010
3011                            cx.notify();
3012                        })?;
3013                    }
3014
3015                    // Streaming stopped and we have the new text in the buffer, and a line-based diff applied for the whole new buffer.
3016                    // That diff is not what a regular diff is and might look unexpected, ergo apply a regular diff.
3017                    // It's fine to apply even if the rest of the line diffing fails, as no more hunks are coming through `diff_rx`.
3018                    let batch_diff_task =
3019                        codegen.update(&mut cx, |codegen, cx| codegen.reapply_batch_diff(cx))?;
3020                    let (line_based_stream_diff, ()) =
3021                        join!(line_based_stream_diff, batch_diff_task);
3022                    line_based_stream_diff?;
3023
3024                    anyhow::Ok(())
3025                };
3026
3027                let result = generate.await;
3028                let elapsed_time = start_time.elapsed().as_secs_f64();
3029
3030                codegen
3031                    .update(&mut cx, |this, cx| {
3032                        this.message_id = message_id;
3033                        this.last_equal_ranges.clear();
3034                        if let Err(error) = result {
3035                            this.status = CodegenStatus::Error(error);
3036                        } else {
3037                            this.status = CodegenStatus::Done;
3038                        }
3039                        this.elapsed_time = Some(elapsed_time);
3040                        cx.emit(CodegenEvent::Finished);
3041                        cx.notify();
3042                    })
3043                    .ok();
3044            }
3045        });
3046        cx.notify();
3047    }
3048
3049    pub fn stop(&mut self, cx: &mut ModelContext<Self>) {
3050        self.last_equal_ranges.clear();
3051        if self.diff.is_empty() {
3052            self.status = CodegenStatus::Idle;
3053        } else {
3054            self.status = CodegenStatus::Done;
3055        }
3056        self.generation = Task::ready(());
3057        cx.emit(CodegenEvent::Finished);
3058        cx.notify();
3059    }
3060
3061    pub fn undo(&mut self, cx: &mut ModelContext<Self>) {
3062        self.buffer.update(cx, |buffer, cx| {
3063            if let Some(transaction_id) = self.transformation_transaction_id.take() {
3064                buffer.undo_transaction(transaction_id, cx);
3065                buffer.refresh_preview(cx);
3066            }
3067        });
3068    }
3069
3070    fn apply_edits(
3071        &mut self,
3072        edits: impl IntoIterator<Item = (Range<Anchor>, String)>,
3073        cx: &mut ModelContext<CodegenAlternative>,
3074    ) {
3075        let transaction = self.buffer.update(cx, |buffer, cx| {
3076            // Avoid grouping assistant edits with user edits.
3077            buffer.finalize_last_transaction(cx);
3078            buffer.start_transaction(cx);
3079            buffer.edit(edits, None, cx);
3080            buffer.end_transaction(cx)
3081        });
3082
3083        if let Some(transaction) = transaction {
3084            if let Some(first_transaction) = self.transformation_transaction_id {
3085                // Group all assistant edits into the first transaction.
3086                self.buffer.update(cx, |buffer, cx| {
3087                    buffer.merge_transactions(transaction, first_transaction, cx)
3088                });
3089            } else {
3090                self.transformation_transaction_id = Some(transaction);
3091                self.buffer
3092                    .update(cx, |buffer, cx| buffer.finalize_last_transaction(cx));
3093            }
3094        }
3095    }
3096
3097    fn reapply_line_based_diff(
3098        &mut self,
3099        line_operations: impl IntoIterator<Item = LineOperation>,
3100        cx: &mut ModelContext<Self>,
3101    ) {
3102        let old_snapshot = self.snapshot.clone();
3103        let old_range = self.range.to_point(&old_snapshot);
3104        let new_snapshot = self.buffer.read(cx).snapshot(cx);
3105        let new_range = self.range.to_point(&new_snapshot);
3106
3107        let mut old_row = old_range.start.row;
3108        let mut new_row = new_range.start.row;
3109
3110        self.diff.deleted_row_ranges.clear();
3111        self.diff.inserted_row_ranges.clear();
3112        for operation in line_operations {
3113            match operation {
3114                LineOperation::Keep { lines } => {
3115                    old_row += lines;
3116                    new_row += lines;
3117                }
3118                LineOperation::Delete { lines } => {
3119                    let old_end_row = old_row + lines - 1;
3120                    let new_row = new_snapshot.anchor_before(Point::new(new_row, 0));
3121
3122                    if let Some((_, last_deleted_row_range)) =
3123                        self.diff.deleted_row_ranges.last_mut()
3124                    {
3125                        if *last_deleted_row_range.end() + 1 == old_row {
3126                            *last_deleted_row_range = *last_deleted_row_range.start()..=old_end_row;
3127                        } else {
3128                            self.diff
3129                                .deleted_row_ranges
3130                                .push((new_row, old_row..=old_end_row));
3131                        }
3132                    } else {
3133                        self.diff
3134                            .deleted_row_ranges
3135                            .push((new_row, old_row..=old_end_row));
3136                    }
3137
3138                    old_row += lines;
3139                }
3140                LineOperation::Insert { lines } => {
3141                    let new_end_row = new_row + lines - 1;
3142                    let start = new_snapshot.anchor_before(Point::new(new_row, 0));
3143                    let end = new_snapshot.anchor_before(Point::new(
3144                        new_end_row,
3145                        new_snapshot.line_len(MultiBufferRow(new_end_row)),
3146                    ));
3147                    self.diff.inserted_row_ranges.push(start..end);
3148                    new_row += lines;
3149                }
3150            }
3151
3152            cx.notify();
3153        }
3154    }
3155
3156    fn reapply_batch_diff(&mut self, cx: &mut ModelContext<Self>) -> Task<()> {
3157        let old_snapshot = self.snapshot.clone();
3158        let old_range = self.range.to_point(&old_snapshot);
3159        let new_snapshot = self.buffer.read(cx).snapshot(cx);
3160        let new_range = self.range.to_point(&new_snapshot);
3161
3162        cx.spawn(|codegen, mut cx| async move {
3163            let (deleted_row_ranges, inserted_row_ranges) = cx
3164                .background_executor()
3165                .spawn(async move {
3166                    let old_text = old_snapshot
3167                        .text_for_range(
3168                            Point::new(old_range.start.row, 0)
3169                                ..Point::new(
3170                                    old_range.end.row,
3171                                    old_snapshot.line_len(MultiBufferRow(old_range.end.row)),
3172                                ),
3173                        )
3174                        .collect::<String>();
3175                    let new_text = new_snapshot
3176                        .text_for_range(
3177                            Point::new(new_range.start.row, 0)
3178                                ..Point::new(
3179                                    new_range.end.row,
3180                                    new_snapshot.line_len(MultiBufferRow(new_range.end.row)),
3181                                ),
3182                        )
3183                        .collect::<String>();
3184
3185                    let mut old_row = old_range.start.row;
3186                    let mut new_row = new_range.start.row;
3187                    let batch_diff =
3188                        similar::TextDiff::from_lines(old_text.as_str(), new_text.as_str());
3189
3190                    let mut deleted_row_ranges: Vec<(Anchor, RangeInclusive<u32>)> = Vec::new();
3191                    let mut inserted_row_ranges = Vec::new();
3192                    for change in batch_diff.iter_all_changes() {
3193                        let line_count = change.value().lines().count() as u32;
3194                        match change.tag() {
3195                            similar::ChangeTag::Equal => {
3196                                old_row += line_count;
3197                                new_row += line_count;
3198                            }
3199                            similar::ChangeTag::Delete => {
3200                                let old_end_row = old_row + line_count - 1;
3201                                let new_row = new_snapshot.anchor_before(Point::new(new_row, 0));
3202
3203                                if let Some((_, last_deleted_row_range)) =
3204                                    deleted_row_ranges.last_mut()
3205                                {
3206                                    if *last_deleted_row_range.end() + 1 == old_row {
3207                                        *last_deleted_row_range =
3208                                            *last_deleted_row_range.start()..=old_end_row;
3209                                    } else {
3210                                        deleted_row_ranges.push((new_row, old_row..=old_end_row));
3211                                    }
3212                                } else {
3213                                    deleted_row_ranges.push((new_row, old_row..=old_end_row));
3214                                }
3215
3216                                old_row += line_count;
3217                            }
3218                            similar::ChangeTag::Insert => {
3219                                let new_end_row = new_row + line_count - 1;
3220                                let start = new_snapshot.anchor_before(Point::new(new_row, 0));
3221                                let end = new_snapshot.anchor_before(Point::new(
3222                                    new_end_row,
3223                                    new_snapshot.line_len(MultiBufferRow(new_end_row)),
3224                                ));
3225                                inserted_row_ranges.push(start..end);
3226                                new_row += line_count;
3227                            }
3228                        }
3229                    }
3230
3231                    (deleted_row_ranges, inserted_row_ranges)
3232                })
3233                .await;
3234
3235            codegen
3236                .update(&mut cx, |codegen, cx| {
3237                    codegen.diff.deleted_row_ranges = deleted_row_ranges;
3238                    codegen.diff.inserted_row_ranges = inserted_row_ranges;
3239                    cx.notify();
3240                })
3241                .ok();
3242        })
3243    }
3244}
3245
3246struct StripInvalidSpans<T> {
3247    stream: T,
3248    stream_done: bool,
3249    buffer: String,
3250    first_line: bool,
3251    line_end: bool,
3252    starts_with_code_block: bool,
3253}
3254
3255impl<T> StripInvalidSpans<T>
3256where
3257    T: Stream<Item = Result<String>>,
3258{
3259    fn new(stream: T) -> Self {
3260        Self {
3261            stream,
3262            stream_done: false,
3263            buffer: String::new(),
3264            first_line: true,
3265            line_end: false,
3266            starts_with_code_block: false,
3267        }
3268    }
3269}
3270
3271impl<T> Stream for StripInvalidSpans<T>
3272where
3273    T: Stream<Item = Result<String>>,
3274{
3275    type Item = Result<String>;
3276
3277    fn poll_next(self: Pin<&mut Self>, cx: &mut task::Context) -> Poll<Option<Self::Item>> {
3278        const CODE_BLOCK_DELIMITER: &str = "```";
3279        const CURSOR_SPAN: &str = "<|CURSOR|>";
3280
3281        let this = unsafe { self.get_unchecked_mut() };
3282        loop {
3283            if !this.stream_done {
3284                let mut stream = unsafe { Pin::new_unchecked(&mut this.stream) };
3285                match stream.as_mut().poll_next(cx) {
3286                    Poll::Ready(Some(Ok(chunk))) => {
3287                        this.buffer.push_str(&chunk);
3288                    }
3289                    Poll::Ready(Some(Err(error))) => return Poll::Ready(Some(Err(error))),
3290                    Poll::Ready(None) => {
3291                        this.stream_done = true;
3292                    }
3293                    Poll::Pending => return Poll::Pending,
3294                }
3295            }
3296
3297            let mut chunk = String::new();
3298            let mut consumed = 0;
3299            if !this.buffer.is_empty() {
3300                let mut lines = this.buffer.split('\n').enumerate().peekable();
3301                while let Some((line_ix, line)) = lines.next() {
3302                    if line_ix > 0 {
3303                        this.first_line = false;
3304                    }
3305
3306                    if this.first_line {
3307                        let trimmed_line = line.trim();
3308                        if lines.peek().is_some() {
3309                            if trimmed_line.starts_with(CODE_BLOCK_DELIMITER) {
3310                                consumed += line.len() + 1;
3311                                this.starts_with_code_block = true;
3312                                continue;
3313                            }
3314                        } else if trimmed_line.is_empty()
3315                            || prefixes(CODE_BLOCK_DELIMITER)
3316                                .any(|prefix| trimmed_line.starts_with(prefix))
3317                        {
3318                            break;
3319                        }
3320                    }
3321
3322                    let line_without_cursor = line.replace(CURSOR_SPAN, "");
3323                    if lines.peek().is_some() {
3324                        if this.line_end {
3325                            chunk.push('\n');
3326                        }
3327
3328                        chunk.push_str(&line_without_cursor);
3329                        this.line_end = true;
3330                        consumed += line.len() + 1;
3331                    } else if this.stream_done {
3332                        if !this.starts_with_code_block
3333                            || !line_without_cursor.trim().ends_with(CODE_BLOCK_DELIMITER)
3334                        {
3335                            if this.line_end {
3336                                chunk.push('\n');
3337                            }
3338
3339                            chunk.push_str(&line);
3340                        }
3341
3342                        consumed += line.len();
3343                    } else {
3344                        let trimmed_line = line.trim();
3345                        if trimmed_line.is_empty()
3346                            || prefixes(CURSOR_SPAN).any(|prefix| trimmed_line.ends_with(prefix))
3347                            || prefixes(CODE_BLOCK_DELIMITER)
3348                                .any(|prefix| trimmed_line.ends_with(prefix))
3349                        {
3350                            break;
3351                        } else {
3352                            if this.line_end {
3353                                chunk.push('\n');
3354                                this.line_end = false;
3355                            }
3356
3357                            chunk.push_str(&line_without_cursor);
3358                            consumed += line.len();
3359                        }
3360                    }
3361                }
3362            }
3363
3364            this.buffer = this.buffer.split_off(consumed);
3365            if !chunk.is_empty() {
3366                return Poll::Ready(Some(Ok(chunk)));
3367            } else if this.stream_done {
3368                return Poll::Ready(None);
3369            }
3370        }
3371    }
3372}
3373
3374struct AssistantCodeActionProvider {
3375    editor: WeakView<Editor>,
3376    workspace: WeakView<Workspace>,
3377}
3378
3379impl CodeActionProvider for AssistantCodeActionProvider {
3380    fn code_actions(
3381        &self,
3382        buffer: &Model<Buffer>,
3383        range: Range<text::Anchor>,
3384        cx: &mut WindowContext,
3385    ) -> Task<Result<Vec<CodeAction>>> {
3386        if !AssistantSettings::get_global(cx).enabled {
3387            return Task::ready(Ok(Vec::new()));
3388        }
3389
3390        let snapshot = buffer.read(cx).snapshot();
3391        let mut range = range.to_point(&snapshot);
3392
3393        // Expand the range to line boundaries.
3394        range.start.column = 0;
3395        range.end.column = snapshot.line_len(range.end.row);
3396
3397        let mut has_diagnostics = false;
3398        for diagnostic in snapshot.diagnostics_in_range::<_, Point>(range.clone(), false) {
3399            range.start = cmp::min(range.start, diagnostic.range.start);
3400            range.end = cmp::max(range.end, diagnostic.range.end);
3401            has_diagnostics = true;
3402        }
3403        if has_diagnostics {
3404            if let Some(symbols_containing_start) = snapshot.symbols_containing(range.start, None) {
3405                if let Some(symbol) = symbols_containing_start.last() {
3406                    range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
3407                    range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
3408                }
3409            }
3410
3411            if let Some(symbols_containing_end) = snapshot.symbols_containing(range.end, None) {
3412                if let Some(symbol) = symbols_containing_end.last() {
3413                    range.start = cmp::min(range.start, symbol.range.start.to_point(&snapshot));
3414                    range.end = cmp::max(range.end, symbol.range.end.to_point(&snapshot));
3415                }
3416            }
3417
3418            Task::ready(Ok(vec![CodeAction {
3419                server_id: language::LanguageServerId(0),
3420                range: snapshot.anchor_before(range.start)..snapshot.anchor_after(range.end),
3421                lsp_action: lsp::CodeAction {
3422                    title: "Fix with Assistant".into(),
3423                    ..Default::default()
3424                },
3425            }]))
3426        } else {
3427            Task::ready(Ok(Vec::new()))
3428        }
3429    }
3430
3431    fn apply_code_action(
3432        &self,
3433        buffer: Model<Buffer>,
3434        action: CodeAction,
3435        excerpt_id: ExcerptId,
3436        _push_to_history: bool,
3437        cx: &mut WindowContext,
3438    ) -> Task<Result<ProjectTransaction>> {
3439        let editor = self.editor.clone();
3440        let workspace = self.workspace.clone();
3441        cx.spawn(|mut cx| async move {
3442            let editor = editor.upgrade().context("editor was released")?;
3443            let range = editor
3444                .update(&mut cx, |editor, cx| {
3445                    editor.buffer().update(cx, |multibuffer, cx| {
3446                        let buffer = buffer.read(cx);
3447                        let multibuffer_snapshot = multibuffer.read(cx);
3448
3449                        let old_context_range =
3450                            multibuffer_snapshot.context_range_for_excerpt(excerpt_id)?;
3451                        let mut new_context_range = old_context_range.clone();
3452                        if action
3453                            .range
3454                            .start
3455                            .cmp(&old_context_range.start, buffer)
3456                            .is_lt()
3457                        {
3458                            new_context_range.start = action.range.start;
3459                        }
3460                        if action.range.end.cmp(&old_context_range.end, buffer).is_gt() {
3461                            new_context_range.end = action.range.end;
3462                        }
3463                        drop(multibuffer_snapshot);
3464
3465                        if new_context_range != old_context_range {
3466                            multibuffer.resize_excerpt(excerpt_id, new_context_range, cx);
3467                        }
3468
3469                        let multibuffer_snapshot = multibuffer.read(cx);
3470                        Some(
3471                            multibuffer_snapshot
3472                                .anchor_in_excerpt(excerpt_id, action.range.start)?
3473                                ..multibuffer_snapshot
3474                                    .anchor_in_excerpt(excerpt_id, action.range.end)?,
3475                        )
3476                    })
3477                })?
3478                .context("invalid range")?;
3479            let assistant_panel = workspace.update(&mut cx, |workspace, cx| {
3480                workspace
3481                    .panel::<AssistantPanel>(cx)
3482                    .context("assistant panel was released")
3483            })??;
3484
3485            cx.update_global(|assistant: &mut InlineAssistant, cx| {
3486                let assist_id = assistant.suggest_assist(
3487                    &editor,
3488                    range,
3489                    "Fix Diagnostics".into(),
3490                    None,
3491                    true,
3492                    Some(workspace),
3493                    Some(&assistant_panel),
3494                    cx,
3495                );
3496                assistant.start_assist(assist_id, cx);
3497            })?;
3498
3499            Ok(ProjectTransaction::default())
3500        })
3501    }
3502}
3503
3504fn prefixes(text: &str) -> impl Iterator<Item = &str> {
3505    (0..text.len() - 1).map(|ix| &text[..ix + 1])
3506}
3507
3508fn merge_ranges(ranges: &mut Vec<Range<Anchor>>, buffer: &MultiBufferSnapshot) {
3509    ranges.sort_unstable_by(|a, b| {
3510        a.start
3511            .cmp(&b.start, buffer)
3512            .then_with(|| b.end.cmp(&a.end, buffer))
3513    });
3514
3515    let mut ix = 0;
3516    while ix + 1 < ranges.len() {
3517        let b = ranges[ix + 1].clone();
3518        let a = &mut ranges[ix];
3519        if a.end.cmp(&b.start, buffer).is_gt() {
3520            if a.end.cmp(&b.end, buffer).is_lt() {
3521                a.end = b.end;
3522            }
3523            ranges.remove(ix + 1);
3524        } else {
3525            ix += 1;
3526        }
3527    }
3528}
3529
3530#[cfg(test)]
3531mod tests {
3532    use super::*;
3533    use futures::stream::{self};
3534    use gpui::{Context, TestAppContext};
3535    use indoc::indoc;
3536    use language::{
3537        language_settings, tree_sitter_rust, Buffer, Language, LanguageConfig, LanguageMatcher,
3538        Point,
3539    };
3540    use language_model::LanguageModelRegistry;
3541    use rand::prelude::*;
3542    use serde::Serialize;
3543    use settings::SettingsStore;
3544    use std::{future, sync::Arc};
3545
3546    #[derive(Serialize)]
3547    pub struct DummyCompletionRequest {
3548        pub name: String,
3549    }
3550
3551    #[gpui::test(iterations = 10)]
3552    async fn test_transform_autoindent(cx: &mut TestAppContext, mut rng: StdRng) {
3553        cx.set_global(cx.update(SettingsStore::test));
3554        cx.update(language_model::LanguageModelRegistry::test);
3555        cx.update(language_settings::init);
3556
3557        let text = indoc! {"
3558            fn main() {
3559                let x = 0;
3560                for _ in 0..10 {
3561                    x += 1;
3562                }
3563            }
3564        "};
3565        let buffer =
3566            cx.new_model(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
3567        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
3568        let range = buffer.read_with(cx, |buffer, cx| {
3569            let snapshot = buffer.snapshot(cx);
3570            snapshot.anchor_before(Point::new(1, 0))..snapshot.anchor_after(Point::new(4, 5))
3571        });
3572        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3573        let codegen = cx.new_model(|cx| {
3574            CodegenAlternative::new(
3575                buffer.clone(),
3576                range.clone(),
3577                true,
3578                None,
3579                prompt_builder,
3580                cx,
3581            )
3582        });
3583
3584        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
3585
3586        let mut new_text = concat!(
3587            "       let mut x = 0;\n",
3588            "       while x < 10 {\n",
3589            "           x += 1;\n",
3590            "       }",
3591        );
3592        while !new_text.is_empty() {
3593            let max_len = cmp::min(new_text.len(), 10);
3594            let len = rng.gen_range(1..=max_len);
3595            let (chunk, suffix) = new_text.split_at(len);
3596            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
3597            new_text = suffix;
3598            cx.background_executor.run_until_parked();
3599        }
3600        drop(chunks_tx);
3601        cx.background_executor.run_until_parked();
3602
3603        assert_eq!(
3604            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3605            indoc! {"
3606                fn main() {
3607                    let mut x = 0;
3608                    while x < 10 {
3609                        x += 1;
3610                    }
3611                }
3612            "}
3613        );
3614    }
3615
3616    #[gpui::test(iterations = 10)]
3617    async fn test_autoindent_when_generating_past_indentation(
3618        cx: &mut TestAppContext,
3619        mut rng: StdRng,
3620    ) {
3621        cx.set_global(cx.update(SettingsStore::test));
3622        cx.update(language_settings::init);
3623
3624        let text = indoc! {"
3625            fn main() {
3626                le
3627            }
3628        "};
3629        let buffer =
3630            cx.new_model(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
3631        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
3632        let range = buffer.read_with(cx, |buffer, cx| {
3633            let snapshot = buffer.snapshot(cx);
3634            snapshot.anchor_before(Point::new(1, 6))..snapshot.anchor_after(Point::new(1, 6))
3635        });
3636        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3637        let codegen = cx.new_model(|cx| {
3638            CodegenAlternative::new(
3639                buffer.clone(),
3640                range.clone(),
3641                true,
3642                None,
3643                prompt_builder,
3644                cx,
3645            )
3646        });
3647
3648        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
3649
3650        cx.background_executor.run_until_parked();
3651
3652        let mut new_text = concat!(
3653            "t mut x = 0;\n",
3654            "while x < 10 {\n",
3655            "    x += 1;\n",
3656            "}", //
3657        );
3658        while !new_text.is_empty() {
3659            let max_len = cmp::min(new_text.len(), 10);
3660            let len = rng.gen_range(1..=max_len);
3661            let (chunk, suffix) = new_text.split_at(len);
3662            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
3663            new_text = suffix;
3664            cx.background_executor.run_until_parked();
3665        }
3666        drop(chunks_tx);
3667        cx.background_executor.run_until_parked();
3668
3669        assert_eq!(
3670            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3671            indoc! {"
3672                fn main() {
3673                    let mut x = 0;
3674                    while x < 10 {
3675                        x += 1;
3676                    }
3677                }
3678            "}
3679        );
3680    }
3681
3682    #[gpui::test(iterations = 10)]
3683    async fn test_autoindent_when_generating_before_indentation(
3684        cx: &mut TestAppContext,
3685        mut rng: StdRng,
3686    ) {
3687        cx.update(LanguageModelRegistry::test);
3688        cx.set_global(cx.update(SettingsStore::test));
3689        cx.update(language_settings::init);
3690
3691        let text = concat!(
3692            "fn main() {\n",
3693            "  \n",
3694            "}\n" //
3695        );
3696        let buffer =
3697            cx.new_model(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
3698        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
3699        let range = buffer.read_with(cx, |buffer, cx| {
3700            let snapshot = buffer.snapshot(cx);
3701            snapshot.anchor_before(Point::new(1, 2))..snapshot.anchor_after(Point::new(1, 2))
3702        });
3703        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3704        let codegen = cx.new_model(|cx| {
3705            CodegenAlternative::new(
3706                buffer.clone(),
3707                range.clone(),
3708                true,
3709                None,
3710                prompt_builder,
3711                cx,
3712            )
3713        });
3714
3715        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
3716
3717        cx.background_executor.run_until_parked();
3718
3719        let mut new_text = concat!(
3720            "let mut x = 0;\n",
3721            "while x < 10 {\n",
3722            "    x += 1;\n",
3723            "}", //
3724        );
3725        while !new_text.is_empty() {
3726            let max_len = cmp::min(new_text.len(), 10);
3727            let len = rng.gen_range(1..=max_len);
3728            let (chunk, suffix) = new_text.split_at(len);
3729            chunks_tx.unbounded_send(chunk.to_string()).unwrap();
3730            new_text = suffix;
3731            cx.background_executor.run_until_parked();
3732        }
3733        drop(chunks_tx);
3734        cx.background_executor.run_until_parked();
3735
3736        assert_eq!(
3737            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3738            indoc! {"
3739                fn main() {
3740                    let mut x = 0;
3741                    while x < 10 {
3742                        x += 1;
3743                    }
3744                }
3745            "}
3746        );
3747    }
3748
3749    #[gpui::test(iterations = 10)]
3750    async fn test_autoindent_respects_tabs_in_selection(cx: &mut TestAppContext) {
3751        cx.update(LanguageModelRegistry::test);
3752        cx.set_global(cx.update(SettingsStore::test));
3753        cx.update(language_settings::init);
3754
3755        let text = indoc! {"
3756            func main() {
3757            \tx := 0
3758            \tfor i := 0; i < 10; i++ {
3759            \t\tx++
3760            \t}
3761            }
3762        "};
3763        let buffer = cx.new_model(|cx| Buffer::local(text, cx));
3764        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
3765        let range = buffer.read_with(cx, |buffer, cx| {
3766            let snapshot = buffer.snapshot(cx);
3767            snapshot.anchor_before(Point::new(0, 0))..snapshot.anchor_after(Point::new(4, 2))
3768        });
3769        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3770        let codegen = cx.new_model(|cx| {
3771            CodegenAlternative::new(
3772                buffer.clone(),
3773                range.clone(),
3774                true,
3775                None,
3776                prompt_builder,
3777                cx,
3778            )
3779        });
3780
3781        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
3782        let new_text = concat!(
3783            "func main() {\n",
3784            "\tx := 0\n",
3785            "\tfor x < 10 {\n",
3786            "\t\tx++\n",
3787            "\t}", //
3788        );
3789        chunks_tx.unbounded_send(new_text.to_string()).unwrap();
3790        drop(chunks_tx);
3791        cx.background_executor.run_until_parked();
3792
3793        assert_eq!(
3794            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3795            indoc! {"
3796                func main() {
3797                \tx := 0
3798                \tfor x < 10 {
3799                \t\tx++
3800                \t}
3801                }
3802            "}
3803        );
3804    }
3805
3806    #[gpui::test]
3807    async fn test_inactive_codegen_alternative(cx: &mut TestAppContext) {
3808        cx.update(LanguageModelRegistry::test);
3809        cx.set_global(cx.update(SettingsStore::test));
3810        cx.update(language_settings::init);
3811
3812        let text = indoc! {"
3813            fn main() {
3814                let x = 0;
3815            }
3816        "};
3817        let buffer =
3818            cx.new_model(|cx| Buffer::local(text, cx).with_language(Arc::new(rust_lang()), cx));
3819        let buffer = cx.new_model(|cx| MultiBuffer::singleton(buffer, cx));
3820        let range = buffer.read_with(cx, |buffer, cx| {
3821            let snapshot = buffer.snapshot(cx);
3822            snapshot.anchor_before(Point::new(1, 0))..snapshot.anchor_after(Point::new(1, 14))
3823        });
3824        let prompt_builder = Arc::new(PromptBuilder::new(None).unwrap());
3825        let codegen = cx.new_model(|cx| {
3826            CodegenAlternative::new(
3827                buffer.clone(),
3828                range.clone(),
3829                false,
3830                None,
3831                prompt_builder,
3832                cx,
3833            )
3834        });
3835
3836        let chunks_tx = simulate_response_stream(codegen.clone(), cx);
3837        chunks_tx
3838            .unbounded_send("let mut x = 0;\nx += 1;".to_string())
3839            .unwrap();
3840        drop(chunks_tx);
3841        cx.run_until_parked();
3842
3843        // The codegen is inactive, so the buffer doesn't get modified.
3844        assert_eq!(
3845            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3846            text
3847        );
3848
3849        // Activating the codegen applies the changes.
3850        codegen.update(cx, |codegen, cx| codegen.set_active(true, cx));
3851        assert_eq!(
3852            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3853            indoc! {"
3854                fn main() {
3855                    let mut x = 0;
3856                    x += 1;
3857                }
3858            "}
3859        );
3860
3861        // Deactivating the codegen undoes the changes.
3862        codegen.update(cx, |codegen, cx| codegen.set_active(false, cx));
3863        cx.run_until_parked();
3864        assert_eq!(
3865            buffer.read_with(cx, |buffer, cx| buffer.snapshot(cx).text()),
3866            text
3867        );
3868    }
3869
3870    #[gpui::test]
3871    async fn test_strip_invalid_spans_from_codeblock() {
3872        assert_chunks("Lorem ipsum dolor", "Lorem ipsum dolor").await;
3873        assert_chunks("```\nLorem ipsum dolor", "Lorem ipsum dolor").await;
3874        assert_chunks("```\nLorem ipsum dolor\n```", "Lorem ipsum dolor").await;
3875        assert_chunks(
3876            "```html\n```js\nLorem ipsum dolor\n```\n```",
3877            "```js\nLorem ipsum dolor\n```",
3878        )
3879        .await;
3880        assert_chunks("``\nLorem ipsum dolor\n```", "``\nLorem ipsum dolor\n```").await;
3881        assert_chunks("Lorem<|CURSOR|> ipsum", "Lorem ipsum").await;
3882        assert_chunks("Lorem ipsum", "Lorem ipsum").await;
3883        assert_chunks("```\n<|CURSOR|>Lorem ipsum\n```", "Lorem ipsum").await;
3884
3885        async fn assert_chunks(text: &str, expected_text: &str) {
3886            for chunk_size in 1..=text.len() {
3887                let actual_text = StripInvalidSpans::new(chunks(text, chunk_size))
3888                    .map(|chunk| chunk.unwrap())
3889                    .collect::<String>()
3890                    .await;
3891                assert_eq!(
3892                    actual_text, expected_text,
3893                    "failed to strip invalid spans, chunk size: {}",
3894                    chunk_size
3895                );
3896            }
3897        }
3898
3899        fn chunks(text: &str, size: usize) -> impl Stream<Item = Result<String>> {
3900            stream::iter(
3901                text.chars()
3902                    .collect::<Vec<_>>()
3903                    .chunks(size)
3904                    .map(|chunk| Ok(chunk.iter().collect::<String>()))
3905                    .collect::<Vec<_>>(),
3906            )
3907        }
3908    }
3909
3910    fn simulate_response_stream(
3911        codegen: Model<CodegenAlternative>,
3912        cx: &mut TestAppContext,
3913    ) -> mpsc::UnboundedSender<String> {
3914        let (chunks_tx, chunks_rx) = mpsc::unbounded();
3915        codegen.update(cx, |codegen, cx| {
3916            codegen.handle_stream(
3917                String::new(),
3918                String::new(),
3919                None,
3920                future::ready(Ok(LanguageModelTextStream {
3921                    message_id: None,
3922                    stream: chunks_rx.map(Ok).boxed(),
3923                })),
3924                cx,
3925            );
3926        });
3927        chunks_tx
3928    }
3929
3930    fn rust_lang() -> Language {
3931        Language::new(
3932            LanguageConfig {
3933                name: "Rust".into(),
3934                matcher: LanguageMatcher {
3935                    path_suffixes: vec!["rs".to_string()],
3936                    ..Default::default()
3937                },
3938                ..Default::default()
3939            },
3940            Some(tree_sitter_rust::LANGUAGE.into()),
3941        )
3942        .with_indents_query(
3943            r#"
3944            (call_expression) @indent
3945            (field_expression) @indent
3946            (_ "(" ")" @end) @indent
3947            (_ "{" "}" @end) @indent
3948            "#,
3949        )
3950        .unwrap()
3951    }
3952}