message_editor.rs

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