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