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, 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    fn render_max_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
 475        let thread = self.thread.read(cx);
 476        let model = thread.configured_model();
 477        if !model?.model.supports_max_mode() {
 478            return None;
 479        }
 480
 481        let active_completion_mode = thread.completion_mode();
 482        let max_mode_enabled = active_completion_mode == CompletionMode::Max;
 483
 484        Some(
 485            Button::new("max-mode", "Max Mode")
 486                .label_size(LabelSize::Small)
 487                .color(Color::Muted)
 488                .icon(IconName::ZedMaxMode)
 489                .icon_size(IconSize::Small)
 490                .icon_color(Color::Muted)
 491                .icon_position(IconPosition::Start)
 492                .toggle_state(max_mode_enabled)
 493                .on_click(cx.listener(move |this, _event, _window, cx| {
 494                    this.thread.update(cx, |thread, _cx| {
 495                        thread.set_completion_mode(match active_completion_mode {
 496                            CompletionMode::Max => CompletionMode::Normal,
 497                            CompletionMode::Normal => CompletionMode::Max,
 498                        });
 499                    });
 500                }))
 501                .tooltip(move |_window, cx| {
 502                    cx.new(|_| MaxModeTooltip::new().selected(max_mode_enabled))
 503                        .into()
 504                })
 505                .into_any_element(),
 506        )
 507    }
 508
 509    fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
 510        let following = self
 511            .workspace
 512            .read_with(cx, |workspace, _| {
 513                workspace.is_being_followed(CollaboratorId::Agent)
 514            })
 515            .unwrap_or(false);
 516
 517        IconButton::new("follow-agent", IconName::Crosshair)
 518            .icon_size(IconSize::Small)
 519            .icon_color(Color::Muted)
 520            .toggle_state(following)
 521            .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
 522            .tooltip(move |window, cx| {
 523                if following {
 524                    Tooltip::for_action("Stop Following Agent", &Follow, window, cx)
 525                } else {
 526                    Tooltip::with_meta(
 527                        "Follow Agent",
 528                        Some(&Follow),
 529                        "Track the agent's location as it reads and edits files.",
 530                        window,
 531                        cx,
 532                    )
 533                }
 534            })
 535            .on_click(cx.listener(move |this, _, window, cx| {
 536                this.workspace
 537                    .update(cx, |workspace, cx| {
 538                        if following {
 539                            workspace.unfollow(CollaboratorId::Agent, window, cx);
 540                        } else {
 541                            workspace.follow(CollaboratorId::Agent, window, cx);
 542                        }
 543                    })
 544                    .ok();
 545            }))
 546    }
 547
 548    fn render_editor(&self, window: &mut Window, cx: &mut Context<Self>) -> Div {
 549        let thread = self.thread.read(cx);
 550        let model = thread.configured_model();
 551
 552        let editor_bg_color = cx.theme().colors().editor_background;
 553        let is_generating = thread.is_generating();
 554        let focus_handle = self.editor.focus_handle(cx);
 555
 556        let is_model_selected = model.is_some();
 557        let is_editor_empty = self.is_editor_empty(cx);
 558
 559        let incompatible_tools = model
 560            .as_ref()
 561            .map(|model| {
 562                self.incompatible_tools_state.update(cx, |state, cx| {
 563                    state
 564                        .incompatible_tools(&model.model, cx)
 565                        .iter()
 566                        .cloned()
 567                        .collect::<Vec<_>>()
 568                })
 569            })
 570            .unwrap_or_default();
 571
 572        let is_editor_expanded = self.editor_is_expanded;
 573        let expand_icon = if is_editor_expanded {
 574            IconName::Minimize
 575        } else {
 576            IconName::Maximize
 577        };
 578
 579        v_flex()
 580            .key_context("MessageEditor")
 581            .on_action(cx.listener(Self::chat))
 582            .on_action(cx.listener(Self::chat_with_follow))
 583            .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
 584                this.profile_selector
 585                    .read(cx)
 586                    .menu_handle()
 587                    .toggle(window, cx);
 588            }))
 589            .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
 590                this.model_selector
 591                    .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
 592            }))
 593            .on_action(cx.listener(Self::toggle_context_picker))
 594            .on_action(cx.listener(Self::remove_all_context))
 595            .on_action(cx.listener(Self::move_up))
 596            .on_action(cx.listener(Self::expand_message_editor))
 597            .capture_action(cx.listener(Self::paste))
 598            .gap_2()
 599            .p_2()
 600            .bg(editor_bg_color)
 601            .border_t_1()
 602            .border_color(cx.theme().colors().border)
 603            .child(
 604                h_flex()
 605                    .items_start()
 606                    .justify_between()
 607                    .child(self.context_strip.clone())
 608                    .child(
 609                        h_flex()
 610                            .gap_1()
 611                            .when(focus_handle.is_focused(window), |this| {
 612                                this.child(
 613                                    IconButton::new("toggle-height", expand_icon)
 614                                        .icon_size(IconSize::XSmall)
 615                                        .icon_color(Color::Muted)
 616                                        .tooltip({
 617                                            let focus_handle = focus_handle.clone();
 618                                            move |window, cx| {
 619                                                let expand_label = if is_editor_expanded {
 620                                                    "Minimize Message Editor".to_string()
 621                                                } else {
 622                                                    "Expand Message Editor".to_string()
 623                                                };
 624
 625                                                Tooltip::for_action_in(
 626                                                    expand_label,
 627                                                    &ExpandMessageEditor,
 628                                                    &focus_handle,
 629                                                    window,
 630                                                    cx,
 631                                                )
 632                                            }
 633                                        })
 634                                        .on_click(cx.listener(|_, _, window, cx| {
 635                                            window
 636                                                .dispatch_action(Box::new(ExpandMessageEditor), cx);
 637                                        })),
 638                                )
 639                            }),
 640                    ),
 641            )
 642            .child(
 643                v_flex()
 644                    .size_full()
 645                    .gap_4()
 646                    .when(is_editor_expanded, |this| {
 647                        this.h(vh(0.8, window)).justify_between()
 648                    })
 649                    .child(
 650                        v_flex()
 651                            .min_h_16()
 652                            .when(is_editor_expanded, |this| this.h_full())
 653                            .child({
 654                                let settings = ThemeSettings::get_global(cx);
 655                                let font_size = TextSize::Small
 656                                    .rems(cx)
 657                                    .to_pixels(settings.agent_font_size(cx));
 658                                let line_height = settings.buffer_line_height.value() * font_size;
 659
 660                                let text_style = TextStyle {
 661                                    color: cx.theme().colors().text,
 662                                    font_family: settings.buffer_font.family.clone(),
 663                                    font_fallbacks: settings.buffer_font.fallbacks.clone(),
 664                                    font_features: settings.buffer_font.features.clone(),
 665                                    font_size: font_size.into(),
 666                                    line_height: line_height.into(),
 667                                    ..Default::default()
 668                                };
 669
 670                                EditorElement::new(
 671                                    &self.editor,
 672                                    EditorStyle {
 673                                        background: editor_bg_color,
 674                                        local_player: cx.theme().players().local(),
 675                                        text: text_style,
 676                                        syntax: cx.theme().syntax().clone(),
 677                                        ..Default::default()
 678                                    },
 679                                )
 680                                .into_any()
 681                            }),
 682                    )
 683                    .child(
 684                        h_flex()
 685                            .flex_none()
 686                            .justify_between()
 687                            .child(
 688                                h_flex()
 689                                    .gap_1()
 690                                    .child(self.render_follow_toggle(cx))
 691                                    .children(self.render_max_mode_toggle(cx)),
 692                            )
 693                            .child(
 694                                h_flex()
 695                                    .gap_1()
 696                                    .when(!incompatible_tools.is_empty(), |this| {
 697                                        this.child(
 698                                            IconButton::new(
 699                                                "tools-incompatible-warning",
 700                                                IconName::Warning,
 701                                            )
 702                                            .icon_color(Color::Warning)
 703                                            .icon_size(IconSize::Small)
 704                                            .tooltip({
 705                                                move |_, cx| {
 706                                                    cx.new(|_| IncompatibleToolsTooltip {
 707                                                        incompatible_tools: incompatible_tools
 708                                                            .clone(),
 709                                                    })
 710                                                    .into()
 711                                                }
 712                                            }),
 713                                        )
 714                                    })
 715                                    .child(self.profile_selector.clone())
 716                                    .child(self.model_selector.clone())
 717                                    .map({
 718                                        let focus_handle = focus_handle.clone();
 719                                        move |parent| {
 720                                            if is_generating {
 721                                                parent
 722                                                    .when(is_editor_empty, |parent| {
 723                                                        parent.child(
 724                                                            IconButton::new(
 725                                                                "stop-generation",
 726                                                                IconName::StopFilled,
 727                                                            )
 728                                                            .icon_color(Color::Error)
 729                                                            .style(ButtonStyle::Tinted(
 730                                                                ui::TintColor::Error,
 731                                                            ))
 732                                                            .tooltip(move |window, cx| {
 733                                                                Tooltip::for_action(
 734                                                                    "Stop Generation",
 735                                                                    &editor::actions::Cancel,
 736                                                                    window,
 737                                                                    cx,
 738                                                                )
 739                                                            })
 740                                                            .on_click({
 741                                                                let focus_handle =
 742                                                                    focus_handle.clone();
 743                                                                move |_event, window, cx| {
 744                                                                    focus_handle.dispatch_action(
 745                                                                        &editor::actions::Cancel,
 746                                                                        window,
 747                                                                        cx,
 748                                                                    );
 749                                                                }
 750                                                            })
 751                                                            .with_animation(
 752                                                                "pulsating-label",
 753                                                                Animation::new(
 754                                                                    Duration::from_secs(2),
 755                                                                )
 756                                                                .repeat()
 757                                                                .with_easing(pulsating_between(
 758                                                                    0.4, 1.0,
 759                                                                )),
 760                                                                |icon_button, delta| {
 761                                                                    icon_button.alpha(delta)
 762                                                                },
 763                                                            ),
 764                                                        )
 765                                                    })
 766                                                    .when(!is_editor_empty, |parent| {
 767                                                        parent.child(
 768                                                            IconButton::new(
 769                                                                "send-message",
 770                                                                IconName::Send,
 771                                                            )
 772                                                            .icon_color(Color::Accent)
 773                                                            .style(ButtonStyle::Filled)
 774                                                            .disabled(!is_model_selected)
 775                                                            .on_click({
 776                                                                let focus_handle =
 777                                                                    focus_handle.clone();
 778                                                                move |_event, window, cx| {
 779                                                                    focus_handle.dispatch_action(
 780                                                                        &Chat, window, cx,
 781                                                                    );
 782                                                                }
 783                                                            })
 784                                                            .tooltip(move |window, cx| {
 785                                                                Tooltip::for_action(
 786                                                                    "Stop and Send New Message",
 787                                                                    &Chat,
 788                                                                    window,
 789                                                                    cx,
 790                                                                )
 791                                                            }),
 792                                                        )
 793                                                    })
 794                                            } else {
 795                                                parent.child(
 796                                                    IconButton::new("send-message", IconName::Send)
 797                                                        .icon_color(Color::Accent)
 798                                                        .style(ButtonStyle::Filled)
 799                                                        .disabled(
 800                                                            is_editor_empty || !is_model_selected,
 801                                                        )
 802                                                        .on_click({
 803                                                            let focus_handle = focus_handle.clone();
 804                                                            move |_event, window, cx| {
 805                                                                focus_handle.dispatch_action(
 806                                                                    &Chat, window, cx,
 807                                                                );
 808                                                            }
 809                                                        })
 810                                                        .when(
 811                                                            !is_editor_empty && is_model_selected,
 812                                                            |button| {
 813                                                                button.tooltip(move |window, cx| {
 814                                                                    Tooltip::for_action(
 815                                                                        "Send", &Chat, window, cx,
 816                                                                    )
 817                                                                })
 818                                                            },
 819                                                        )
 820                                                        .when(is_editor_empty, |button| {
 821                                                            button.tooltip(Tooltip::text(
 822                                                                "Type a message to submit",
 823                                                            ))
 824                                                        })
 825                                                        .when(!is_model_selected, |button| {
 826                                                            button.tooltip(Tooltip::text(
 827                                                                "Select a model to continue",
 828                                                            ))
 829                                                        }),
 830                                                )
 831                                            }
 832                                        }
 833                                    }),
 834                            ),
 835                    ),
 836            )
 837    }
 838
 839    fn render_changed_buffers(
 840        &self,
 841        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
 842        window: &mut Window,
 843        cx: &mut Context<Self>,
 844    ) -> Div {
 845        let focus_handle = self.editor.focus_handle(cx);
 846
 847        let editor_bg_color = cx.theme().colors().editor_background;
 848        let border_color = cx.theme().colors().border;
 849        let active_color = cx.theme().colors().element_selected;
 850        let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
 851
 852        let is_edit_changes_expanded = self.edits_expanded;
 853        let is_generating = self.thread.read(cx).is_generating();
 854
 855        v_flex()
 856            .mt_1()
 857            .mx_2()
 858            .bg(bg_edit_files_disclosure)
 859            .border_1()
 860            .border_b_0()
 861            .border_color(border_color)
 862            .rounded_t_md()
 863            .shadow(vec![gpui::BoxShadow {
 864                color: gpui::black().opacity(0.15),
 865                offset: point(px(1.), px(-1.)),
 866                blur_radius: px(3.),
 867                spread_radius: px(0.),
 868            }])
 869            .child(
 870                h_flex()
 871                    .id("edits-container")
 872                    .cursor_pointer()
 873                    .p_1p5()
 874                    .justify_between()
 875                    .when(is_edit_changes_expanded, |this| {
 876                        this.border_b_1().border_color(border_color)
 877                    })
 878                    .on_click(
 879                        cx.listener(|this, _, window, cx| this.handle_review_click(window, cx)),
 880                    )
 881                    .child(
 882                        h_flex()
 883                            .gap_1()
 884                            .child(
 885                                Disclosure::new("edits-disclosure", is_edit_changes_expanded)
 886                                    .on_click(cx.listener(|this, _ev, _window, cx| {
 887                                        this.edits_expanded = !this.edits_expanded;
 888                                        cx.notify();
 889                                    })),
 890                            )
 891                            .map(|this| {
 892                                if is_generating {
 893                                    this.child(
 894                                        AnimatedLabel::new(format!(
 895                                            "Editing {} {}",
 896                                            changed_buffers.len(),
 897                                            if changed_buffers.len() == 1 {
 898                                                "file"
 899                                            } else {
 900                                                "files"
 901                                            }
 902                                        ))
 903                                        .size(LabelSize::Small),
 904                                    )
 905                                } else {
 906                                    this.child(
 907                                        Label::new("Edits")
 908                                            .size(LabelSize::Small)
 909                                            .color(Color::Muted),
 910                                    )
 911                                    .child(
 912                                        Label::new("").size(LabelSize::XSmall).color(Color::Muted),
 913                                    )
 914                                    .child(
 915                                        Label::new(format!(
 916                                            "{} {}",
 917                                            changed_buffers.len(),
 918                                            if changed_buffers.len() == 1 {
 919                                                "file"
 920                                            } else {
 921                                                "files"
 922                                            }
 923                                        ))
 924                                        .size(LabelSize::Small)
 925                                        .color(Color::Muted),
 926                                    )
 927                                }
 928                            }),
 929                    )
 930                    .child(
 931                        Button::new("review", "Review Changes")
 932                            .label_size(LabelSize::Small)
 933                            .key_binding(
 934                                KeyBinding::for_action_in(
 935                                    &OpenAgentDiff,
 936                                    &focus_handle,
 937                                    window,
 938                                    cx,
 939                                )
 940                                .map(|kb| kb.size(rems_from_px(12.))),
 941                            )
 942                            .on_click(cx.listener(|this, _, window, cx| {
 943                                this.handle_review_click(window, cx)
 944                            })),
 945                    ),
 946            )
 947            .when(is_edit_changes_expanded, |parent| {
 948                parent.child(
 949                    v_flex().children(changed_buffers.into_iter().enumerate().flat_map(
 950                        |(index, (buffer, _diff))| {
 951                            let file = buffer.read(cx).file()?;
 952                            let path = file.path();
 953
 954                            let parent_label = path.parent().and_then(|parent| {
 955                                let parent_str = parent.to_string_lossy();
 956
 957                                if parent_str.is_empty() {
 958                                    None
 959                                } else {
 960                                    Some(
 961                                        Label::new(format!(
 962                                            "/{}{}",
 963                                            parent_str,
 964                                            std::path::MAIN_SEPARATOR_STR
 965                                        ))
 966                                        .color(Color::Muted)
 967                                        .size(LabelSize::XSmall)
 968                                        .buffer_font(cx),
 969                                    )
 970                                }
 971                            });
 972
 973                            let name_label = path.file_name().map(|name| {
 974                                Label::new(name.to_string_lossy().to_string())
 975                                    .size(LabelSize::XSmall)
 976                                    .buffer_font(cx)
 977                            });
 978
 979                            let file_icon = FileIcons::get_icon(&path, cx)
 980                                .map(Icon::from_path)
 981                                .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
 982                                .unwrap_or_else(|| {
 983                                    Icon::new(IconName::File)
 984                                        .color(Color::Muted)
 985                                        .size(IconSize::Small)
 986                                });
 987
 988                            let hover_color = cx
 989                                .theme()
 990                                .colors()
 991                                .element_background
 992                                .blend(cx.theme().colors().editor_foreground.opacity(0.025));
 993
 994                            let overlay_gradient = linear_gradient(
 995                                90.,
 996                                linear_color_stop(editor_bg_color, 1.),
 997                                linear_color_stop(editor_bg_color.opacity(0.2), 0.),
 998                            );
 999
1000                            let overlay_gradient_hover = linear_gradient(
1001                                90.,
1002                                linear_color_stop(hover_color, 1.),
1003                                linear_color_stop(hover_color.opacity(0.2), 0.),
1004                            );
1005
1006                            let element = h_flex()
1007                                .group("edited-code")
1008                                .id(("file-container", index))
1009                                .cursor_pointer()
1010                                .relative()
1011                                .py_1()
1012                                .pl_2()
1013                                .pr_1()
1014                                .gap_2()
1015                                .justify_between()
1016                                .bg(cx.theme().colors().editor_background)
1017                                .hover(|style| style.bg(hover_color))
1018                                .when(index < changed_buffers.len() - 1, |parent| {
1019                                    parent.border_color(border_color).border_b_1()
1020                                })
1021                                .child(
1022                                    h_flex()
1023                                        .id("file-name")
1024                                        .pr_8()
1025                                        .gap_1p5()
1026                                        .max_w_full()
1027                                        .overflow_x_scroll()
1028                                        .child(file_icon)
1029                                        .child(
1030                                            h_flex()
1031                                                .gap_0p5()
1032                                                .children(name_label)
1033                                                .children(parent_label),
1034                                        ), // TODO: Implement line diff
1035                                           // .child(Label::new("+").color(Color::Created))
1036                                           // .child(Label::new("-").color(Color::Deleted)),
1037                                )
1038                                .child(
1039                                    div().visible_on_hover("edited-code").child(
1040                                        Button::new("review", "Review")
1041                                            .label_size(LabelSize::Small)
1042                                            .on_click({
1043                                                let buffer = buffer.clone();
1044                                                cx.listener(move |this, _, window, cx| {
1045                                                    this.handle_file_click(
1046                                                        buffer.clone(),
1047                                                        window,
1048                                                        cx,
1049                                                    );
1050                                                })
1051                                            }),
1052                                    ),
1053                                )
1054                                .child(
1055                                    div()
1056                                        .id("gradient-overlay")
1057                                        .absolute()
1058                                        .h_5_6()
1059                                        .w_12()
1060                                        .bottom_0()
1061                                        .right(px(52.))
1062                                        .bg(overlay_gradient)
1063                                        .group_hover("edited-code", |style| {
1064                                            style.bg(overlay_gradient_hover)
1065                                        }),
1066                                )
1067                                .on_click({
1068                                    let buffer = buffer.clone();
1069                                    cx.listener(move |this, _, window, cx| {
1070                                        this.handle_file_click(buffer.clone(), window, cx);
1071                                    })
1072                                });
1073
1074                            Some(element)
1075                        },
1076                    )),
1077                )
1078            })
1079    }
1080
1081    fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
1082        let is_using_zed_provider = self
1083            .thread
1084            .read(cx)
1085            .configured_model()
1086            .map_or(false, |model| {
1087                model.provider.id().0 == ZED_CLOUD_PROVIDER_ID
1088            });
1089        if !is_using_zed_provider {
1090            return None;
1091        }
1092
1093        let user_store = self.user_store.read(cx);
1094
1095        let ubb_enable = user_store
1096            .usage_based_billing_enabled()
1097            .map_or(false, |enabled| enabled);
1098
1099        if ubb_enable {
1100            return None;
1101        }
1102
1103        let plan = user_store
1104            .current_plan()
1105            .map(|plan| match plan {
1106                Plan::Free => zed_llm_client::Plan::ZedFree,
1107                Plan::ZedPro => zed_llm_client::Plan::ZedPro,
1108                Plan::ZedProTrial => zed_llm_client::Plan::ZedProTrial,
1109            })
1110            .unwrap_or(zed_llm_client::Plan::ZedFree);
1111        let usage = self.thread.read(cx).last_usage().or_else(|| {
1112            maybe!({
1113                let amount = user_store.model_request_usage_amount()?;
1114                let limit = user_store.model_request_usage_limit()?.variant?;
1115
1116                Some(RequestUsage {
1117                    amount: amount as i32,
1118                    limit: match limit {
1119                        proto::usage_limit::Variant::Limited(limited) => {
1120                            zed_llm_client::UsageLimit::Limited(limited.limit as i32)
1121                        }
1122                        proto::usage_limit::Variant::Unlimited(_) => {
1123                            zed_llm_client::UsageLimit::Unlimited
1124                        }
1125                    },
1126                })
1127            })
1128        })?;
1129
1130        Some(
1131            div()
1132                .child(UsageCallout::new(plan, usage))
1133                .line_height(line_height),
1134        )
1135    }
1136
1137    fn render_token_limit_callout(
1138        &self,
1139        line_height: Pixels,
1140        token_usage_ratio: TokenUsageRatio,
1141        cx: &mut Context<Self>,
1142    ) -> Option<Div> {
1143        let title = if token_usage_ratio == TokenUsageRatio::Exceeded {
1144            "Thread reached the token limit"
1145        } else {
1146            "Thread reaching the token limit soon"
1147        };
1148
1149        let message = "Start a new thread from a summary to continue the conversation.";
1150
1151        let icon = if token_usage_ratio == TokenUsageRatio::Exceeded {
1152            Icon::new(IconName::X)
1153                .color(Color::Error)
1154                .size(IconSize::XSmall)
1155        } else {
1156            Icon::new(IconName::Warning)
1157                .color(Color::Warning)
1158                .size(IconSize::XSmall)
1159        };
1160
1161        Some(
1162            div()
1163                .child(ui::Callout::multi_line(
1164                    title,
1165                    message,
1166                    icon,
1167                    "Start New Thread",
1168                    Box::new(cx.listener(|this, _, window, cx| {
1169                        let from_thread_id = Some(this.thread.read(cx).id().clone());
1170                        window.dispatch_action(Box::new(NewThread { from_thread_id }), cx);
1171                    })),
1172                ))
1173                .line_height(line_height),
1174        )
1175    }
1176
1177    pub fn last_estimated_token_count(&self) -> Option<usize> {
1178        self.last_estimated_token_count
1179    }
1180
1181    pub fn is_waiting_to_update_token_count(&self) -> bool {
1182        self.update_token_count_task.is_some()
1183    }
1184
1185    fn reload_context(&mut self, cx: &mut Context<Self>) -> Task<Option<ContextLoadResult>> {
1186        let load_task = cx.spawn(async move |this, cx| {
1187            let Ok(load_task) = this.update(cx, |this, cx| {
1188                let new_context = this
1189                    .context_store
1190                    .read(cx)
1191                    .new_context_for_thread(this.thread.read(cx), None);
1192                load_context(new_context, &this.project, &this.prompt_store, cx)
1193            }) else {
1194                return;
1195            };
1196            let result = load_task.await;
1197            this.update(cx, |this, cx| {
1198                this.last_loaded_context = Some(result);
1199                this.load_context_task = None;
1200                this.message_or_context_changed(false, cx);
1201            })
1202            .ok();
1203        });
1204        // Replace existing load task, if any, causing it to be cancelled.
1205        let load_task = load_task.shared();
1206        self.load_context_task = Some(load_task.clone());
1207        cx.spawn(async move |this, cx| {
1208            load_task.await;
1209            this.read_with(cx, |this, _cx| this.last_loaded_context.clone())
1210                .ok()
1211                .flatten()
1212        })
1213    }
1214
1215    fn handle_message_changed(&mut self, cx: &mut Context<Self>) {
1216        self.message_or_context_changed(true, cx);
1217    }
1218
1219    fn message_or_context_changed(&mut self, debounce: bool, cx: &mut Context<Self>) {
1220        cx.emit(MessageEditorEvent::Changed);
1221        self.update_token_count_task.take();
1222
1223        let Some(model) = self.thread.read(cx).configured_model() else {
1224            self.last_estimated_token_count.take();
1225            return;
1226        };
1227
1228        let editor = self.editor.clone();
1229
1230        self.update_token_count_task = Some(cx.spawn(async move |this, cx| {
1231            if debounce {
1232                cx.background_executor()
1233                    .timer(Duration::from_millis(200))
1234                    .await;
1235            }
1236
1237            let token_count = if let Some(task) = this
1238                .update(cx, |this, cx| {
1239                    let loaded_context = this
1240                        .last_loaded_context
1241                        .as_ref()
1242                        .map(|context_load_result| &context_load_result.loaded_context);
1243                    let message_text = editor.read(cx).text(cx);
1244
1245                    if message_text.is_empty()
1246                        && loaded_context.map_or(true, |loaded_context| loaded_context.is_empty())
1247                    {
1248                        return None;
1249                    }
1250
1251                    let mut request_message = LanguageModelRequestMessage {
1252                        role: language_model::Role::User,
1253                        content: Vec::new(),
1254                        cache: false,
1255                    };
1256
1257                    if let Some(loaded_context) = loaded_context {
1258                        loaded_context.add_to_request_message(&mut request_message);
1259                    }
1260
1261                    if !message_text.is_empty() {
1262                        request_message
1263                            .content
1264                            .push(MessageContent::Text(message_text));
1265                    }
1266
1267                    let request = language_model::LanguageModelRequest {
1268                        thread_id: None,
1269                        prompt_id: None,
1270                        mode: None,
1271                        messages: vec![request_message],
1272                        tools: vec![],
1273                        tool_choice: None,
1274                        stop: vec![],
1275                        temperature: AgentSettings::temperature_for_model(&model.model, cx),
1276                    };
1277
1278                    Some(model.model.count_tokens(request, cx))
1279                })
1280                .ok()
1281                .flatten()
1282            {
1283                task.await.log_err()
1284            } else {
1285                Some(0)
1286            };
1287
1288            this.update(cx, |this, cx| {
1289                if let Some(token_count) = token_count {
1290                    this.last_estimated_token_count = Some(token_count);
1291                    cx.emit(MessageEditorEvent::EstimatedTokenCount);
1292                }
1293                this.update_token_count_task.take();
1294            })
1295            .ok();
1296        }));
1297    }
1298}
1299
1300pub fn extract_message_creases(
1301    editor: &mut Editor,
1302    cx: &mut Context<'_, Editor>,
1303) -> Vec<MessageCrease> {
1304    let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1305    let mut contexts_by_crease_id = editor
1306        .addon_mut::<ContextCreasesAddon>()
1307        .map(std::mem::take)
1308        .unwrap_or_default()
1309        .into_inner()
1310        .into_iter()
1311        .flat_map(|(key, creases)| {
1312            let context = key.0;
1313            creases
1314                .into_iter()
1315                .map(move |(id, _)| (id, context.clone()))
1316        })
1317        .collect::<HashMap<_, _>>();
1318    // Filter the addon's list of creases based on what the editor reports,
1319    // since the addon might have removed creases in it.
1320    let creases = editor.display_map.update(cx, |display_map, cx| {
1321        display_map
1322            .snapshot(cx)
1323            .crease_snapshot
1324            .creases()
1325            .filter_map(|(id, crease)| {
1326                Some((
1327                    id,
1328                    (
1329                        crease.range().to_offset(&buffer_snapshot),
1330                        crease.metadata()?.clone(),
1331                    ),
1332                ))
1333            })
1334            .map(|(id, (range, metadata))| {
1335                let context = contexts_by_crease_id.remove(&id);
1336                MessageCrease {
1337                    range,
1338                    metadata,
1339                    context,
1340                }
1341            })
1342            .collect()
1343    });
1344    creases
1345}
1346
1347impl EventEmitter<MessageEditorEvent> for MessageEditor {}
1348
1349pub enum MessageEditorEvent {
1350    EstimatedTokenCount,
1351    Changed,
1352}
1353
1354impl Focusable for MessageEditor {
1355    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
1356        self.editor.focus_handle(cx)
1357    }
1358}
1359
1360impl Render for MessageEditor {
1361    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1362        let thread = self.thread.read(cx);
1363        let token_usage_ratio = thread
1364            .total_token_usage()
1365            .map_or(TokenUsageRatio::Normal, |total_token_usage| {
1366                total_token_usage.ratio()
1367            });
1368
1369        let action_log = self.thread.read(cx).action_log();
1370        let changed_buffers = action_log.read(cx).changed_buffers(cx);
1371
1372        let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
1373
1374        v_flex()
1375            .size_full()
1376            .when(changed_buffers.len() > 0, |parent| {
1377                parent.child(self.render_changed_buffers(&changed_buffers, window, cx))
1378            })
1379            .child(self.render_editor(window, cx))
1380            .children({
1381                let usage_callout = self.render_usage_callout(line_height, cx);
1382
1383                if usage_callout.is_some() {
1384                    usage_callout
1385                } else if token_usage_ratio != TokenUsageRatio::Normal {
1386                    self.render_token_limit_callout(line_height, token_usage_ratio, cx)
1387                } else {
1388                    None
1389                }
1390            })
1391    }
1392}
1393
1394pub fn insert_message_creases(
1395    editor: &mut Editor,
1396    message_creases: &[MessageCrease],
1397    context_store: &Entity<ContextStore>,
1398    window: &mut Window,
1399    cx: &mut Context<'_, Editor>,
1400) {
1401    let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1402    let creases = message_creases
1403        .iter()
1404        .map(|crease| {
1405            let start = buffer_snapshot.anchor_after(crease.range.start);
1406            let end = buffer_snapshot.anchor_before(crease.range.end);
1407            crease_for_mention(
1408                crease.metadata.label.clone(),
1409                crease.metadata.icon_path.clone(),
1410                start..end,
1411                cx.weak_entity(),
1412            )
1413        })
1414        .collect::<Vec<_>>();
1415    let ids = editor.insert_creases(creases.clone(), cx);
1416    editor.fold_creases(creases, false, window, cx);
1417    if let Some(addon) = editor.addon_mut::<ContextCreasesAddon>() {
1418        for (crease, id) in message_creases.iter().zip(ids) {
1419            if let Some(context) = crease.context.as_ref() {
1420                let key = AgentContextKey(context.clone());
1421                addon.add_creases(
1422                    context_store,
1423                    key,
1424                    vec![(id, crease.metadata.label.clone())],
1425                    cx,
1426                );
1427            }
1428        }
1429    }
1430}
1431impl Component for MessageEditor {
1432    fn scope() -> ComponentScope {
1433        ComponentScope::Agent
1434    }
1435
1436    fn description() -> Option<&'static str> {
1437        Some(
1438            "The composer experience of the Agent Panel. This interface handles context, composing messages, switching profiles, models and more.",
1439        )
1440    }
1441}
1442
1443impl AgentPreview for MessageEditor {
1444    fn agent_preview(
1445        workspace: WeakEntity<Workspace>,
1446        active_thread: Entity<ActiveThread>,
1447        window: &mut Window,
1448        cx: &mut App,
1449    ) -> Option<AnyElement> {
1450        if let Some(workspace) = workspace.upgrade() {
1451            let fs = workspace.read(cx).app_state().fs.clone();
1452            let user_store = workspace.read(cx).app_state().user_store.clone();
1453            let project = workspace.read(cx).project().clone();
1454            let weak_project = project.downgrade();
1455            let context_store = cx.new(|_cx| ContextStore::new(weak_project, None));
1456            let active_thread = active_thread.read(cx);
1457            let thread = active_thread.thread().clone();
1458            let thread_store = active_thread.thread_store().clone();
1459            let text_thread_store = active_thread.text_thread_store().clone();
1460
1461            let default_message_editor = cx.new(|cx| {
1462                MessageEditor::new(
1463                    fs,
1464                    workspace.downgrade(),
1465                    user_store,
1466                    context_store,
1467                    None,
1468                    thread_store.downgrade(),
1469                    text_thread_store.downgrade(),
1470                    thread,
1471                    window,
1472                    cx,
1473                )
1474            });
1475
1476            Some(
1477                v_flex()
1478                    .gap_4()
1479                    .children(vec![single_example(
1480                        "Default Message Editor",
1481                        div()
1482                            .w(px(540.))
1483                            .pt_12()
1484                            .bg(cx.theme().colors().panel_background)
1485                            .border_1()
1486                            .border_color(cx.theme().colors().border)
1487                            .child(default_message_editor.clone())
1488                            .into_any_element(),
1489                    )])
1490                    .into_any_element(),
1491            )
1492        } else {
1493            None
1494        }
1495    }
1496}
1497
1498register_agent_preview!(MessageEditor);