message_editor.rs

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