message_editor.rs

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