message_editor.rs

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