message_editor.rs

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