message_editor.rs

   1use std::collections::BTreeMap;
   2use std::sync::Arc;
   3
   4use crate::assistant_model_selector::{AssistantModelSelector, ModelType};
   5use crate::context::{AgentContextKey, ContextCreasesAddon, ContextLoadResult, load_context};
   6use crate::tool_compatibility::{IncompatibleToolsState, IncompatibleToolsTooltip};
   7use crate::ui::{AgentPreview, AnimatedLabel};
   8use buffer_diff::BufferDiff;
   9use collections::{HashMap, HashSet};
  10use editor::actions::{MoveUp, Paste};
  11use editor::{
  12    AnchorRangeExt, ContextMenuOptions, ContextMenuPlacement, Editor, EditorElement, EditorEvent,
  13    EditorMode, EditorStyle, MultiBuffer,
  14};
  15use feature_flags::{FeatureFlagAppExt, NewBillingFeatureFlag};
  16use file_icons::FileIcons;
  17use fs::Fs;
  18use futures::future::Shared;
  19use futures::{FutureExt as _, future};
  20use gpui::{
  21    Animation, AnimationExt, App, ClipboardEntry, Entity, EventEmitter, Focusable, Subscription,
  22    Task, TextStyle, WeakEntity, linear_color_stop, linear_gradient, point, pulsating_between,
  23};
  24use language::{Buffer, Language};
  25use language_model::{ConfiguredModel, LanguageModelRequestMessage, MessageContent};
  26use language_model_selector::ToggleModelSelector;
  27use multi_buffer;
  28use project::Project;
  29use prompt_store::PromptStore;
  30use settings::Settings;
  31use std::time::Duration;
  32use theme::ThemeSettings;
  33use ui::{Disclosure, KeyBinding, PopoverMenuHandle, Tooltip, prelude::*};
  34use util::ResultExt as _;
  35use workspace::Workspace;
  36use zed_llm_client::CompletionMode;
  37
  38use crate::context_picker::{ContextPicker, ContextPickerCompletionProvider, crease_for_mention};
  39use crate::context_store::ContextStore;
  40use crate::context_strip::{ContextStrip, ContextStripEvent, SuggestContextKind};
  41use crate::profile_selector::ProfileSelector;
  42use crate::thread::{MessageCrease, Thread, TokenUsageRatio};
  43use crate::thread_store::ThreadStore;
  44use crate::{
  45    ActiveThread, AgentDiffPane, Chat, ExpandMessageEditor, NewThread, OpenAgentDiff,
  46    RemoveAllContext, ToggleContextPicker, ToggleProfileSelector, register_agent_preview,
  47};
  48
  49#[derive(RegisterComponent)]
  50pub struct MessageEditor {
  51    thread: Entity<Thread>,
  52    incompatible_tools_state: Entity<IncompatibleToolsState>,
  53    editor: Entity<Editor>,
  54    workspace: WeakEntity<Workspace>,
  55    project: Entity<Project>,
  56    context_store: Entity<ContextStore>,
  57    prompt_store: Option<Entity<PromptStore>>,
  58    context_strip: Entity<ContextStrip>,
  59    context_picker_menu_handle: PopoverMenuHandle<ContextPicker>,
  60    model_selector: Entity<AssistantModelSelector>,
  61    last_loaded_context: Option<ContextLoadResult>,
  62    load_context_task: Option<Shared<Task<()>>>,
  63    profile_selector: Entity<ProfileSelector>,
  64    edits_expanded: bool,
  65    editor_is_expanded: bool,
  66    last_estimated_token_count: Option<usize>,
  67    update_token_count_task: Option<Task<()>>,
  68    _subscriptions: Vec<Subscription>,
  69}
  70
  71const MAX_EDITOR_LINES: usize = 8;
  72
  73pub(crate) fn create_editor(
  74    workspace: WeakEntity<Workspace>,
  75    context_store: WeakEntity<ContextStore>,
  76    thread_store: WeakEntity<ThreadStore>,
  77    window: &mut Window,
  78    cx: &mut App,
  79) -> Entity<Editor> {
  80    let language = Language::new(
  81        language::LanguageConfig {
  82            completion_query_characters: HashSet::from_iter(['.', '-', '_', '@']),
  83            ..Default::default()
  84        },
  85        None,
  86    );
  87
  88    let editor = cx.new(|cx| {
  89        let buffer = cx.new(|cx| Buffer::local("", cx).with_language(Arc::new(language), cx));
  90        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
  91        let mut editor = Editor::new(
  92            editor::EditorMode::AutoHeight {
  93                max_lines: MAX_EDITOR_LINES,
  94            },
  95            buffer,
  96            None,
  97            window,
  98            cx,
  99        );
 100        editor.set_placeholder_text("Ask anything, @ to mention, ↑ to select", cx);
 101        editor.set_show_indent_guides(false, cx);
 102        editor.set_soft_wrap();
 103        editor.set_context_menu_options(ContextMenuOptions {
 104            min_entries_visible: 12,
 105            max_entries_visible: 12,
 106            placement: Some(ContextMenuPlacement::Above),
 107        });
 108        editor.register_addon(ContextCreasesAddon::new());
 109        editor
 110    });
 111
 112    let editor_entity = editor.downgrade();
 113    editor.update(cx, |editor, _| {
 114        editor.set_completion_provider(Some(Box::new(ContextPickerCompletionProvider::new(
 115            workspace,
 116            context_store,
 117            Some(thread_store),
 118            editor_entity,
 119        ))));
 120    });
 121    editor
 122}
 123
 124impl MessageEditor {
 125    pub fn new(
 126        fs: Arc<dyn Fs>,
 127        workspace: WeakEntity<Workspace>,
 128        context_store: Entity<ContextStore>,
 129        prompt_store: Option<Entity<PromptStore>>,
 130        thread_store: WeakEntity<ThreadStore>,
 131        thread: Entity<Thread>,
 132        window: &mut Window,
 133        cx: &mut Context<Self>,
 134    ) -> Self {
 135        let context_picker_menu_handle = PopoverMenuHandle::default();
 136        let model_selector_menu_handle = PopoverMenuHandle::default();
 137
 138        let editor = create_editor(
 139            workspace.clone(),
 140            context_store.downgrade(),
 141            thread_store.clone(),
 142            window,
 143            cx,
 144        );
 145
 146        let context_strip = cx.new(|cx| {
 147            ContextStrip::new(
 148                context_store.clone(),
 149                workspace.clone(),
 150                Some(thread_store.clone()),
 151                context_picker_menu_handle.clone(),
 152                SuggestContextKind::File,
 153                window,
 154                cx,
 155            )
 156        });
 157
 158        let incompatible_tools =
 159            cx.new(|cx| IncompatibleToolsState::new(thread.read(cx).tools().clone(), cx));
 160
 161        let subscriptions = vec![
 162            cx.subscribe_in(&context_strip, window, Self::handle_context_strip_event),
 163            cx.subscribe(&editor, |this, _, event, cx| match event {
 164                EditorEvent::BufferEdited => this.handle_message_changed(cx),
 165                _ => {}
 166            }),
 167            cx.observe(&context_store, |this, _, cx| {
 168                // When context changes, reload it for token counting.
 169                let _ = this.reload_context(cx);
 170            }),
 171            cx.observe(&thread.read(cx).action_log().clone(), |_, _, cx| {
 172                cx.notify()
 173            }),
 174        ];
 175
 176        let model_selector = cx.new(|cx| {
 177            AssistantModelSelector::new(
 178                fs.clone(),
 179                model_selector_menu_handle,
 180                editor.focus_handle(cx),
 181                ModelType::Default(thread.clone()),
 182                window,
 183                cx,
 184            )
 185        });
 186
 187        Self {
 188            editor: editor.clone(),
 189            project: thread.read(cx).project().clone(),
 190            thread,
 191            incompatible_tools_state: incompatible_tools.clone(),
 192            workspace,
 193            context_store,
 194            prompt_store,
 195            context_strip,
 196            context_picker_menu_handle,
 197            load_context_task: None,
 198            last_loaded_context: None,
 199            model_selector,
 200            edits_expanded: false,
 201            editor_is_expanded: false,
 202            profile_selector: cx
 203                .new(|cx| ProfileSelector::new(fs, thread_store, editor.focus_handle(cx), cx)),
 204            last_estimated_token_count: None,
 205            update_token_count_task: None,
 206            _subscriptions: subscriptions,
 207        }
 208    }
 209
 210    pub fn context_store(&self) -> &Entity<ContextStore> {
 211        &self.context_store
 212    }
 213
 214    pub fn expand_message_editor(
 215        &mut self,
 216        _: &ExpandMessageEditor,
 217        _window: &mut Window,
 218        cx: &mut Context<Self>,
 219    ) {
 220        self.set_editor_is_expanded(!self.editor_is_expanded, cx);
 221    }
 222
 223    fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
 224        self.editor_is_expanded = is_expanded;
 225        self.editor.update(cx, |editor, _| {
 226            if self.editor_is_expanded {
 227                editor.set_mode(EditorMode::Full {
 228                    scale_ui_elements_with_buffer_font_size: false,
 229                    show_active_line_background: false,
 230                    sized_by_content: false,
 231                })
 232            } else {
 233                editor.set_mode(EditorMode::AutoHeight {
 234                    max_lines: MAX_EDITOR_LINES,
 235                })
 236            }
 237        });
 238        cx.notify();
 239    }
 240
 241    fn toggle_context_picker(
 242        &mut self,
 243        _: &ToggleContextPicker,
 244        window: &mut Window,
 245        cx: &mut Context<Self>,
 246    ) {
 247        self.context_picker_menu_handle.toggle(window, cx);
 248    }
 249
 250    pub fn remove_all_context(
 251        &mut self,
 252        _: &RemoveAllContext,
 253        _window: &mut Window,
 254        cx: &mut Context<Self>,
 255    ) {
 256        self.context_store.update(cx, |store, _cx| store.clear());
 257        cx.notify();
 258    }
 259
 260    fn chat(&mut self, _: &Chat, window: &mut Window, cx: &mut Context<Self>) {
 261        if self.is_editor_empty(cx) {
 262            return;
 263        }
 264
 265        self.thread.update(cx, |thread, cx| {
 266            thread.cancel_editing(cx);
 267        });
 268
 269        if self.thread.read(cx).is_generating() {
 270            self.stop_current_and_send_new_message(window, cx);
 271            return;
 272        }
 273
 274        self.set_editor_is_expanded(false, cx);
 275        self.send_to_model(window, cx);
 276
 277        cx.notify();
 278    }
 279
 280    fn is_editor_empty(&self, cx: &App) -> bool {
 281        self.editor.read(cx).text(cx).trim().is_empty()
 282    }
 283
 284    fn send_to_model(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 285        let Some(ConfiguredModel { model, provider }) = self
 286            .thread
 287            .update(cx, |thread, cx| thread.get_or_init_configured_model(cx))
 288        else {
 289            return;
 290        };
 291
 292        if provider.must_accept_terms(cx) {
 293            cx.notify();
 294            return;
 295        }
 296
 297        let (user_message, user_message_creases) = self.editor.update(cx, |editor, cx| {
 298            let creases = extract_message_creases(editor, cx);
 299            let text = editor.text(cx);
 300            editor.clear(window, cx);
 301            (text, creases)
 302        });
 303
 304        self.last_estimated_token_count.take();
 305        cx.emit(MessageEditorEvent::EstimatedTokenCount);
 306
 307        let thread = self.thread.clone();
 308        let git_store = self.project.read(cx).git_store().clone();
 309        let checkpoint = git_store.update(cx, |git_store, cx| git_store.checkpoint(cx));
 310        let context_task = self.reload_context(cx);
 311        let window_handle = window.window_handle();
 312
 313        cx.spawn(async move |_this, cx| {
 314            let (checkpoint, loaded_context) = future::join(checkpoint, context_task).await;
 315            let loaded_context = loaded_context.unwrap_or_default();
 316
 317            thread
 318                .update(cx, |thread, cx| {
 319                    thread.insert_user_message(
 320                        user_message,
 321                        loaded_context,
 322                        checkpoint.ok(),
 323                        user_message_creases,
 324                        cx,
 325                    );
 326                })
 327                .log_err();
 328
 329            thread
 330                .update(cx, |thread, cx| {
 331                    thread.advance_prompt_id();
 332                    thread.send_to_model(model, Some(window_handle), cx);
 333                })
 334                .log_err();
 335        })
 336        .detach();
 337    }
 338
 339    fn stop_current_and_send_new_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 340        self.thread.update(cx, |thread, cx| {
 341            thread.cancel_editing(cx);
 342        });
 343
 344        let cancelled = self.thread.update(cx, |thread, cx| {
 345            thread.cancel_last_completion(Some(window.window_handle()), cx)
 346        });
 347
 348        if cancelled {
 349            self.set_editor_is_expanded(false, cx);
 350            self.send_to_model(window, cx);
 351        }
 352    }
 353
 354    fn handle_context_strip_event(
 355        &mut self,
 356        _context_strip: &Entity<ContextStrip>,
 357        event: &ContextStripEvent,
 358        window: &mut Window,
 359        cx: &mut Context<Self>,
 360    ) {
 361        match event {
 362            ContextStripEvent::PickerDismissed
 363            | ContextStripEvent::BlurredEmpty
 364            | ContextStripEvent::BlurredDown => {
 365                let editor_focus_handle = self.editor.focus_handle(cx);
 366                window.focus(&editor_focus_handle);
 367            }
 368            ContextStripEvent::BlurredUp => {}
 369        }
 370    }
 371
 372    fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 373        if self.context_picker_menu_handle.is_deployed() {
 374            cx.propagate();
 375        } else {
 376            self.context_strip.focus_handle(cx).focus(window);
 377        }
 378    }
 379
 380    fn paste(&mut self, _: &Paste, _: &mut Window, cx: &mut Context<Self>) {
 381        let images = cx
 382            .read_from_clipboard()
 383            .map(|item| {
 384                item.into_entries()
 385                    .filter_map(|entry| {
 386                        if let ClipboardEntry::Image(image) = entry {
 387                            Some(image)
 388                        } else {
 389                            None
 390                        }
 391                    })
 392                    .collect::<Vec<_>>()
 393            })
 394            .unwrap_or_default();
 395
 396        if images.is_empty() {
 397            return;
 398        }
 399        cx.stop_propagation();
 400
 401        self.context_store.update(cx, |store, cx| {
 402            for image in images {
 403                store.add_image_instance(Arc::new(image), cx);
 404            }
 405        });
 406    }
 407
 408    fn handle_review_click(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 409        self.edits_expanded = true;
 410        AgentDiffPane::deploy(self.thread.clone(), self.workspace.clone(), window, cx).log_err();
 411        cx.notify();
 412    }
 413
 414    fn handle_file_click(
 415        &self,
 416        buffer: Entity<Buffer>,
 417        window: &mut Window,
 418        cx: &mut Context<Self>,
 419    ) {
 420        if let Ok(diff) =
 421            AgentDiffPane::deploy(self.thread.clone(), self.workspace.clone(), window, cx)
 422        {
 423            let path_key = multi_buffer::PathKey::for_buffer(&buffer, cx);
 424            diff.update(cx, |diff, cx| diff.move_to_path(path_key, window, cx));
 425        }
 426    }
 427
 428    fn render_max_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
 429        if !cx.has_flag::<NewBillingFeatureFlag>() {
 430            return None;
 431        }
 432
 433        let thread = self.thread.read(cx);
 434        let model = thread.configured_model();
 435        if !model?.model.supports_max_mode() {
 436            return None;
 437        }
 438
 439        let active_completion_mode = thread.completion_mode();
 440
 441        Some(
 442            IconButton::new("max-mode", IconName::ZedMaxMode)
 443                .icon_size(IconSize::Small)
 444                .icon_color(Color::Muted)
 445                .toggle_state(active_completion_mode == CompletionMode::Max)
 446                .on_click(cx.listener(move |this, _event, _window, cx| {
 447                    this.thread.update(cx, |thread, _cx| {
 448                        thread.set_completion_mode(match active_completion_mode {
 449                            CompletionMode::Max => CompletionMode::Normal,
 450                            CompletionMode::Normal => CompletionMode::Max,
 451                        });
 452                    });
 453                }))
 454                .tooltip(Tooltip::text("Toggle Max Mode"))
 455                .into_any_element(),
 456        )
 457    }
 458
 459    fn render_editor(
 460        &self,
 461        font_size: Rems,
 462        line_height: Pixels,
 463        window: &mut Window,
 464        cx: &mut Context<Self>,
 465    ) -> Div {
 466        let thread = self.thread.read(cx);
 467        let model = thread.configured_model();
 468
 469        let editor_bg_color = cx.theme().colors().editor_background;
 470        let is_generating = thread.is_generating();
 471        let focus_handle = self.editor.focus_handle(cx);
 472
 473        let is_model_selected = model.is_some();
 474        let is_editor_empty = self.is_editor_empty(cx);
 475
 476        let incompatible_tools = model
 477            .as_ref()
 478            .map(|model| {
 479                self.incompatible_tools_state.update(cx, |state, cx| {
 480                    state
 481                        .incompatible_tools(&model.model, cx)
 482                        .iter()
 483                        .cloned()
 484                        .collect::<Vec<_>>()
 485                })
 486            })
 487            .unwrap_or_default();
 488
 489        let is_editor_expanded = self.editor_is_expanded;
 490        let expand_icon = if is_editor_expanded {
 491            IconName::Minimize
 492        } else {
 493            IconName::Maximize
 494        };
 495
 496        v_flex()
 497            .key_context("MessageEditor")
 498            .on_action(cx.listener(Self::chat))
 499            .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
 500                this.profile_selector
 501                    .read(cx)
 502                    .menu_handle()
 503                    .toggle(window, cx);
 504            }))
 505            .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
 506                this.model_selector
 507                    .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
 508            }))
 509            .on_action(cx.listener(Self::toggle_context_picker))
 510            .on_action(cx.listener(Self::remove_all_context))
 511            .on_action(cx.listener(Self::move_up))
 512            .on_action(cx.listener(Self::expand_message_editor))
 513            .capture_action(cx.listener(Self::paste))
 514            .gap_2()
 515            .p_2()
 516            .bg(editor_bg_color)
 517            .border_t_1()
 518            .border_color(cx.theme().colors().border)
 519            .child(
 520                h_flex()
 521                    .items_start()
 522                    .justify_between()
 523                    .child(self.context_strip.clone())
 524                    .when(focus_handle.is_focused(window), |this| {
 525                        this.child(
 526                            IconButton::new("toggle-height", expand_icon)
 527                                .icon_size(IconSize::XSmall)
 528                                .icon_color(Color::Muted)
 529                                .tooltip({
 530                                    let focus_handle = focus_handle.clone();
 531                                    move |window, cx| {
 532                                        let expand_label = if is_editor_expanded {
 533                                            "Minimize Message Editor".to_string()
 534                                        } else {
 535                                            "Expand Message Editor".to_string()
 536                                        };
 537
 538                                        Tooltip::for_action_in(
 539                                            expand_label,
 540                                            &ExpandMessageEditor,
 541                                            &focus_handle,
 542                                            window,
 543                                            cx,
 544                                        )
 545                                    }
 546                                })
 547                                .on_click(cx.listener(|_, _, window, cx| {
 548                                    window.dispatch_action(Box::new(ExpandMessageEditor), cx);
 549                                })),
 550                        )
 551                    }),
 552            )
 553            .child(
 554                v_flex()
 555                    .size_full()
 556                    .gap_4()
 557                    .when(is_editor_expanded, |this| {
 558                        this.h(vh(0.8, window)).justify_between()
 559                    })
 560                    .child(
 561                        div()
 562                            .min_h_16()
 563                            .when(is_editor_expanded, |this| this.h_full())
 564                            .child({
 565                                let settings = ThemeSettings::get_global(cx);
 566
 567                                let text_style = TextStyle {
 568                                    color: cx.theme().colors().text,
 569                                    font_family: settings.buffer_font.family.clone(),
 570                                    font_fallbacks: settings.buffer_font.fallbacks.clone(),
 571                                    font_features: settings.buffer_font.features.clone(),
 572                                    font_size: font_size.into(),
 573                                    line_height: line_height.into(),
 574                                    ..Default::default()
 575                                };
 576
 577                                EditorElement::new(
 578                                    &self.editor,
 579                                    EditorStyle {
 580                                        background: editor_bg_color,
 581                                        local_player: cx.theme().players().local(),
 582                                        text: text_style,
 583                                        syntax: cx.theme().syntax().clone(),
 584                                        ..Default::default()
 585                                    },
 586                                )
 587                                .into_any()
 588                            }),
 589                    )
 590                    .child(
 591                        h_flex()
 592                            .flex_none()
 593                            .justify_between()
 594                            .child(h_flex().gap_2().child(self.profile_selector.clone()))
 595                            .child(
 596                                h_flex()
 597                                    .gap_1()
 598                                    .when(!incompatible_tools.is_empty(), |this| {
 599                                        this.child(
 600                                            IconButton::new(
 601                                                "tools-incompatible-warning",
 602                                                IconName::Warning,
 603                                            )
 604                                            .icon_color(Color::Warning)
 605                                            .icon_size(IconSize::Small)
 606                                            .tooltip({
 607                                                move |_, cx| {
 608                                                    cx.new(|_| IncompatibleToolsTooltip {
 609                                                        incompatible_tools: incompatible_tools
 610                                                            .clone(),
 611                                                    })
 612                                                    .into()
 613                                                }
 614                                            }),
 615                                        )
 616                                    })
 617                                    .children(self.render_max_mode_toggle(cx))
 618                                    .child(self.model_selector.clone())
 619                                    .map({
 620                                        let focus_handle = focus_handle.clone();
 621                                        move |parent| {
 622                                            if is_generating {
 623                                                parent
 624                                                    .when(is_editor_empty, |parent| {
 625                                                        parent.child(
 626                                                            IconButton::new(
 627                                                                "stop-generation",
 628                                                                IconName::StopFilled,
 629                                                            )
 630                                                            .icon_color(Color::Error)
 631                                                            .style(ButtonStyle::Tinted(
 632                                                                ui::TintColor::Error,
 633                                                            ))
 634                                                            .tooltip(move |window, cx| {
 635                                                                Tooltip::for_action(
 636                                                                    "Stop Generation",
 637                                                                    &editor::actions::Cancel,
 638                                                                    window,
 639                                                                    cx,
 640                                                                )
 641                                                            })
 642                                                            .on_click({
 643                                                                let focus_handle =
 644                                                                    focus_handle.clone();
 645                                                                move |_event, window, cx| {
 646                                                                    focus_handle.dispatch_action(
 647                                                                        &editor::actions::Cancel,
 648                                                                        window,
 649                                                                        cx,
 650                                                                    );
 651                                                                }
 652                                                            })
 653                                                            .with_animation(
 654                                                                "pulsating-label",
 655                                                                Animation::new(
 656                                                                    Duration::from_secs(2),
 657                                                                )
 658                                                                .repeat()
 659                                                                .with_easing(pulsating_between(
 660                                                                    0.4, 1.0,
 661                                                                )),
 662                                                                |icon_button, delta| {
 663                                                                    icon_button.alpha(delta)
 664                                                                },
 665                                                            ),
 666                                                        )
 667                                                    })
 668                                                    .when(!is_editor_empty, |parent| {
 669                                                        parent.child(
 670                                                            IconButton::new(
 671                                                                "send-message",
 672                                                                IconName::Send,
 673                                                            )
 674                                                            .icon_color(Color::Accent)
 675                                                            .style(ButtonStyle::Filled)
 676                                                            .disabled(!is_model_selected)
 677                                                            .on_click({
 678                                                                let focus_handle =
 679                                                                    focus_handle.clone();
 680                                                                move |_event, window, cx| {
 681                                                                    focus_handle.dispatch_action(
 682                                                                        &Chat, window, cx,
 683                                                                    );
 684                                                                }
 685                                                            })
 686                                                            .tooltip(move |window, cx| {
 687                                                                Tooltip::for_action(
 688                                                                    "Stop and Send New Message",
 689                                                                    &Chat,
 690                                                                    window,
 691                                                                    cx,
 692                                                                )
 693                                                            }),
 694                                                        )
 695                                                    })
 696                                            } else {
 697                                                parent.child(
 698                                                    IconButton::new("send-message", IconName::Send)
 699                                                        .icon_color(Color::Accent)
 700                                                        .style(ButtonStyle::Filled)
 701                                                        .disabled(
 702                                                            is_editor_empty || !is_model_selected,
 703                                                        )
 704                                                        .on_click({
 705                                                            let focus_handle = focus_handle.clone();
 706                                                            move |_event, window, cx| {
 707                                                                focus_handle.dispatch_action(
 708                                                                    &Chat, window, cx,
 709                                                                );
 710                                                            }
 711                                                        })
 712                                                        .when(
 713                                                            !is_editor_empty && is_model_selected,
 714                                                            |button| {
 715                                                                button.tooltip(move |window, cx| {
 716                                                                    Tooltip::for_action(
 717                                                                        "Send", &Chat, window, cx,
 718                                                                    )
 719                                                                })
 720                                                            },
 721                                                        )
 722                                                        .when(is_editor_empty, |button| {
 723                                                            button.tooltip(Tooltip::text(
 724                                                                "Type a message to submit",
 725                                                            ))
 726                                                        })
 727                                                        .when(!is_model_selected, |button| {
 728                                                            button.tooltip(Tooltip::text(
 729                                                                "Select a model to continue",
 730                                                            ))
 731                                                        }),
 732                                                )
 733                                            }
 734                                        }
 735                                    }),
 736                            ),
 737                    ),
 738            )
 739    }
 740
 741    fn render_changed_buffers(
 742        &self,
 743        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
 744        window: &mut Window,
 745        cx: &mut Context<Self>,
 746    ) -> Div {
 747        let focus_handle = self.editor.focus_handle(cx);
 748
 749        let editor_bg_color = cx.theme().colors().editor_background;
 750        let border_color = cx.theme().colors().border;
 751        let active_color = cx.theme().colors().element_selected;
 752        let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
 753
 754        let is_edit_changes_expanded = self.edits_expanded;
 755        let is_generating = self.thread.read(cx).is_generating();
 756
 757        v_flex()
 758            .mt_1()
 759            .mx_2()
 760            .bg(bg_edit_files_disclosure)
 761            .border_1()
 762            .border_b_0()
 763            .border_color(border_color)
 764            .rounded_t_md()
 765            .shadow(smallvec::smallvec![gpui::BoxShadow {
 766                color: gpui::black().opacity(0.15),
 767                offset: point(px(1.), px(-1.)),
 768                blur_radius: px(3.),
 769                spread_radius: px(0.),
 770            }])
 771            .child(
 772                h_flex()
 773                    .id("edits-container")
 774                    .cursor_pointer()
 775                    .p_1p5()
 776                    .justify_between()
 777                    .when(is_edit_changes_expanded, |this| {
 778                        this.border_b_1().border_color(border_color)
 779                    })
 780                    .on_click(
 781                        cx.listener(|this, _, window, cx| this.handle_review_click(window, cx)),
 782                    )
 783                    .child(
 784                        h_flex()
 785                            .gap_1()
 786                            .child(
 787                                Disclosure::new("edits-disclosure", is_edit_changes_expanded)
 788                                    .on_click(cx.listener(|this, _ev, _window, cx| {
 789                                        this.edits_expanded = !this.edits_expanded;
 790                                        cx.notify();
 791                                    })),
 792                            )
 793                            .map(|this| {
 794                                if is_generating {
 795                                    this.child(
 796                                        AnimatedLabel::new(format!(
 797                                            "Editing {} {}",
 798                                            changed_buffers.len(),
 799                                            if changed_buffers.len() == 1 {
 800                                                "file"
 801                                            } else {
 802                                                "files"
 803                                            }
 804                                        ))
 805                                        .size(LabelSize::Small),
 806                                    )
 807                                } else {
 808                                    this.child(
 809                                        Label::new("Edits")
 810                                            .size(LabelSize::Small)
 811                                            .color(Color::Muted),
 812                                    )
 813                                    .child(
 814                                        Label::new("").size(LabelSize::XSmall).color(Color::Muted),
 815                                    )
 816                                    .child(
 817                                        Label::new(format!(
 818                                            "{} {}",
 819                                            changed_buffers.len(),
 820                                            if changed_buffers.len() == 1 {
 821                                                "file"
 822                                            } else {
 823                                                "files"
 824                                            }
 825                                        ))
 826                                        .size(LabelSize::Small)
 827                                        .color(Color::Muted),
 828                                    )
 829                                }
 830                            }),
 831                    )
 832                    .child(
 833                        Button::new("review", "Review Changes")
 834                            .label_size(LabelSize::Small)
 835                            .key_binding(
 836                                KeyBinding::for_action_in(
 837                                    &OpenAgentDiff,
 838                                    &focus_handle,
 839                                    window,
 840                                    cx,
 841                                )
 842                                .map(|kb| kb.size(rems_from_px(12.))),
 843                            )
 844                            .on_click(cx.listener(|this, _, window, cx| {
 845                                this.handle_review_click(window, cx)
 846                            })),
 847                    ),
 848            )
 849            .when(is_edit_changes_expanded, |parent| {
 850                parent.child(
 851                    v_flex().children(changed_buffers.into_iter().enumerate().flat_map(
 852                        |(index, (buffer, _diff))| {
 853                            let file = buffer.read(cx).file()?;
 854                            let path = file.path();
 855
 856                            let parent_label = path.parent().and_then(|parent| {
 857                                let parent_str = parent.to_string_lossy();
 858
 859                                if parent_str.is_empty() {
 860                                    None
 861                                } else {
 862                                    Some(
 863                                        Label::new(format!(
 864                                            "/{}{}",
 865                                            parent_str,
 866                                            std::path::MAIN_SEPARATOR_STR
 867                                        ))
 868                                        .color(Color::Muted)
 869                                        .size(LabelSize::XSmall)
 870                                        .buffer_font(cx),
 871                                    )
 872                                }
 873                            });
 874
 875                            let name_label = path.file_name().map(|name| {
 876                                Label::new(name.to_string_lossy().to_string())
 877                                    .size(LabelSize::XSmall)
 878                                    .buffer_font(cx)
 879                            });
 880
 881                            let file_icon = FileIcons::get_icon(&path, cx)
 882                                .map(Icon::from_path)
 883                                .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
 884                                .unwrap_or_else(|| {
 885                                    Icon::new(IconName::File)
 886                                        .color(Color::Muted)
 887                                        .size(IconSize::Small)
 888                                });
 889
 890                            let hover_color = cx
 891                                .theme()
 892                                .colors()
 893                                .element_background
 894                                .blend(cx.theme().colors().editor_foreground.opacity(0.025));
 895
 896                            let overlay_gradient = linear_gradient(
 897                                90.,
 898                                linear_color_stop(editor_bg_color, 1.),
 899                                linear_color_stop(editor_bg_color.opacity(0.2), 0.),
 900                            );
 901
 902                            let overlay_gradient_hover = linear_gradient(
 903                                90.,
 904                                linear_color_stop(hover_color, 1.),
 905                                linear_color_stop(hover_color.opacity(0.2), 0.),
 906                            );
 907
 908                            let element = h_flex()
 909                                .group("edited-code")
 910                                .id(("file-container", index))
 911                                .cursor_pointer()
 912                                .relative()
 913                                .py_1()
 914                                .pl_2()
 915                                .pr_1()
 916                                .gap_2()
 917                                .justify_between()
 918                                .bg(cx.theme().colors().editor_background)
 919                                .hover(|style| style.bg(hover_color))
 920                                .when(index < changed_buffers.len() - 1, |parent| {
 921                                    parent.border_color(border_color).border_b_1()
 922                                })
 923                                .child(
 924                                    h_flex()
 925                                        .id("file-name")
 926                                        .pr_8()
 927                                        .gap_1p5()
 928                                        .max_w_full()
 929                                        .overflow_x_scroll()
 930                                        .child(file_icon)
 931                                        .child(
 932                                            h_flex()
 933                                                .gap_0p5()
 934                                                .children(name_label)
 935                                                .children(parent_label),
 936                                        ), // TODO: Implement line diff
 937                                           // .child(Label::new("+").color(Color::Created))
 938                                           // .child(Label::new("-").color(Color::Deleted)),
 939                                )
 940                                .child(
 941                                    div().visible_on_hover("edited-code").child(
 942                                        Button::new("review", "Review")
 943                                            .label_size(LabelSize::Small)
 944                                            .on_click({
 945                                                let buffer = buffer.clone();
 946                                                cx.listener(move |this, _, window, cx| {
 947                                                    this.handle_file_click(
 948                                                        buffer.clone(),
 949                                                        window,
 950                                                        cx,
 951                                                    );
 952                                                })
 953                                            }),
 954                                    ),
 955                                )
 956                                .child(
 957                                    div()
 958                                        .id("gradient-overlay")
 959                                        .absolute()
 960                                        .h_5_6()
 961                                        .w_12()
 962                                        .bottom_0()
 963                                        .right(px(52.))
 964                                        .bg(overlay_gradient)
 965                                        .group_hover("edited-code", |style| {
 966                                            style.bg(overlay_gradient_hover)
 967                                        }),
 968                                )
 969                                .on_click({
 970                                    let buffer = buffer.clone();
 971                                    cx.listener(move |this, _, window, cx| {
 972                                        this.handle_file_click(buffer.clone(), window, cx);
 973                                    })
 974                                });
 975
 976                            Some(element)
 977                        },
 978                    )),
 979                )
 980            })
 981    }
 982
 983    fn render_token_limit_callout(
 984        &self,
 985        line_height: Pixels,
 986        token_usage_ratio: TokenUsageRatio,
 987        cx: &mut Context<Self>,
 988    ) -> Div {
 989        let heading = if token_usage_ratio == TokenUsageRatio::Exceeded {
 990            "Thread reached the token limit"
 991        } else {
 992            "Thread reaching the token limit soon"
 993        };
 994
 995        h_flex()
 996            .p_2()
 997            .gap_2()
 998            .flex_wrap()
 999            .justify_between()
1000            .bg(
1001                if token_usage_ratio == TokenUsageRatio::Exceeded {
1002                    cx.theme().status().error_background.opacity(0.1)
1003                } else {
1004                    cx.theme().status().warning_background.opacity(0.1)
1005                })
1006            .border_t_1()
1007            .border_color(cx.theme().colors().border)
1008            .child(
1009                h_flex()
1010                    .gap_2()
1011                    .items_start()
1012                    .child(
1013                        h_flex()
1014                            .h(line_height)
1015                            .justify_center()
1016                            .child(
1017                                if token_usage_ratio == TokenUsageRatio::Exceeded {
1018                                    Icon::new(IconName::X)
1019                                        .color(Color::Error)
1020                                        .size(IconSize::XSmall)
1021                                } else {
1022                                    Icon::new(IconName::Warning)
1023                                        .color(Color::Warning)
1024                                        .size(IconSize::XSmall)
1025                                }
1026                            ),
1027                    )
1028                    .child(
1029                        v_flex()
1030                            .mr_auto()
1031                            .child(Label::new(heading).size(LabelSize::Small))
1032                            .child(
1033                                Label::new(
1034                                    "Start a new thread from a summary to continue the conversation.",
1035                                )
1036                                .size(LabelSize::Small)
1037                                .color(Color::Muted),
1038                            ),
1039                    ),
1040            )
1041            .child(
1042                Button::new("new-thread", "Start New Thread")
1043                    .on_click(cx.listener(|this, _, window, cx| {
1044                        let from_thread_id = Some(this.thread.read(cx).id().clone());
1045
1046                        window.dispatch_action(Box::new(NewThread {
1047                            from_thread_id
1048                        }), cx);
1049                    }))
1050                    .icon(IconName::Plus)
1051                    .icon_position(IconPosition::Start)
1052                    .icon_size(IconSize::Small)
1053                    .style(ButtonStyle::Tinted(ui::TintColor::Accent))
1054                    .label_size(LabelSize::Small),
1055            )
1056    }
1057
1058    pub fn last_estimated_token_count(&self) -> Option<usize> {
1059        self.last_estimated_token_count
1060    }
1061
1062    pub fn is_waiting_to_update_token_count(&self) -> bool {
1063        self.update_token_count_task.is_some()
1064    }
1065
1066    fn reload_context(&mut self, cx: &mut Context<Self>) -> Task<Option<ContextLoadResult>> {
1067        let load_task = cx.spawn(async move |this, cx| {
1068            let Ok(load_task) = this.update(cx, |this, cx| {
1069                let new_context = this.context_store.read_with(cx, |context_store, cx| {
1070                    context_store.new_context_for_thread(this.thread.read(cx), None)
1071                });
1072                load_context(new_context, &this.project, &this.prompt_store, cx)
1073            }) else {
1074                return;
1075            };
1076            let result = load_task.await;
1077            this.update(cx, |this, cx| {
1078                this.last_loaded_context = Some(result);
1079                this.load_context_task = None;
1080                this.message_or_context_changed(false, cx);
1081            })
1082            .ok();
1083        });
1084        // Replace existing load task, if any, causing it to be cancelled.
1085        let load_task = load_task.shared();
1086        self.load_context_task = Some(load_task.clone());
1087        cx.spawn(async move |this, cx| {
1088            load_task.await;
1089            this.read_with(cx, |this, _cx| this.last_loaded_context.clone())
1090                .ok()
1091                .flatten()
1092        })
1093    }
1094
1095    fn handle_message_changed(&mut self, cx: &mut Context<Self>) {
1096        self.message_or_context_changed(true, cx);
1097    }
1098
1099    fn message_or_context_changed(&mut self, debounce: bool, cx: &mut Context<Self>) {
1100        cx.emit(MessageEditorEvent::Changed);
1101        self.update_token_count_task.take();
1102
1103        let Some(model) = self.thread.read(cx).configured_model() else {
1104            self.last_estimated_token_count.take();
1105            return;
1106        };
1107
1108        let editor = self.editor.clone();
1109
1110        self.update_token_count_task = Some(cx.spawn(async move |this, cx| {
1111            if debounce {
1112                cx.background_executor()
1113                    .timer(Duration::from_millis(200))
1114                    .await;
1115            }
1116
1117            let token_count = if let Some(task) = this
1118                .update(cx, |this, cx| {
1119                    let loaded_context = this
1120                        .last_loaded_context
1121                        .as_ref()
1122                        .map(|context_load_result| &context_load_result.loaded_context);
1123                    let message_text = editor.read(cx).text(cx);
1124
1125                    if message_text.is_empty()
1126                        && loaded_context.map_or(true, |loaded_context| loaded_context.is_empty())
1127                    {
1128                        return None;
1129                    }
1130
1131                    let mut request_message = LanguageModelRequestMessage {
1132                        role: language_model::Role::User,
1133                        content: Vec::new(),
1134                        cache: false,
1135                    };
1136
1137                    if let Some(loaded_context) = loaded_context {
1138                        loaded_context.add_to_request_message(&mut request_message);
1139                    }
1140
1141                    if !message_text.is_empty() {
1142                        request_message
1143                            .content
1144                            .push(MessageContent::Text(message_text));
1145                    }
1146
1147                    let request = language_model::LanguageModelRequest {
1148                        thread_id: None,
1149                        prompt_id: None,
1150                        mode: None,
1151                        messages: vec![request_message],
1152                        tools: vec![],
1153                        stop: vec![],
1154                        temperature: None,
1155                    };
1156
1157                    Some(model.model.count_tokens(request, cx))
1158                })
1159                .ok()
1160                .flatten()
1161            {
1162                task.await.log_err()
1163            } else {
1164                Some(0)
1165            };
1166
1167            this.update(cx, |this, cx| {
1168                if let Some(token_count) = token_count {
1169                    this.last_estimated_token_count = Some(token_count);
1170                    cx.emit(MessageEditorEvent::EstimatedTokenCount);
1171                }
1172                this.update_token_count_task.take();
1173            })
1174            .ok();
1175        }));
1176    }
1177}
1178
1179pub fn extract_message_creases(
1180    editor: &mut Editor,
1181    cx: &mut Context<'_, Editor>,
1182) -> Vec<MessageCrease> {
1183    let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1184    let mut contexts_by_crease_id = editor
1185        .addon_mut::<ContextCreasesAddon>()
1186        .map(std::mem::take)
1187        .unwrap_or_default()
1188        .into_inner()
1189        .into_iter()
1190        .flat_map(|(key, creases)| {
1191            let context = key.0;
1192            creases
1193                .into_iter()
1194                .map(move |(id, _)| (id, context.clone()))
1195        })
1196        .collect::<HashMap<_, _>>();
1197    // Filter the addon's list of creases based on what the editor reports,
1198    // since the addon might have removed creases in it.
1199    let creases = editor.display_map.update(cx, |display_map, cx| {
1200        display_map
1201            .snapshot(cx)
1202            .crease_snapshot
1203            .creases()
1204            .filter_map(|(id, crease)| {
1205                Some((
1206                    id,
1207                    (
1208                        crease.range().to_offset(&buffer_snapshot),
1209                        crease.metadata()?.clone(),
1210                    ),
1211                ))
1212            })
1213            .map(|(id, (range, metadata))| {
1214                let context = contexts_by_crease_id.remove(&id);
1215                MessageCrease {
1216                    range,
1217                    metadata,
1218                    context,
1219                }
1220            })
1221            .collect()
1222    });
1223    creases
1224}
1225
1226impl EventEmitter<MessageEditorEvent> for MessageEditor {}
1227
1228pub enum MessageEditorEvent {
1229    EstimatedTokenCount,
1230    Changed,
1231}
1232
1233impl Focusable for MessageEditor {
1234    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
1235        self.editor.focus_handle(cx)
1236    }
1237}
1238
1239impl Render for MessageEditor {
1240    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1241        let thread = self.thread.read(cx);
1242        let token_usage_ratio = thread
1243            .total_token_usage()
1244            .map_or(TokenUsageRatio::Normal, |total_token_usage| {
1245                total_token_usage.ratio()
1246            });
1247
1248        let action_log = self.thread.read(cx).action_log();
1249        let changed_buffers = action_log.read(cx).changed_buffers(cx);
1250
1251        let font_size = TextSize::Small.rems(cx);
1252        let line_height = font_size.to_pixels(window.rem_size()) * 1.5;
1253
1254        v_flex()
1255            .size_full()
1256            .when(changed_buffers.len() > 0, |parent| {
1257                parent.child(self.render_changed_buffers(&changed_buffers, window, cx))
1258            })
1259            .child(self.render_editor(font_size, line_height, window, cx))
1260            .when(token_usage_ratio != TokenUsageRatio::Normal, |parent| {
1261                parent.child(self.render_token_limit_callout(line_height, token_usage_ratio, cx))
1262            })
1263    }
1264}
1265
1266pub fn insert_message_creases(
1267    editor: &mut Editor,
1268    message_creases: &[MessageCrease],
1269    context_store: &Entity<ContextStore>,
1270    window: &mut Window,
1271    cx: &mut Context<'_, Editor>,
1272) {
1273    let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1274    let creases = message_creases
1275        .iter()
1276        .map(|crease| {
1277            let start = buffer_snapshot.anchor_after(crease.range.start);
1278            let end = buffer_snapshot.anchor_before(crease.range.end);
1279            crease_for_mention(
1280                crease.metadata.label.clone(),
1281                crease.metadata.icon_path.clone(),
1282                start..end,
1283                cx.weak_entity(),
1284            )
1285        })
1286        .collect::<Vec<_>>();
1287    let ids = editor.insert_creases(creases.clone(), cx);
1288    editor.fold_creases(creases, false, window, cx);
1289    if let Some(addon) = editor.addon_mut::<ContextCreasesAddon>() {
1290        for (crease, id) in message_creases.iter().zip(ids) {
1291            if let Some(context) = crease.context.as_ref() {
1292                let key = AgentContextKey(context.clone());
1293                addon.add_creases(
1294                    context_store,
1295                    key,
1296                    vec![(id, crease.metadata.label.clone())],
1297                    cx,
1298                );
1299            }
1300        }
1301    }
1302}
1303impl Component for MessageEditor {
1304    fn scope() -> ComponentScope {
1305        ComponentScope::Agent
1306    }
1307}
1308
1309impl AgentPreview for MessageEditor {
1310    fn agent_preview(
1311        workspace: WeakEntity<Workspace>,
1312        active_thread: Entity<ActiveThread>,
1313        thread_store: WeakEntity<ThreadStore>,
1314        window: &mut Window,
1315        cx: &mut App,
1316    ) -> Option<AnyElement> {
1317        if let Some(workspace_entity) = workspace.upgrade() {
1318            let fs = workspace_entity.read(cx).app_state().fs.clone();
1319            let weak_project = workspace_entity.read(cx).project().clone().downgrade();
1320            let context_store = cx.new(|_cx| ContextStore::new(weak_project, None));
1321            let thread = active_thread.read(cx).thread().clone();
1322
1323            let example_message_editor = cx.new(|cx| {
1324                MessageEditor::new(
1325                    fs,
1326                    workspace,
1327                    context_store,
1328                    None,
1329                    thread_store,
1330                    thread,
1331                    window,
1332                    cx,
1333                )
1334            });
1335
1336            Some(
1337                v_flex()
1338                    .gap_4()
1339                    .children(vec![single_example(
1340                        "Default",
1341                        example_message_editor.clone().into_any_element(),
1342                    )])
1343                    .into_any_element(),
1344            )
1345        } else {
1346            None
1347        }
1348    }
1349}
1350
1351register_agent_preview!(MessageEditor);