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