inline_prompt_editor.rs

   1use agent::HistoryStore;
   2use collections::{HashMap, VecDeque};
   3use editor::actions::Paste;
   4use editor::code_context_menus::CodeContextMenu;
   5use editor::display_map::{CreaseId, EditorMargins};
   6use editor::{AnchorRangeExt as _, MultiBufferOffset, ToOffset as _};
   7use editor::{
   8    ContextMenuOptions, Editor, EditorElement, EditorEvent, EditorMode, EditorStyle, MultiBuffer,
   9    actions::{MoveDown, MoveUp},
  10};
  11use feature_flags::{FeatureFlagAppExt, InlineAssistantUseToolFeatureFlag};
  12use fs::Fs;
  13use gpui::{
  14    AnyElement, App, ClipboardItem, Context, Entity, EventEmitter, FocusHandle, Focusable,
  15    Subscription, TextStyle, TextStyleRefinement, WeakEntity, Window, actions,
  16};
  17use language_model::{LanguageModel, LanguageModelRegistry};
  18use markdown::{HeadingLevelStyles, Markdown, MarkdownElement, MarkdownStyle};
  19use parking_lot::Mutex;
  20use project::Project;
  21use prompt_store::PromptStore;
  22use settings::Settings;
  23use std::cmp;
  24use std::ops::Range;
  25use std::rc::Rc;
  26use std::sync::Arc;
  27use theme::ThemeSettings;
  28use ui::utils::WithRemSize;
  29use ui::{IconButtonShape, KeyBinding, PopoverMenuHandle, Tooltip, prelude::*};
  30use uuid::Uuid;
  31use workspace::notifications::NotificationId;
  32use workspace::{Toast, Workspace};
  33use zed_actions::agent::ToggleModelSelector;
  34
  35use crate::agent_model_selector::AgentModelSelector;
  36use crate::buffer_codegen::BufferCodegen;
  37use crate::completion_provider::{
  38    PromptCompletionProvider, PromptCompletionProviderDelegate, PromptContextType,
  39};
  40use crate::mention_set::paste_images_as_context;
  41use crate::mention_set::{MentionSet, crease_for_mention};
  42use crate::terminal_codegen::TerminalCodegen;
  43use crate::{CycleNextInlineAssist, CyclePreviousInlineAssist, ModelUsageContext};
  44
  45actions!(inline_assistant, [ThumbsUpResult, ThumbsDownResult]);
  46
  47enum CompletionState {
  48    Pending,
  49    Generated { completion_text: Option<String> },
  50    Rated,
  51}
  52
  53struct SessionState {
  54    session_id: Uuid,
  55    completion: CompletionState,
  56}
  57
  58pub struct PromptEditor<T> {
  59    pub editor: Entity<Editor>,
  60    mode: PromptEditorMode,
  61    mention_set: Entity<MentionSet>,
  62    history_store: Entity<HistoryStore>,
  63    prompt_store: Option<Entity<PromptStore>>,
  64    workspace: WeakEntity<Workspace>,
  65    model_selector: Entity<AgentModelSelector>,
  66    edited_since_done: bool,
  67    prompt_history: VecDeque<String>,
  68    prompt_history_ix: Option<usize>,
  69    pending_prompt: String,
  70    _codegen_subscription: Subscription,
  71    editor_subscriptions: Vec<Subscription>,
  72    show_rate_limit_notice: bool,
  73    session_state: SessionState,
  74    _phantom: std::marker::PhantomData<T>,
  75}
  76
  77impl<T: 'static> EventEmitter<PromptEditorEvent> for PromptEditor<T> {}
  78
  79impl<T: 'static> Render for PromptEditor<T> {
  80    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
  81        let ui_font_size = ThemeSettings::get_global(cx).ui_font_size(cx);
  82        let mut buttons = Vec::new();
  83
  84        const RIGHT_PADDING: Pixels = px(9.);
  85
  86        let (left_gutter_width, right_padding, explanation) = match &self.mode {
  87            PromptEditorMode::Buffer {
  88                id: _,
  89                codegen,
  90                editor_margins,
  91            } => {
  92                let codegen = codegen.read(cx);
  93
  94                if codegen.alternative_count(cx) > 1 {
  95                    buttons.push(self.render_cycle_controls(codegen, cx));
  96                }
  97
  98                let editor_margins = editor_margins.lock();
  99                let gutter = editor_margins.gutter;
 100
 101                let left_gutter_width = gutter.full_width() + (gutter.margin / 2.0);
 102                let right_padding = editor_margins.right + RIGHT_PADDING;
 103
 104                let explanation = codegen
 105                    .active_alternative()
 106                    .read(cx)
 107                    .model_explanation
 108                    .clone();
 109
 110                (left_gutter_width, right_padding, explanation)
 111            }
 112            PromptEditorMode::Terminal { .. } => {
 113                // Give the equivalent of the same left-padding that we're using on the right
 114                (Pixels::from(40.0), Pixels::from(24.), None)
 115            }
 116        };
 117
 118        let bottom_padding = match &self.mode {
 119            PromptEditorMode::Buffer { .. } => rems_from_px(2.0),
 120            PromptEditorMode::Terminal { .. } => rems_from_px(4.0),
 121        };
 122
 123        buttons.extend(self.render_buttons(window, cx));
 124
 125        let menu_visible = self.is_completions_menu_visible(cx);
 126        let add_context_button = IconButton::new("add-context", IconName::AtSign)
 127            .icon_size(IconSize::Small)
 128            .icon_color(Color::Muted)
 129            .when(!menu_visible, |this| {
 130                this.tooltip(move |_window, cx| {
 131                    Tooltip::with_meta("Add Context", None, "Or type @ to include context", cx)
 132                })
 133            })
 134            .on_click(cx.listener(move |this, _, window, cx| {
 135                this.trigger_completion_menu(window, cx);
 136            }));
 137
 138        let markdown = window.use_state(cx, |_, cx| Markdown::new("".into(), None, None, cx));
 139
 140        if let Some(explanation) = &explanation {
 141            markdown.update(cx, |markdown, cx| {
 142                markdown.reset(explanation.clone(), cx);
 143            });
 144        }
 145
 146        let explanation_label = self
 147            .render_markdown(markdown, markdown_style(window, cx))
 148            .into_any_element();
 149
 150        v_flex()
 151            .key_context("PromptEditor")
 152            .capture_action(cx.listener(Self::paste))
 153            .block_mouse_except_scroll()
 154            .size_full()
 155            .pt_0p5()
 156            .pb(bottom_padding)
 157            .pr(right_padding)
 158            .gap_0p5()
 159            .justify_center()
 160            .border_y_1()
 161            .border_color(cx.theme().colors().border)
 162            .bg(cx.theme().colors().editor_background)
 163            .child(
 164                h_flex()
 165                    .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
 166                        this.model_selector
 167                            .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
 168                    }))
 169                    .on_action(cx.listener(Self::confirm))
 170                    .on_action(cx.listener(Self::cancel))
 171                    .on_action(cx.listener(Self::move_up))
 172                    .on_action(cx.listener(Self::move_down))
 173                    .on_action(cx.listener(Self::thumbs_up))
 174                    .on_action(cx.listener(Self::thumbs_down))
 175                    .capture_action(cx.listener(Self::cycle_prev))
 176                    .capture_action(cx.listener(Self::cycle_next))
 177                    .child(
 178                        WithRemSize::new(ui_font_size)
 179                            .h_full()
 180                            .w(left_gutter_width)
 181                            .flex()
 182                            .flex_row()
 183                            .flex_shrink_0()
 184                            .items_center()
 185                            .justify_center()
 186                            .gap_1()
 187                            .child(self.render_close_button(cx))
 188                            .map(|el| {
 189                                let CodegenStatus::Error(error) = self.codegen_status(cx) else {
 190                                    return el;
 191                                };
 192
 193                                let error_message = SharedString::from(error.to_string());
 194                                el.child(
 195                                    div()
 196                                        .id("error")
 197                                        .tooltip(Tooltip::text(error_message))
 198                                        .child(
 199                                            Icon::new(IconName::XCircle)
 200                                                .size(IconSize::Small)
 201                                                .color(Color::Error),
 202                                        ),
 203                                )
 204                            }),
 205                    )
 206                    .child(
 207                        h_flex()
 208                            .w_full()
 209                            .justify_between()
 210                            .child(div().flex_1().child(self.render_editor(window, cx)))
 211                            .child(
 212                                WithRemSize::new(ui_font_size)
 213                                    .flex()
 214                                    .flex_row()
 215                                    .items_center()
 216                                    .gap_1()
 217                                    .child(add_context_button)
 218                                    .child(self.model_selector.clone())
 219                                    .children(buttons),
 220                            ),
 221                    ),
 222            )
 223            .when_some(explanation, |this, _| {
 224                this.child(
 225                    h_flex()
 226                        .size_full()
 227                        .justify_center()
 228                        .child(div().w(left_gutter_width + px(6.)))
 229                        .child(
 230                            div()
 231                                .size_full()
 232                                .min_w_0()
 233                                .pt(rems_from_px(3.))
 234                                .pl_0p5()
 235                                .flex_1()
 236                                .border_t_1()
 237                                .border_color(cx.theme().colors().border_variant)
 238                                .child(explanation_label),
 239                        ),
 240                )
 241            })
 242    }
 243}
 244
 245fn markdown_style(window: &Window, cx: &App) -> MarkdownStyle {
 246    let theme_settings = ThemeSettings::get_global(cx);
 247    let colors = cx.theme().colors();
 248    let mut text_style = window.text_style();
 249
 250    text_style.refine(&TextStyleRefinement {
 251        font_family: Some(theme_settings.ui_font.family.clone()),
 252        color: Some(colors.text),
 253        ..Default::default()
 254    });
 255
 256    MarkdownStyle {
 257        base_text_style: text_style.clone(),
 258        syntax: cx.theme().syntax().clone(),
 259        selection_background_color: colors.element_selection_background,
 260        heading_level_styles: Some(HeadingLevelStyles {
 261            h1: Some(TextStyleRefinement {
 262                font_size: Some(rems(1.15).into()),
 263                ..Default::default()
 264            }),
 265            h2: Some(TextStyleRefinement {
 266                font_size: Some(rems(1.1).into()),
 267                ..Default::default()
 268            }),
 269            h3: Some(TextStyleRefinement {
 270                font_size: Some(rems(1.05).into()),
 271                ..Default::default()
 272            }),
 273            h4: Some(TextStyleRefinement {
 274                font_size: Some(rems(1.).into()),
 275                ..Default::default()
 276            }),
 277            h5: Some(TextStyleRefinement {
 278                font_size: Some(rems(0.95).into()),
 279                ..Default::default()
 280            }),
 281            h6: Some(TextStyleRefinement {
 282                font_size: Some(rems(0.875).into()),
 283                ..Default::default()
 284            }),
 285        }),
 286        inline_code: TextStyleRefinement {
 287            font_family: Some(theme_settings.buffer_font.family.clone()),
 288            font_fallbacks: theme_settings.buffer_font.fallbacks.clone(),
 289            font_features: Some(theme_settings.buffer_font.features.clone()),
 290            background_color: Some(colors.editor_foreground.opacity(0.08)),
 291            ..Default::default()
 292        },
 293        ..Default::default()
 294    }
 295}
 296
 297impl<T: 'static> Focusable for PromptEditor<T> {
 298    fn focus_handle(&self, cx: &App) -> FocusHandle {
 299        self.editor.focus_handle(cx)
 300    }
 301}
 302
 303impl<T: 'static> PromptEditor<T> {
 304    const MAX_LINES: u8 = 8;
 305
 306    fn codegen_status<'a>(&'a self, cx: &'a App) -> &'a CodegenStatus {
 307        match &self.mode {
 308            PromptEditorMode::Buffer { codegen, .. } => codegen.read(cx).status(cx),
 309            PromptEditorMode::Terminal { codegen, .. } => &codegen.read(cx).status,
 310        }
 311    }
 312
 313    fn subscribe_to_editor(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 314        self.editor_subscriptions.clear();
 315        self.editor_subscriptions.push(cx.subscribe_in(
 316            &self.editor,
 317            window,
 318            Self::handle_prompt_editor_events,
 319        ));
 320    }
 321
 322    fn assign_completion_provider(&mut self, cx: &mut Context<Self>) {
 323        self.editor.update(cx, |editor, cx| {
 324            editor.set_completion_provider(Some(Rc::new(PromptCompletionProvider::new(
 325                PromptEditorCompletionProviderDelegate,
 326                cx.weak_entity(),
 327                self.mention_set.clone(),
 328                self.history_store.clone(),
 329                self.prompt_store.clone(),
 330                self.workspace.clone(),
 331            ))));
 332        });
 333    }
 334
 335    pub fn set_show_cursor_when_unfocused(
 336        &mut self,
 337        show_cursor_when_unfocused: bool,
 338        cx: &mut Context<Self>,
 339    ) {
 340        self.editor.update(cx, |editor, cx| {
 341            editor.set_show_cursor_when_unfocused(show_cursor_when_unfocused, cx)
 342        });
 343    }
 344
 345    pub fn unlink(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 346        let prompt = self.prompt(cx);
 347        let existing_creases = self.editor.update(cx, |editor, cx| {
 348            extract_message_creases(editor, &self.mention_set, window, cx)
 349        });
 350        let focus = self.editor.focus_handle(cx).contains_focused(window, cx);
 351        let mut creases = vec![];
 352        self.editor = cx.new(|cx| {
 353            let mut editor = Editor::auto_height(1, Self::MAX_LINES as usize, window, cx);
 354            editor.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
 355            editor.set_placeholder_text("Add a prompt…", window, cx);
 356            editor.set_text(prompt, window, cx);
 357            creases = insert_message_creases(&mut editor, &existing_creases, window, cx);
 358
 359            if focus {
 360                window.focus(&editor.focus_handle(cx));
 361            }
 362            editor
 363        });
 364
 365        self.mention_set.update(cx, |mention_set, _cx| {
 366            debug_assert_eq!(
 367                creases.len(),
 368                mention_set.creases().len(),
 369                "Missing creases"
 370            );
 371
 372            let mentions = mention_set
 373                .clear()
 374                .zip(creases)
 375                .map(|((_, value), id)| (id, value))
 376                .collect::<HashMap<_, _>>();
 377            mention_set.set_mentions(mentions);
 378        });
 379
 380        self.assign_completion_provider(cx);
 381        self.subscribe_to_editor(window, cx);
 382    }
 383
 384    pub fn placeholder_text(mode: &PromptEditorMode, window: &mut Window, cx: &mut App) -> String {
 385        let action = match mode {
 386            PromptEditorMode::Buffer { codegen, .. } => {
 387                if codegen.read(cx).is_insertion {
 388                    "Generate"
 389                } else {
 390                    "Transform"
 391                }
 392            }
 393            PromptEditorMode::Terminal { .. } => "Generate",
 394        };
 395
 396        let agent_panel_keybinding =
 397            ui::text_for_action(&zed_actions::assistant::ToggleFocus, window, cx)
 398                .map(|keybinding| format!("{keybinding} to chat"))
 399                .unwrap_or_default();
 400
 401        format!("{action}… ({agent_panel_keybinding} ― ↓↑ for history — @ to include context)")
 402    }
 403
 404    pub fn prompt(&self, cx: &App) -> String {
 405        self.editor.read(cx).text(cx)
 406    }
 407
 408    fn paste(&mut self, _: &Paste, window: &mut Window, cx: &mut Context<Self>) {
 409        if inline_assistant_model_supports_images(cx)
 410            && let Some(task) =
 411                paste_images_as_context(self.editor.clone(), self.mention_set.clone(), window, cx)
 412        {
 413            task.detach();
 414        }
 415    }
 416
 417    fn handle_prompt_editor_events(
 418        &mut self,
 419        editor: &Entity<Editor>,
 420        event: &EditorEvent,
 421        window: &mut Window,
 422        cx: &mut Context<Self>,
 423    ) {
 424        match event {
 425            EditorEvent::Edited { .. } => {
 426                let snapshot = editor.update(cx, |editor, cx| editor.snapshot(window, cx));
 427
 428                self.mention_set
 429                    .update(cx, |mention_set, _cx| mention_set.remove_invalid(&snapshot));
 430
 431                if let Some(workspace) = window.root::<Workspace>().flatten() {
 432                    workspace.update(cx, |workspace, cx| {
 433                        let is_via_ssh = workspace.project().read(cx).is_via_remote_server();
 434
 435                        workspace
 436                            .client()
 437                            .telemetry()
 438                            .log_edit_event("inline assist", is_via_ssh);
 439                    });
 440                }
 441                let prompt = snapshot.text();
 442                if self
 443                    .prompt_history_ix
 444                    .is_none_or(|ix| self.prompt_history[ix] != prompt)
 445                {
 446                    self.prompt_history_ix.take();
 447                    self.pending_prompt = prompt;
 448                }
 449
 450                self.edited_since_done = true;
 451                self.session_state.completion = CompletionState::Pending;
 452                cx.notify();
 453            }
 454            EditorEvent::Blurred => {
 455                if self.show_rate_limit_notice {
 456                    self.show_rate_limit_notice = false;
 457                    cx.notify();
 458                }
 459            }
 460            _ => {}
 461        }
 462    }
 463
 464    pub fn is_completions_menu_visible(&self, cx: &App) -> bool {
 465        self.editor
 466            .read(cx)
 467            .context_menu()
 468            .borrow()
 469            .as_ref()
 470            .is_some_and(|menu| matches!(menu, CodeContextMenu::Completions(_)) && menu.visible())
 471    }
 472
 473    pub fn trigger_completion_menu(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 474        self.editor.update(cx, |editor, cx| {
 475            let menu_is_open = editor.context_menu().borrow().as_ref().is_some_and(|menu| {
 476                matches!(menu, CodeContextMenu::Completions(_)) && menu.visible()
 477            });
 478
 479            let has_at_sign = {
 480                let snapshot = editor.display_snapshot(cx);
 481                let cursor = editor.selections.newest::<text::Point>(&snapshot).head();
 482                let offset = cursor.to_offset(&snapshot);
 483                if offset.0 > 0 {
 484                    snapshot
 485                        .buffer_snapshot()
 486                        .reversed_chars_at(offset)
 487                        .next()
 488                        .map(|sign| sign == '@')
 489                        .unwrap_or(false)
 490                } else {
 491                    false
 492                }
 493            };
 494
 495            if menu_is_open && has_at_sign {
 496                return;
 497            }
 498
 499            editor.insert("@", window, cx);
 500            editor.show_completions(&editor::actions::ShowCompletions, window, cx);
 501        });
 502    }
 503
 504    fn cancel(
 505        &mut self,
 506        _: &editor::actions::Cancel,
 507        _window: &mut Window,
 508        cx: &mut Context<Self>,
 509    ) {
 510        match self.codegen_status(cx) {
 511            CodegenStatus::Idle | CodegenStatus::Done | CodegenStatus::Error(_) => {
 512                cx.emit(PromptEditorEvent::CancelRequested);
 513            }
 514            CodegenStatus::Pending => {
 515                cx.emit(PromptEditorEvent::StopRequested);
 516            }
 517        }
 518    }
 519
 520    fn confirm(&mut self, _: &menu::Confirm, _window: &mut Window, cx: &mut Context<Self>) {
 521        match self.codegen_status(cx) {
 522            CodegenStatus::Idle => {
 523                self.fire_started_telemetry(cx);
 524                cx.emit(PromptEditorEvent::StartRequested);
 525            }
 526            CodegenStatus::Pending => {}
 527            CodegenStatus::Done => {
 528                if self.edited_since_done {
 529                    self.fire_started_telemetry(cx);
 530                    cx.emit(PromptEditorEvent::StartRequested);
 531                } else {
 532                    cx.emit(PromptEditorEvent::ConfirmRequested { execute: false });
 533                }
 534            }
 535            CodegenStatus::Error(_) => {
 536                self.fire_started_telemetry(cx);
 537                cx.emit(PromptEditorEvent::StartRequested);
 538            }
 539        }
 540    }
 541
 542    fn fire_started_telemetry(&self, cx: &Context<Self>) {
 543        let Some(model) = LanguageModelRegistry::read_global(cx).inline_assistant_model() else {
 544            return;
 545        };
 546
 547        let model_telemetry_id = model.model.telemetry_id();
 548        let model_provider_id = model.provider.id().to_string();
 549
 550        let (kind, language_name) = match &self.mode {
 551            PromptEditorMode::Buffer { codegen, .. } => {
 552                let codegen = codegen.read(cx);
 553                (
 554                    "inline",
 555                    codegen.language_name(cx).map(|name| name.to_string()),
 556                )
 557            }
 558            PromptEditorMode::Terminal { .. } => ("inline_terminal", None),
 559        };
 560
 561        telemetry::event!(
 562            "Assistant Started",
 563            session_id = self.session_state.session_id.to_string(),
 564            kind = kind,
 565            phase = "started",
 566            model = model_telemetry_id,
 567            model_provider = model_provider_id,
 568            language_name = language_name,
 569        );
 570    }
 571
 572    fn thumbs_up(&mut self, _: &ThumbsUpResult, _window: &mut Window, cx: &mut Context<Self>) {
 573        match &self.session_state.completion {
 574            CompletionState::Pending => {
 575                self.toast("Can't rate, still generating...", None, cx);
 576                return;
 577            }
 578            CompletionState::Rated => {
 579                self.toast(
 580                    "Already rated this completion",
 581                    Some(self.session_state.session_id),
 582                    cx,
 583                );
 584                return;
 585            }
 586            CompletionState::Generated { completion_text } => {
 587                let model_info = self.model_selector.read(cx).active_model(cx);
 588                let model_id = {
 589                    let Some(configured_model) = model_info else {
 590                        self.toast("No configured model", None, cx);
 591                        return;
 592                    };
 593                    configured_model.model.telemetry_id()
 594                };
 595
 596                let selected_text = match &self.mode {
 597                    PromptEditorMode::Buffer { codegen, .. } => {
 598                        codegen.read(cx).selected_text(cx).map(|s| s.to_string())
 599                    }
 600                    PromptEditorMode::Terminal { .. } => None,
 601                };
 602
 603                let prompt = self.editor.read(cx).text(cx);
 604
 605                let kind = match &self.mode {
 606                    PromptEditorMode::Buffer { .. } => "inline",
 607                    PromptEditorMode::Terminal { .. } => "inline_terminal",
 608                };
 609
 610                telemetry::event!(
 611                    "Inline Assistant Rated",
 612                    rating = "positive",
 613                    session_id = self.session_state.session_id.to_string(),
 614                    kind = kind,
 615                    model = model_id,
 616                    prompt = prompt,
 617                    completion = completion_text,
 618                    selected_text = selected_text,
 619                );
 620
 621                self.session_state.completion = CompletionState::Rated;
 622
 623                cx.notify();
 624            }
 625        }
 626    }
 627
 628    fn thumbs_down(&mut self, _: &ThumbsDownResult, _window: &mut Window, cx: &mut Context<Self>) {
 629        match &self.session_state.completion {
 630            CompletionState::Pending => {
 631                self.toast("Can't rate, still generating...", None, cx);
 632                return;
 633            }
 634            CompletionState::Rated => {
 635                self.toast(
 636                    "Already rated this completion",
 637                    Some(self.session_state.session_id),
 638                    cx,
 639                );
 640                return;
 641            }
 642            CompletionState::Generated { completion_text } => {
 643                let model_info = self.model_selector.read(cx).active_model(cx);
 644                let model_telemetry_id = {
 645                    let Some(configured_model) = model_info else {
 646                        self.toast("No configured model", None, cx);
 647                        return;
 648                    };
 649                    configured_model.model.telemetry_id()
 650                };
 651
 652                let selected_text = match &self.mode {
 653                    PromptEditorMode::Buffer { codegen, .. } => {
 654                        codegen.read(cx).selected_text(cx).map(|s| s.to_string())
 655                    }
 656                    PromptEditorMode::Terminal { .. } => None,
 657                };
 658
 659                let prompt = self.editor.read(cx).text(cx);
 660
 661                let kind = match &self.mode {
 662                    PromptEditorMode::Buffer { .. } => "inline",
 663                    PromptEditorMode::Terminal { .. } => "inline_terminal",
 664                };
 665
 666                telemetry::event!(
 667                    "Inline Assistant Rated",
 668                    rating = "negative",
 669                    session_id = self.session_state.session_id.to_string(),
 670                    kind = kind,
 671                    model = model_telemetry_id,
 672                    prompt = prompt,
 673                    completion = completion_text,
 674                    selected_text = selected_text,
 675                );
 676
 677                self.session_state.completion = CompletionState::Rated;
 678
 679                cx.notify();
 680            }
 681        }
 682    }
 683
 684    fn toast(&mut self, msg: &str, uuid: Option<Uuid>, cx: &mut Context<'_, PromptEditor<T>>) {
 685        self.workspace
 686            .update(cx, |workspace, cx| {
 687                enum InlinePromptRating {}
 688                workspace.show_toast(
 689                    {
 690                        let mut toast = Toast::new(
 691                            NotificationId::unique::<InlinePromptRating>(),
 692                            msg.to_string(),
 693                        )
 694                        .autohide();
 695
 696                        if let Some(uuid) = uuid {
 697                            toast = toast.on_click("Click to copy rating ID", move |_, cx| {
 698                                cx.write_to_clipboard(ClipboardItem::new_string(uuid.to_string()));
 699                            });
 700                        };
 701
 702                        toast
 703                    },
 704                    cx,
 705                );
 706            })
 707            .ok();
 708    }
 709
 710    fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 711        if let Some(ix) = self.prompt_history_ix {
 712            if ix > 0 {
 713                self.prompt_history_ix = Some(ix - 1);
 714                let prompt = self.prompt_history[ix - 1].as_str();
 715                self.editor.update(cx, |editor, cx| {
 716                    editor.set_text(prompt, window, cx);
 717                    editor.move_to_beginning(&Default::default(), window, cx);
 718                });
 719            }
 720        } else if !self.prompt_history.is_empty() {
 721            self.prompt_history_ix = Some(self.prompt_history.len() - 1);
 722            let prompt = self.prompt_history[self.prompt_history.len() - 1].as_str();
 723            self.editor.update(cx, |editor, cx| {
 724                editor.set_text(prompt, window, cx);
 725                editor.move_to_beginning(&Default::default(), window, cx);
 726            });
 727        }
 728    }
 729
 730    fn move_down(&mut self, _: &MoveDown, window: &mut Window, cx: &mut Context<Self>) {
 731        if let Some(ix) = self.prompt_history_ix {
 732            if ix < self.prompt_history.len() - 1 {
 733                self.prompt_history_ix = Some(ix + 1);
 734                let prompt = self.prompt_history[ix + 1].as_str();
 735                self.editor.update(cx, |editor, cx| {
 736                    editor.set_text(prompt, window, cx);
 737                    editor.move_to_end(&Default::default(), window, cx)
 738                });
 739            } else {
 740                self.prompt_history_ix = None;
 741                let prompt = self.pending_prompt.as_str();
 742                self.editor.update(cx, |editor, cx| {
 743                    editor.set_text(prompt, window, cx);
 744                    editor.move_to_end(&Default::default(), window, cx)
 745                });
 746            }
 747        }
 748    }
 749
 750    fn render_buttons(&self, _window: &mut Window, cx: &mut Context<Self>) -> Vec<AnyElement> {
 751        let mode = match &self.mode {
 752            PromptEditorMode::Buffer { codegen, .. } => {
 753                let codegen = codegen.read(cx);
 754                if codegen.is_insertion {
 755                    GenerationMode::Generate
 756                } else {
 757                    GenerationMode::Transform
 758                }
 759            }
 760            PromptEditorMode::Terminal { .. } => GenerationMode::Generate,
 761        };
 762
 763        let codegen_status = self.codegen_status(cx);
 764
 765        match codegen_status {
 766            CodegenStatus::Idle => {
 767                vec![
 768                    Button::new("start", mode.start_label())
 769                        .label_size(LabelSize::Small)
 770                        .icon(IconName::Return)
 771                        .icon_size(IconSize::XSmall)
 772                        .icon_color(Color::Muted)
 773                        .on_click(
 774                            cx.listener(|_, _, _, cx| cx.emit(PromptEditorEvent::StartRequested)),
 775                        )
 776                        .into_any_element(),
 777                ]
 778            }
 779            CodegenStatus::Pending => vec![
 780                IconButton::new("stop", IconName::Stop)
 781                    .icon_color(Color::Error)
 782                    .shape(IconButtonShape::Square)
 783                    .tooltip(move |_window, cx| {
 784                        Tooltip::with_meta(
 785                            mode.tooltip_interrupt(),
 786                            Some(&menu::Cancel),
 787                            "Changes won't be discarded",
 788                            cx,
 789                        )
 790                    })
 791                    .on_click(cx.listener(|_, _, _, cx| cx.emit(PromptEditorEvent::StopRequested)))
 792                    .into_any_element(),
 793            ],
 794            CodegenStatus::Done | CodegenStatus::Error(_) => {
 795                let has_error = matches!(codegen_status, CodegenStatus::Error(_));
 796                if has_error || self.edited_since_done {
 797                    vec![
 798                        IconButton::new("restart", IconName::RotateCw)
 799                            .icon_color(Color::Info)
 800                            .shape(IconButtonShape::Square)
 801                            .tooltip(move |_window, cx| {
 802                                Tooltip::with_meta(
 803                                    mode.tooltip_restart(),
 804                                    Some(&menu::Confirm),
 805                                    "Changes will be discarded",
 806                                    cx,
 807                                )
 808                            })
 809                            .on_click(cx.listener(|_, _, _, cx| {
 810                                cx.emit(PromptEditorEvent::StartRequested);
 811                            }))
 812                            .into_any_element(),
 813                    ]
 814                } else {
 815                    let show_rating_buttons = cx.has_flag::<InlineAssistantUseToolFeatureFlag>();
 816                    let rated = matches!(self.session_state.completion, CompletionState::Rated);
 817
 818                    let accept = IconButton::new("accept", IconName::Check)
 819                        .icon_color(Color::Info)
 820                        .shape(IconButtonShape::Square)
 821                        .tooltip(move |_window, cx| {
 822                            Tooltip::for_action(mode.tooltip_accept(), &menu::Confirm, cx)
 823                        })
 824                        .on_click(cx.listener(|_, _, _, cx| {
 825                            cx.emit(PromptEditorEvent::ConfirmRequested { execute: false });
 826                        }))
 827                        .into_any_element();
 828
 829                    let mut buttons = Vec::new();
 830
 831                    if show_rating_buttons {
 832                        buttons.push(
 833                            IconButton::new("thumbs-down", IconName::ThumbsDown)
 834                                .icon_color(if rated { Color::Muted } else { Color::Default })
 835                                .shape(IconButtonShape::Square)
 836                                .disabled(rated)
 837                                .tooltip(Tooltip::text("Bad result"))
 838                                .on_click(cx.listener(|this, _, window, cx| {
 839                                    this.thumbs_down(&ThumbsDownResult, window, cx);
 840                                }))
 841                                .into_any_element(),
 842                        );
 843
 844                        buttons.push(
 845                            IconButton::new("thumbs-up", IconName::ThumbsUp)
 846                                .icon_color(if rated { Color::Muted } else { Color::Default })
 847                                .shape(IconButtonShape::Square)
 848                                .disabled(rated)
 849                                .tooltip(Tooltip::text("Good result"))
 850                                .on_click(cx.listener(|this, _, window, cx| {
 851                                    this.thumbs_up(&ThumbsUpResult, window, cx);
 852                                }))
 853                                .into_any_element(),
 854                        );
 855                    }
 856
 857                    buttons.push(accept);
 858
 859                    match &self.mode {
 860                        PromptEditorMode::Terminal { .. } => {
 861                            buttons.push(
 862                                IconButton::new("confirm", IconName::PlayFilled)
 863                                    .icon_color(Color::Info)
 864                                    .shape(IconButtonShape::Square)
 865                                    .tooltip(|_window, cx| {
 866                                        Tooltip::for_action(
 867                                            "Execute Generated Command",
 868                                            &menu::SecondaryConfirm,
 869                                            cx,
 870                                        )
 871                                    })
 872                                    .on_click(cx.listener(|_, _, _, cx| {
 873                                        cx.emit(PromptEditorEvent::ConfirmRequested {
 874                                            execute: true,
 875                                        });
 876                                    }))
 877                                    .into_any_element(),
 878                            );
 879                            buttons
 880                        }
 881                        PromptEditorMode::Buffer { .. } => buttons,
 882                    }
 883                }
 884            }
 885        }
 886    }
 887
 888    fn cycle_prev(
 889        &mut self,
 890        _: &CyclePreviousInlineAssist,
 891        _: &mut Window,
 892        cx: &mut Context<Self>,
 893    ) {
 894        match &self.mode {
 895            PromptEditorMode::Buffer { codegen, .. } => {
 896                codegen.update(cx, |codegen, cx| codegen.cycle_prev(cx));
 897            }
 898            PromptEditorMode::Terminal { .. } => {
 899                // no cycle buttons in terminal mode
 900            }
 901        }
 902    }
 903
 904    fn cycle_next(&mut self, _: &CycleNextInlineAssist, _: &mut Window, cx: &mut Context<Self>) {
 905        match &self.mode {
 906            PromptEditorMode::Buffer { codegen, .. } => {
 907                codegen.update(cx, |codegen, cx| codegen.cycle_next(cx));
 908            }
 909            PromptEditorMode::Terminal { .. } => {
 910                // no cycle buttons in terminal mode
 911            }
 912        }
 913    }
 914
 915    fn render_close_button(&self, cx: &mut Context<Self>) -> AnyElement {
 916        IconButton::new("cancel", IconName::Close)
 917            .icon_color(Color::Muted)
 918            .shape(IconButtonShape::Square)
 919            .tooltip(Tooltip::text("Close Assistant"))
 920            .on_click(cx.listener(|_, _, _, cx| cx.emit(PromptEditorEvent::CancelRequested)))
 921            .into_any_element()
 922    }
 923
 924    fn render_cycle_controls(&self, codegen: &BufferCodegen, cx: &Context<Self>) -> AnyElement {
 925        let disabled = matches!(codegen.status(cx), CodegenStatus::Idle);
 926
 927        let model_registry = LanguageModelRegistry::read_global(cx);
 928        let default_model = model_registry.default_model().map(|default| default.model);
 929        let alternative_models = model_registry.inline_alternative_models();
 930
 931        let get_model_name = |index: usize| -> String {
 932            let name = |model: &Arc<dyn LanguageModel>| model.name().0.to_string();
 933
 934            match index {
 935                0 => default_model.as_ref().map_or_else(String::new, name),
 936                index if index <= alternative_models.len() => alternative_models
 937                    .get(index - 1)
 938                    .map_or_else(String::new, name),
 939                _ => String::new(),
 940            }
 941        };
 942
 943        let total_models = alternative_models.len() + 1;
 944
 945        if total_models <= 1 {
 946            return div().into_any_element();
 947        }
 948
 949        let current_index = codegen.active_alternative;
 950        let prev_index = (current_index + total_models - 1) % total_models;
 951        let next_index = (current_index + 1) % total_models;
 952
 953        let prev_model_name = get_model_name(prev_index);
 954        let next_model_name = get_model_name(next_index);
 955
 956        h_flex()
 957            .child(
 958                IconButton::new("previous", IconName::ChevronLeft)
 959                    .icon_color(Color::Muted)
 960                    .disabled(disabled || current_index == 0)
 961                    .shape(IconButtonShape::Square)
 962                    .tooltip({
 963                        let focus_handle = self.editor.focus_handle(cx);
 964                        move |_window, cx| {
 965                            cx.new(|cx| {
 966                                let mut tooltip = Tooltip::new("Previous Alternative").key_binding(
 967                                    KeyBinding::for_action_in(
 968                                        &CyclePreviousInlineAssist,
 969                                        &focus_handle,
 970                                        cx,
 971                                    ),
 972                                );
 973                                if !disabled && current_index != 0 {
 974                                    tooltip = tooltip.meta(prev_model_name.clone());
 975                                }
 976                                tooltip
 977                            })
 978                            .into()
 979                        }
 980                    })
 981                    .on_click(cx.listener(|this, _, window, cx| {
 982                        this.cycle_prev(&CyclePreviousInlineAssist, window, cx);
 983                    })),
 984            )
 985            .child(
 986                Label::new(format!(
 987                    "{}/{}",
 988                    codegen.active_alternative + 1,
 989                    codegen.alternative_count(cx)
 990                ))
 991                .size(LabelSize::Small)
 992                .color(if disabled {
 993                    Color::Disabled
 994                } else {
 995                    Color::Muted
 996                }),
 997            )
 998            .child(
 999                IconButton::new("next", IconName::ChevronRight)
1000                    .icon_color(Color::Muted)
1001                    .disabled(disabled || current_index == total_models - 1)
1002                    .shape(IconButtonShape::Square)
1003                    .tooltip({
1004                        let focus_handle = self.editor.focus_handle(cx);
1005                        move |_window, cx| {
1006                            cx.new(|cx| {
1007                                let mut tooltip = Tooltip::new("Next Alternative").key_binding(
1008                                    KeyBinding::for_action_in(
1009                                        &CycleNextInlineAssist,
1010                                        &focus_handle,
1011                                        cx,
1012                                    ),
1013                                );
1014                                if !disabled && current_index != total_models - 1 {
1015                                    tooltip = tooltip.meta(next_model_name.clone());
1016                                }
1017                                tooltip
1018                            })
1019                            .into()
1020                        }
1021                    })
1022                    .on_click(cx.listener(|this, _, window, cx| {
1023                        this.cycle_next(&CycleNextInlineAssist, window, cx)
1024                    })),
1025            )
1026            .into_any_element()
1027    }
1028
1029    fn render_editor(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> AnyElement {
1030        let colors = cx.theme().colors();
1031
1032        div()
1033            .key_context("InlineAssistEditor")
1034            .size_full()
1035            .p_2()
1036            .pl_1()
1037            .bg(colors.editor_background)
1038            .child({
1039                let settings = ThemeSettings::get_global(cx);
1040                let font_size = settings.buffer_font_size(cx);
1041                let line_height = font_size * 1.2;
1042
1043                let text_style = TextStyle {
1044                    color: colors.editor_foreground,
1045                    font_family: settings.buffer_font.family.clone(),
1046                    font_features: settings.buffer_font.features.clone(),
1047                    font_size: font_size.into(),
1048                    line_height: line_height.into(),
1049                    ..Default::default()
1050                };
1051
1052                EditorElement::new(
1053                    &self.editor,
1054                    EditorStyle {
1055                        background: colors.editor_background,
1056                        local_player: cx.theme().players().local(),
1057                        syntax: cx.theme().syntax().clone(),
1058                        text: text_style,
1059                        ..Default::default()
1060                    },
1061                )
1062            })
1063            .into_any_element()
1064    }
1065
1066    fn render_markdown(&self, markdown: Entity<Markdown>, style: MarkdownStyle) -> MarkdownElement {
1067        MarkdownElement::new(markdown, style)
1068    }
1069}
1070
1071pub enum PromptEditorMode {
1072    Buffer {
1073        id: InlineAssistId,
1074        codegen: Entity<BufferCodegen>,
1075        editor_margins: Arc<Mutex<EditorMargins>>,
1076    },
1077    Terminal {
1078        id: TerminalInlineAssistId,
1079        codegen: Entity<TerminalCodegen>,
1080        height_in_lines: u8,
1081    },
1082}
1083
1084pub enum PromptEditorEvent {
1085    StartRequested,
1086    StopRequested,
1087    ConfirmRequested { execute: bool },
1088    CancelRequested,
1089    Resized { height_in_lines: u8 },
1090}
1091
1092#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
1093pub struct InlineAssistId(pub usize);
1094
1095impl InlineAssistId {
1096    pub fn post_inc(&mut self) -> InlineAssistId {
1097        let id = *self;
1098        self.0 += 1;
1099        id
1100    }
1101}
1102
1103struct PromptEditorCompletionProviderDelegate;
1104
1105fn inline_assistant_model_supports_images(cx: &App) -> bool {
1106    LanguageModelRegistry::read_global(cx)
1107        .inline_assistant_model()
1108        .map_or(false, |m| m.model.supports_images())
1109}
1110
1111impl PromptCompletionProviderDelegate for PromptEditorCompletionProviderDelegate {
1112    fn supported_modes(&self, _cx: &App) -> Vec<PromptContextType> {
1113        vec![
1114            PromptContextType::File,
1115            PromptContextType::Symbol,
1116            PromptContextType::Thread,
1117            PromptContextType::Fetch,
1118            PromptContextType::Rules,
1119        ]
1120    }
1121
1122    fn supports_images(&self, cx: &App) -> bool {
1123        inline_assistant_model_supports_images(cx)
1124    }
1125
1126    fn available_commands(&self, _cx: &App) -> Vec<crate::completion_provider::AvailableCommand> {
1127        Vec::new()
1128    }
1129
1130    fn confirm_command(&self, _cx: &mut App) {}
1131}
1132
1133impl PromptEditor<BufferCodegen> {
1134    pub fn new_buffer(
1135        id: InlineAssistId,
1136        editor_margins: Arc<Mutex<EditorMargins>>,
1137        prompt_history: VecDeque<String>,
1138        prompt_buffer: Entity<MultiBuffer>,
1139        codegen: Entity<BufferCodegen>,
1140        session_id: Uuid,
1141        fs: Arc<dyn Fs>,
1142        history_store: Entity<HistoryStore>,
1143        prompt_store: Option<Entity<PromptStore>>,
1144        project: WeakEntity<Project>,
1145        workspace: WeakEntity<Workspace>,
1146        window: &mut Window,
1147        cx: &mut Context<PromptEditor<BufferCodegen>>,
1148    ) -> PromptEditor<BufferCodegen> {
1149        let codegen_subscription = cx.observe(&codegen, Self::handle_codegen_changed);
1150        let mode = PromptEditorMode::Buffer {
1151            id,
1152            codegen,
1153            editor_margins,
1154        };
1155
1156        let prompt_editor = cx.new(|cx| {
1157            let mut editor = Editor::new(
1158                EditorMode::AutoHeight {
1159                    min_lines: 1,
1160                    max_lines: Some(Self::MAX_LINES as usize),
1161                },
1162                prompt_buffer,
1163                None,
1164                window,
1165                cx,
1166            );
1167            editor.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
1168            // Since the prompt editors for all inline assistants are linked,
1169            // always show the cursor (even when it isn't focused) because
1170            // typing in one will make what you typed appear in all of them.
1171            editor.set_show_cursor_when_unfocused(true, cx);
1172            editor.set_placeholder_text(&Self::placeholder_text(&mode, window, cx), window, cx);
1173            editor.set_context_menu_options(ContextMenuOptions {
1174                min_entries_visible: 12,
1175                max_entries_visible: 12,
1176                placement: None,
1177            });
1178
1179            editor
1180        });
1181
1182        let mention_set =
1183            cx.new(|_cx| MentionSet::new(project, history_store.clone(), prompt_store.clone()));
1184
1185        let model_selector_menu_handle = PopoverMenuHandle::default();
1186
1187        let mut this: PromptEditor<BufferCodegen> = PromptEditor {
1188            editor: prompt_editor.clone(),
1189            mention_set,
1190            history_store,
1191            prompt_store,
1192            workspace,
1193            model_selector: cx.new(|cx| {
1194                AgentModelSelector::new(
1195                    fs,
1196                    model_selector_menu_handle,
1197                    prompt_editor.focus_handle(cx),
1198                    ModelUsageContext::InlineAssistant,
1199                    window,
1200                    cx,
1201                )
1202            }),
1203            edited_since_done: false,
1204            prompt_history,
1205            prompt_history_ix: None,
1206            pending_prompt: String::new(),
1207            _codegen_subscription: codegen_subscription,
1208            editor_subscriptions: Vec::new(),
1209            show_rate_limit_notice: false,
1210            mode,
1211            session_state: SessionState {
1212                session_id,
1213                completion: CompletionState::Pending,
1214            },
1215            _phantom: Default::default(),
1216        };
1217
1218        this.assign_completion_provider(cx);
1219        this.subscribe_to_editor(window, cx);
1220        this
1221    }
1222
1223    fn handle_codegen_changed(
1224        &mut self,
1225        codegen: Entity<BufferCodegen>,
1226        cx: &mut Context<PromptEditor<BufferCodegen>>,
1227    ) {
1228        match self.codegen_status(cx) {
1229            CodegenStatus::Idle => {
1230                self.editor
1231                    .update(cx, |editor, _| editor.set_read_only(false));
1232            }
1233            CodegenStatus::Pending => {
1234                self.session_state.completion = CompletionState::Pending;
1235                self.editor
1236                    .update(cx, |editor, _| editor.set_read_only(true));
1237            }
1238            CodegenStatus::Done => {
1239                let completion = codegen.read(cx).active_completion(cx);
1240                self.session_state.completion = CompletionState::Generated {
1241                    completion_text: completion,
1242                };
1243                self.edited_since_done = false;
1244                self.editor
1245                    .update(cx, |editor, _| editor.set_read_only(false));
1246            }
1247            CodegenStatus::Error(_error) => {
1248                self.edited_since_done = false;
1249                self.editor
1250                    .update(cx, |editor, _| editor.set_read_only(false));
1251            }
1252        }
1253    }
1254
1255    pub fn id(&self) -> InlineAssistId {
1256        match &self.mode {
1257            PromptEditorMode::Buffer { id, .. } => *id,
1258            PromptEditorMode::Terminal { .. } => unreachable!(),
1259        }
1260    }
1261
1262    pub fn codegen(&self) -> &Entity<BufferCodegen> {
1263        match &self.mode {
1264            PromptEditorMode::Buffer { codegen, .. } => codegen,
1265            PromptEditorMode::Terminal { .. } => unreachable!(),
1266        }
1267    }
1268
1269    pub fn mention_set(&self) -> &Entity<MentionSet> {
1270        &self.mention_set
1271    }
1272
1273    pub fn editor_margins(&self) -> &Arc<Mutex<EditorMargins>> {
1274        match &self.mode {
1275            PromptEditorMode::Buffer { editor_margins, .. } => editor_margins,
1276            PromptEditorMode::Terminal { .. } => unreachable!(),
1277        }
1278    }
1279}
1280
1281#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash)]
1282pub struct TerminalInlineAssistId(pub usize);
1283
1284impl TerminalInlineAssistId {
1285    pub fn post_inc(&mut self) -> TerminalInlineAssistId {
1286        let id = *self;
1287        self.0 += 1;
1288        id
1289    }
1290}
1291
1292impl PromptEditor<TerminalCodegen> {
1293    pub fn new_terminal(
1294        id: TerminalInlineAssistId,
1295        prompt_history: VecDeque<String>,
1296        prompt_buffer: Entity<MultiBuffer>,
1297        codegen: Entity<TerminalCodegen>,
1298        session_id: Uuid,
1299        fs: Arc<dyn Fs>,
1300        history_store: Entity<HistoryStore>,
1301        prompt_store: Option<Entity<PromptStore>>,
1302        project: WeakEntity<Project>,
1303        workspace: WeakEntity<Workspace>,
1304        window: &mut Window,
1305        cx: &mut Context<Self>,
1306    ) -> Self {
1307        let codegen_subscription = cx.observe(&codegen, Self::handle_codegen_changed);
1308        let mode = PromptEditorMode::Terminal {
1309            id,
1310            codegen,
1311            height_in_lines: 1,
1312        };
1313
1314        let prompt_editor = cx.new(|cx| {
1315            let mut editor = Editor::new(
1316                EditorMode::AutoHeight {
1317                    min_lines: 1,
1318                    max_lines: Some(Self::MAX_LINES as usize),
1319                },
1320                prompt_buffer,
1321                None,
1322                window,
1323                cx,
1324            );
1325            editor.set_soft_wrap_mode(language::language_settings::SoftWrap::EditorWidth, cx);
1326            editor.set_placeholder_text(&Self::placeholder_text(&mode, window, cx), window, cx);
1327            editor.set_context_menu_options(ContextMenuOptions {
1328                min_entries_visible: 12,
1329                max_entries_visible: 12,
1330                placement: None,
1331            });
1332            editor
1333        });
1334
1335        let mention_set =
1336            cx.new(|_cx| MentionSet::new(project, history_store.clone(), prompt_store.clone()));
1337
1338        let model_selector_menu_handle = PopoverMenuHandle::default();
1339
1340        let mut this = Self {
1341            editor: prompt_editor.clone(),
1342            mention_set,
1343            history_store,
1344            prompt_store,
1345            workspace,
1346            model_selector: cx.new(|cx| {
1347                AgentModelSelector::new(
1348                    fs,
1349                    model_selector_menu_handle.clone(),
1350                    prompt_editor.focus_handle(cx),
1351                    ModelUsageContext::InlineAssistant,
1352                    window,
1353                    cx,
1354                )
1355            }),
1356            edited_since_done: false,
1357            prompt_history,
1358            prompt_history_ix: None,
1359            pending_prompt: String::new(),
1360            _codegen_subscription: codegen_subscription,
1361            editor_subscriptions: Vec::new(),
1362            mode,
1363            show_rate_limit_notice: false,
1364            session_state: SessionState {
1365                session_id,
1366                completion: CompletionState::Pending,
1367            },
1368            _phantom: Default::default(),
1369        };
1370        this.count_lines(cx);
1371        this.assign_completion_provider(cx);
1372        this.subscribe_to_editor(window, cx);
1373        this
1374    }
1375
1376    fn count_lines(&mut self, cx: &mut Context<Self>) {
1377        let height_in_lines = cmp::max(
1378            2, // Make the editor at least two lines tall, to account for padding and buttons.
1379            cmp::min(
1380                self.editor
1381                    .update(cx, |editor, cx| editor.max_point(cx).row().0 + 1),
1382                Self::MAX_LINES as u32,
1383            ),
1384        ) as u8;
1385
1386        match &mut self.mode {
1387            PromptEditorMode::Terminal {
1388                height_in_lines: current_height,
1389                ..
1390            } => {
1391                if height_in_lines != *current_height {
1392                    *current_height = height_in_lines;
1393                    cx.emit(PromptEditorEvent::Resized { height_in_lines });
1394                }
1395            }
1396            PromptEditorMode::Buffer { .. } => unreachable!(),
1397        }
1398    }
1399
1400    fn handle_codegen_changed(&mut self, codegen: Entity<TerminalCodegen>, cx: &mut Context<Self>) {
1401        match &self.codegen().read(cx).status {
1402            CodegenStatus::Idle => {
1403                self.editor
1404                    .update(cx, |editor, _| editor.set_read_only(false));
1405            }
1406            CodegenStatus::Pending => {
1407                self.session_state.completion = CompletionState::Pending;
1408                self.editor
1409                    .update(cx, |editor, _| editor.set_read_only(true));
1410            }
1411            CodegenStatus::Done | CodegenStatus::Error(_) => {
1412                self.session_state.completion = CompletionState::Generated {
1413                    completion_text: codegen.read(cx).completion(),
1414                };
1415                self.edited_since_done = false;
1416                self.editor
1417                    .update(cx, |editor, _| editor.set_read_only(false));
1418            }
1419        }
1420    }
1421
1422    pub fn mention_set(&self) -> &Entity<MentionSet> {
1423        &self.mention_set
1424    }
1425
1426    pub fn codegen(&self) -> &Entity<TerminalCodegen> {
1427        match &self.mode {
1428            PromptEditorMode::Buffer { .. } => unreachable!(),
1429            PromptEditorMode::Terminal { codegen, .. } => codegen,
1430        }
1431    }
1432
1433    pub fn id(&self) -> TerminalInlineAssistId {
1434        match &self.mode {
1435            PromptEditorMode::Buffer { .. } => unreachable!(),
1436            PromptEditorMode::Terminal { id, .. } => *id,
1437        }
1438    }
1439}
1440
1441pub enum CodegenStatus {
1442    Idle,
1443    Pending,
1444    Done,
1445    Error(anyhow::Error),
1446}
1447
1448/// This is just CodegenStatus without the anyhow::Error, which causes a lifetime issue for rendering the Cancel button.
1449#[derive(Copy, Clone)]
1450pub enum CancelButtonState {
1451    Idle,
1452    Pending,
1453    Done,
1454    Error,
1455}
1456
1457impl Into<CancelButtonState> for &CodegenStatus {
1458    fn into(self) -> CancelButtonState {
1459        match self {
1460            CodegenStatus::Idle => CancelButtonState::Idle,
1461            CodegenStatus::Pending => CancelButtonState::Pending,
1462            CodegenStatus::Done => CancelButtonState::Done,
1463            CodegenStatus::Error(_) => CancelButtonState::Error,
1464        }
1465    }
1466}
1467
1468#[derive(Copy, Clone)]
1469pub enum GenerationMode {
1470    Generate,
1471    Transform,
1472}
1473
1474impl GenerationMode {
1475    fn start_label(self) -> &'static str {
1476        match self {
1477            GenerationMode::Generate => "Generate",
1478            GenerationMode::Transform => "Transform",
1479        }
1480    }
1481    fn tooltip_interrupt(self) -> &'static str {
1482        match self {
1483            GenerationMode::Generate => "Interrupt Generation",
1484            GenerationMode::Transform => "Interrupt Transform",
1485        }
1486    }
1487
1488    fn tooltip_restart(self) -> &'static str {
1489        match self {
1490            GenerationMode::Generate => "Restart Generation",
1491            GenerationMode::Transform => "Restart Transform",
1492        }
1493    }
1494
1495    fn tooltip_accept(self) -> &'static str {
1496        match self {
1497            GenerationMode::Generate => "Accept Generation",
1498            GenerationMode::Transform => "Accept Transform",
1499        }
1500    }
1501}
1502
1503/// Stored information that can be used to resurrect a context crease when creating an editor for a past message.
1504#[derive(Clone, Debug)]
1505struct MessageCrease {
1506    range: Range<MultiBufferOffset>,
1507    icon_path: SharedString,
1508    label: SharedString,
1509}
1510
1511fn extract_message_creases(
1512    editor: &mut Editor,
1513    mention_set: &Entity<MentionSet>,
1514    window: &mut Window,
1515    cx: &mut Context<'_, Editor>,
1516) -> Vec<MessageCrease> {
1517    let creases = mention_set.read(cx).creases();
1518    let snapshot = editor.snapshot(window, cx);
1519    snapshot
1520        .crease_snapshot
1521        .creases()
1522        .filter(|(id, _)| creases.contains(id))
1523        .filter_map(|(_, crease)| {
1524            let metadata = crease.metadata()?.clone();
1525            Some(MessageCrease {
1526                range: crease.range().to_offset(snapshot.buffer()),
1527                label: metadata.label,
1528                icon_path: metadata.icon_path,
1529            })
1530        })
1531        .collect()
1532}
1533
1534fn insert_message_creases(
1535    editor: &mut Editor,
1536    message_creases: &[MessageCrease],
1537    window: &mut Window,
1538    cx: &mut Context<'_, Editor>,
1539) -> Vec<CreaseId> {
1540    let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1541    let creases = message_creases
1542        .iter()
1543        .map(|crease| {
1544            let start = buffer_snapshot.anchor_after(crease.range.start);
1545            let end = buffer_snapshot.anchor_before(crease.range.end);
1546            crease_for_mention(
1547                crease.label.clone(),
1548                crease.icon_path.clone(),
1549                start..end,
1550                cx.weak_entity(),
1551            )
1552        })
1553        .collect::<Vec<_>>();
1554    let ids = editor.insert_creases(creases.clone(), cx);
1555    editor.fold_creases(creases, false, window, cx);
1556    ids
1557}