inline_prompt_editor.rs

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