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