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