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                            .flex_wrap()
 726                            .justify_between()
 727                            .child(
 728                                h_flex()
 729                                    .child(self.render_follow_toggle(cx))
 730                                    .children(self.render_max_mode_toggle(cx)),
 731                            )
 732                            .child(
 733                                h_flex()
 734                                    .gap_1()
 735                                    .flex_wrap()
 736                                    .when(!incompatible_tools.is_empty(), |this| {
 737                                        this.child(
 738                                            IconButton::new(
 739                                                "tools-incompatible-warning",
 740                                                IconName::Warning,
 741                                            )
 742                                            .icon_color(Color::Warning)
 743                                            .icon_size(IconSize::Small)
 744                                            .tooltip({
 745                                                move |_, cx| {
 746                                                    cx.new(|_| IncompatibleToolsTooltip {
 747                                                        incompatible_tools: incompatible_tools
 748                                                            .clone(),
 749                                                    })
 750                                                    .into()
 751                                                }
 752                                            }),
 753                                        )
 754                                    })
 755                                    .child(self.profile_selector.clone())
 756                                    .child(self.model_selector.clone())
 757                                    .map({
 758                                        let focus_handle = focus_handle.clone();
 759                                        move |parent| {
 760                                            if is_generating {
 761                                                parent
 762                                                    .when(is_editor_empty, |parent| {
 763                                                        parent.child(
 764                                                            IconButton::new(
 765                                                                "stop-generation",
 766                                                                IconName::StopFilled,
 767                                                            )
 768                                                            .icon_color(Color::Error)
 769                                                            .style(ButtonStyle::Tinted(
 770                                                                ui::TintColor::Error,
 771                                                            ))
 772                                                            .tooltip(move |window, cx| {
 773                                                                Tooltip::for_action(
 774                                                                    "Stop Generation",
 775                                                                    &editor::actions::Cancel,
 776                                                                    window,
 777                                                                    cx,
 778                                                                )
 779                                                            })
 780                                                            .on_click({
 781                                                                let focus_handle =
 782                                                                    focus_handle.clone();
 783                                                                move |_event, window, cx| {
 784                                                                    focus_handle.dispatch_action(
 785                                                                        &editor::actions::Cancel,
 786                                                                        window,
 787                                                                        cx,
 788                                                                    );
 789                                                                }
 790                                                            })
 791                                                            .with_animation(
 792                                                                "pulsating-label",
 793                                                                Animation::new(
 794                                                                    Duration::from_secs(2),
 795                                                                )
 796                                                                .repeat()
 797                                                                .with_easing(pulsating_between(
 798                                                                    0.4, 1.0,
 799                                                                )),
 800                                                                |icon_button, delta| {
 801                                                                    icon_button.alpha(delta)
 802                                                                },
 803                                                            ),
 804                                                        )
 805                                                    })
 806                                                    .when(!is_editor_empty, |parent| {
 807                                                        parent.child(
 808                                                            IconButton::new(
 809                                                                "send-message",
 810                                                                IconName::Send,
 811                                                            )
 812                                                            .icon_color(Color::Accent)
 813                                                            .style(ButtonStyle::Filled)
 814                                                            .disabled(!is_model_selected)
 815                                                            .on_click({
 816                                                                let focus_handle =
 817                                                                    focus_handle.clone();
 818                                                                move |_event, window, cx| {
 819                                                                    focus_handle.dispatch_action(
 820                                                                        &Chat, window, cx,
 821                                                                    );
 822                                                                }
 823                                                            })
 824                                                            .tooltip(move |window, cx| {
 825                                                                Tooltip::for_action(
 826                                                                    "Stop and Send New Message",
 827                                                                    &Chat,
 828                                                                    window,
 829                                                                    cx,
 830                                                                )
 831                                                            }),
 832                                                        )
 833                                                    })
 834                                            } else {
 835                                                parent.child(
 836                                                    IconButton::new("send-message", IconName::Send)
 837                                                        .icon_color(Color::Accent)
 838                                                        .style(ButtonStyle::Filled)
 839                                                        .disabled(
 840                                                            is_editor_empty || !is_model_selected,
 841                                                        )
 842                                                        .on_click({
 843                                                            let focus_handle = focus_handle.clone();
 844                                                            move |_event, window, cx| {
 845                                                                focus_handle.dispatch_action(
 846                                                                    &Chat, window, cx,
 847                                                                );
 848                                                            }
 849                                                        })
 850                                                        .when(
 851                                                            !is_editor_empty && is_model_selected,
 852                                                            |button| {
 853                                                                button.tooltip(move |window, cx| {
 854                                                                    Tooltip::for_action(
 855                                                                        "Send", &Chat, window, cx,
 856                                                                    )
 857                                                                })
 858                                                            },
 859                                                        )
 860                                                        .when(is_editor_empty, |button| {
 861                                                            button.tooltip(Tooltip::text(
 862                                                                "Type a message to submit",
 863                                                            ))
 864                                                        })
 865                                                        .when(!is_model_selected, |button| {
 866                                                            button.tooltip(Tooltip::text(
 867                                                                "Select a model to continue",
 868                                                            ))
 869                                                        }),
 870                                                )
 871                                            }
 872                                        }
 873                                    }),
 874                            ),
 875                    ),
 876            )
 877    }
 878
 879    fn render_changed_buffers(
 880        &self,
 881        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
 882        window: &mut Window,
 883        cx: &mut Context<Self>,
 884    ) -> Div {
 885        let focus_handle = self.editor.focus_handle(cx);
 886
 887        let editor_bg_color = cx.theme().colors().editor_background;
 888        let border_color = cx.theme().colors().border;
 889        let active_color = cx.theme().colors().element_selected;
 890        let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
 891
 892        let is_edit_changes_expanded = self.edits_expanded;
 893        let thread = self.thread.read(cx);
 894        let pending_edits = thread.has_pending_edit_tool_uses();
 895
 896        const EDIT_NOT_READY_TOOLTIP_LABEL: &str = "Wait until file edits are complete.";
 897
 898        v_flex()
 899            .mt_1()
 900            .mx_2()
 901            .bg(bg_edit_files_disclosure)
 902            .border_1()
 903            .border_b_0()
 904            .border_color(border_color)
 905            .rounded_t_md()
 906            .shadow(vec![gpui::BoxShadow {
 907                color: gpui::black().opacity(0.15),
 908                offset: point(px(1.), px(-1.)),
 909                blur_radius: px(3.),
 910                spread_radius: px(0.),
 911            }])
 912            .child(
 913                h_flex()
 914                    .p_1()
 915                    .justify_between()
 916                    .when(is_edit_changes_expanded, |this| {
 917                        this.border_b_1().border_color(border_color)
 918                    })
 919                    .child(
 920                        h_flex()
 921                            .id("edits-container")
 922                            .cursor_pointer()
 923                            .w_full()
 924                            .gap_1()
 925                            .child(
 926                                Disclosure::new("edits-disclosure", is_edit_changes_expanded)
 927                                    .on_click(cx.listener(|this, _, _, cx| {
 928                                        this.handle_edit_bar_expand(cx)
 929                                    })),
 930                            )
 931                            .map(|this| {
 932                                if pending_edits {
 933                                    this.child(
 934                                        Label::new(format!(
 935                                            "Editing {} {}",
 936                                            changed_buffers.len(),
 937                                            if changed_buffers.len() == 1 {
 938                                                "file"
 939                                            } else {
 940                                                "files"
 941                                            }
 942                                        ))
 943                                        .color(Color::Muted)
 944                                        .size(LabelSize::Small)
 945                                        .with_animation(
 946                                            "edit-label",
 947                                            Animation::new(Duration::from_secs(2))
 948                                                .repeat()
 949                                                .with_easing(pulsating_between(0.3, 0.7)),
 950                                            |label, delta| label.alpha(delta),
 951                                        ),
 952                                    )
 953                                } else {
 954                                    this.child(
 955                                        Label::new("Edits")
 956                                            .size(LabelSize::Small)
 957                                            .color(Color::Muted),
 958                                    )
 959                                    .child(
 960                                        Label::new("").size(LabelSize::XSmall).color(Color::Muted),
 961                                    )
 962                                    .child(
 963                                        Label::new(format!(
 964                                            "{} {}",
 965                                            changed_buffers.len(),
 966                                            if changed_buffers.len() == 1 {
 967                                                "file"
 968                                            } else {
 969                                                "files"
 970                                            }
 971                                        ))
 972                                        .size(LabelSize::Small)
 973                                        .color(Color::Muted),
 974                                    )
 975                                }
 976                            })
 977                            .on_click(
 978                                cx.listener(|this, _, _, cx| this.handle_edit_bar_expand(cx)),
 979                            ),
 980                    )
 981                    .child(
 982                        h_flex()
 983                            .gap_1()
 984                            .child(
 985                                IconButton::new("review-changes", IconName::ListTodo)
 986                                    .icon_size(IconSize::Small)
 987                                    .tooltip({
 988                                        let focus_handle = focus_handle.clone();
 989                                        move |window, cx| {
 990                                            Tooltip::for_action_in(
 991                                                "Review Changes",
 992                                                &OpenAgentDiff,
 993                                                &focus_handle,
 994                                                window,
 995                                                cx,
 996                                            )
 997                                        }
 998                                    })
 999                                    .on_click(cx.listener(|this, _, window, cx| {
1000                                        this.handle_review_click(window, cx)
1001                                    })),
1002                            )
1003                            .child(ui::Divider::vertical().color(ui::DividerColor::Border))
1004                            .child(
1005                                Button::new("reject-all-changes", "Reject All")
1006                                    .label_size(LabelSize::Small)
1007                                    .disabled(pending_edits)
1008                                    .when(pending_edits, |this| {
1009                                        this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
1010                                    })
1011                                    .key_binding(
1012                                        KeyBinding::for_action_in(
1013                                            &RejectAll,
1014                                            &focus_handle.clone(),
1015                                            window,
1016                                            cx,
1017                                        )
1018                                        .map(|kb| kb.size(rems_from_px(10.))),
1019                                    )
1020                                    .on_click(cx.listener(|this, _, window, cx| {
1021                                        this.handle_reject_all(window, cx)
1022                                    })),
1023                            )
1024                            .child(
1025                                Button::new("accept-all-changes", "Accept All")
1026                                    .label_size(LabelSize::Small)
1027                                    .disabled(pending_edits)
1028                                    .when(pending_edits, |this| {
1029                                        this.tooltip(Tooltip::text(EDIT_NOT_READY_TOOLTIP_LABEL))
1030                                    })
1031                                    .key_binding(
1032                                        KeyBinding::for_action_in(
1033                                            &KeepAll,
1034                                            &focus_handle,
1035                                            window,
1036                                            cx,
1037                                        )
1038                                        .map(|kb| kb.size(rems_from_px(10.))),
1039                                    )
1040                                    .on_click(cx.listener(|this, _, window, cx| {
1041                                        this.handle_accept_all(window, cx)
1042                                    })),
1043                            ),
1044                    ),
1045            )
1046            .when(is_edit_changes_expanded, |parent| {
1047                parent.child(
1048                    v_flex().children(changed_buffers.into_iter().enumerate().flat_map(
1049                        |(index, (buffer, _diff))| {
1050                            let file = buffer.read(cx).file()?;
1051                            let path = file.path();
1052
1053                            let parent_label = path.parent().and_then(|parent| {
1054                                let parent_str = parent.to_string_lossy();
1055
1056                                if parent_str.is_empty() {
1057                                    None
1058                                } else {
1059                                    Some(
1060                                        Label::new(format!(
1061                                            "/{}{}",
1062                                            parent_str,
1063                                            std::path::MAIN_SEPARATOR_STR
1064                                        ))
1065                                        .color(Color::Muted)
1066                                        .size(LabelSize::XSmall)
1067                                        .buffer_font(cx),
1068                                    )
1069                                }
1070                            });
1071
1072                            let name_label = path.file_name().map(|name| {
1073                                Label::new(name.to_string_lossy().to_string())
1074                                    .size(LabelSize::XSmall)
1075                                    .buffer_font(cx)
1076                            });
1077
1078                            let file_icon = FileIcons::get_icon(&path, cx)
1079                                .map(Icon::from_path)
1080                                .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
1081                                .unwrap_or_else(|| {
1082                                    Icon::new(IconName::File)
1083                                        .color(Color::Muted)
1084                                        .size(IconSize::Small)
1085                                });
1086
1087                            let hover_color = cx
1088                                .theme()
1089                                .colors()
1090                                .element_background
1091                                .blend(cx.theme().colors().editor_foreground.opacity(0.025));
1092
1093                            let overlay_gradient = linear_gradient(
1094                                90.,
1095                                linear_color_stop(editor_bg_color, 1.),
1096                                linear_color_stop(editor_bg_color.opacity(0.2), 0.),
1097                            );
1098
1099                            let overlay_gradient_hover = linear_gradient(
1100                                90.,
1101                                linear_color_stop(hover_color, 1.),
1102                                linear_color_stop(hover_color.opacity(0.2), 0.),
1103                            );
1104
1105                            let element = h_flex()
1106                                .group("edited-code")
1107                                .id(("file-container", index))
1108                                .cursor_pointer()
1109                                .relative()
1110                                .py_1()
1111                                .pl_2()
1112                                .pr_1()
1113                                .gap_2()
1114                                .justify_between()
1115                                .bg(cx.theme().colors().editor_background)
1116                                .hover(|style| style.bg(hover_color))
1117                                .when(index < changed_buffers.len() - 1, |parent| {
1118                                    parent.border_color(border_color).border_b_1()
1119                                })
1120                                .child(
1121                                    h_flex()
1122                                        .id("file-name")
1123                                        .pr_8()
1124                                        .gap_1p5()
1125                                        .max_w_full()
1126                                        .overflow_x_scroll()
1127                                        .child(file_icon)
1128                                        .child(
1129                                            h_flex()
1130                                                .gap_0p5()
1131                                                .children(name_label)
1132                                                .children(parent_label),
1133                                        ), // TODO: Implement line diff
1134                                           // .child(Label::new("+").color(Color::Created))
1135                                           // .child(Label::new("-").color(Color::Deleted)),
1136                                )
1137                                .child(
1138                                    div().visible_on_hover("edited-code").child(
1139                                        Button::new("review", "Review")
1140                                            .label_size(LabelSize::Small)
1141                                            .on_click({
1142                                                let buffer = buffer.clone();
1143                                                cx.listener(move |this, _, window, cx| {
1144                                                    this.handle_file_click(
1145                                                        buffer.clone(),
1146                                                        window,
1147                                                        cx,
1148                                                    );
1149                                                })
1150                                            }),
1151                                    ),
1152                                )
1153                                .child(
1154                                    div()
1155                                        .id("gradient-overlay")
1156                                        .absolute()
1157                                        .h_5_6()
1158                                        .w_12()
1159                                        .bottom_0()
1160                                        .right(px(52.))
1161                                        .bg(overlay_gradient)
1162                                        .group_hover("edited-code", |style| {
1163                                            style.bg(overlay_gradient_hover)
1164                                        }),
1165                                )
1166                                .on_click({
1167                                    let buffer = buffer.clone();
1168                                    cx.listener(move |this, _, window, cx| {
1169                                        this.handle_file_click(buffer.clone(), window, cx);
1170                                    })
1171                                });
1172
1173                            Some(element)
1174                        },
1175                    )),
1176                )
1177            })
1178    }
1179
1180    fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
1181        let is_using_zed_provider = self
1182            .thread
1183            .read(cx)
1184            .configured_model()
1185            .map_or(false, |model| {
1186                model.provider.id().0 == ZED_CLOUD_PROVIDER_ID
1187            });
1188        if !is_using_zed_provider {
1189            return None;
1190        }
1191
1192        let user_store = self.user_store.read(cx);
1193
1194        let ubb_enable = user_store
1195            .usage_based_billing_enabled()
1196            .map_or(false, |enabled| enabled);
1197
1198        if ubb_enable {
1199            return None;
1200        }
1201
1202        let plan = user_store
1203            .current_plan()
1204            .map(|plan| match plan {
1205                Plan::Free => zed_llm_client::Plan::ZedFree,
1206                Plan::ZedPro => zed_llm_client::Plan::ZedPro,
1207                Plan::ZedProTrial => zed_llm_client::Plan::ZedProTrial,
1208            })
1209            .unwrap_or(zed_llm_client::Plan::ZedFree);
1210        let usage = self.thread.read(cx).last_usage().or_else(|| {
1211            maybe!({
1212                let amount = user_store.model_request_usage_amount()?;
1213                let limit = user_store.model_request_usage_limit()?.variant?;
1214
1215                Some(RequestUsage {
1216                    amount: amount as i32,
1217                    limit: match limit {
1218                        proto::usage_limit::Variant::Limited(limited) => {
1219                            zed_llm_client::UsageLimit::Limited(limited.limit as i32)
1220                        }
1221                        proto::usage_limit::Variant::Unlimited(_) => {
1222                            zed_llm_client::UsageLimit::Unlimited
1223                        }
1224                    },
1225                })
1226            })
1227        })?;
1228
1229        Some(
1230            div()
1231                .child(UsageCallout::new(plan, usage))
1232                .line_height(line_height),
1233        )
1234    }
1235
1236    fn render_token_limit_callout(
1237        &self,
1238        line_height: Pixels,
1239        token_usage_ratio: TokenUsageRatio,
1240        cx: &mut Context<Self>,
1241    ) -> Option<Div> {
1242        let title = if token_usage_ratio == TokenUsageRatio::Exceeded {
1243            "Thread reached the token limit"
1244        } else {
1245            "Thread reaching the token limit soon"
1246        };
1247
1248        let message = "Start a new thread from a summary to continue the conversation.";
1249
1250        let icon = if token_usage_ratio == TokenUsageRatio::Exceeded {
1251            Icon::new(IconName::X)
1252                .color(Color::Error)
1253                .size(IconSize::XSmall)
1254        } else {
1255            Icon::new(IconName::Warning)
1256                .color(Color::Warning)
1257                .size(IconSize::XSmall)
1258        };
1259
1260        Some(
1261            div()
1262                .child(ui::Callout::multi_line(
1263                    title,
1264                    message,
1265                    icon,
1266                    "Start New Thread",
1267                    Box::new(cx.listener(|this, _, window, cx| {
1268                        let from_thread_id = Some(this.thread.read(cx).id().clone());
1269                        window.dispatch_action(Box::new(NewThread { from_thread_id }), cx);
1270                    })),
1271                ))
1272                .line_height(line_height),
1273        )
1274    }
1275
1276    pub fn last_estimated_token_count(&self) -> Option<usize> {
1277        self.last_estimated_token_count
1278    }
1279
1280    pub fn is_waiting_to_update_token_count(&self) -> bool {
1281        self.update_token_count_task.is_some()
1282    }
1283
1284    fn reload_context(&mut self, cx: &mut Context<Self>) -> Task<Option<ContextLoadResult>> {
1285        let load_task = cx.spawn(async move |this, cx| {
1286            let Ok(load_task) = this.update(cx, |this, cx| {
1287                let new_context = this
1288                    .context_store
1289                    .read(cx)
1290                    .new_context_for_thread(this.thread.read(cx), None);
1291                load_context(new_context, &this.project, &this.prompt_store, cx)
1292            }) else {
1293                return;
1294            };
1295            let result = load_task.await;
1296            this.update(cx, |this, cx| {
1297                this.last_loaded_context = Some(result);
1298                this.load_context_task = None;
1299                this.message_or_context_changed(false, cx);
1300            })
1301            .ok();
1302        });
1303        // Replace existing load task, if any, causing it to be cancelled.
1304        let load_task = load_task.shared();
1305        self.load_context_task = Some(load_task.clone());
1306        cx.spawn(async move |this, cx| {
1307            load_task.await;
1308            this.read_with(cx, |this, _cx| this.last_loaded_context.clone())
1309                .ok()
1310                .flatten()
1311        })
1312    }
1313
1314    fn handle_message_changed(&mut self, cx: &mut Context<Self>) {
1315        self.message_or_context_changed(true, cx);
1316    }
1317
1318    fn message_or_context_changed(&mut self, debounce: bool, cx: &mut Context<Self>) {
1319        cx.emit(MessageEditorEvent::Changed);
1320        self.update_token_count_task.take();
1321
1322        let Some(model) = self.thread.read(cx).configured_model() else {
1323            self.last_estimated_token_count.take();
1324            return;
1325        };
1326
1327        let editor = self.editor.clone();
1328
1329        self.update_token_count_task = Some(cx.spawn(async move |this, cx| {
1330            if debounce {
1331                cx.background_executor()
1332                    .timer(Duration::from_millis(200))
1333                    .await;
1334            }
1335
1336            let token_count = if let Some(task) = this
1337                .update(cx, |this, cx| {
1338                    let loaded_context = this
1339                        .last_loaded_context
1340                        .as_ref()
1341                        .map(|context_load_result| &context_load_result.loaded_context);
1342                    let message_text = editor.read(cx).text(cx);
1343
1344                    if message_text.is_empty()
1345                        && loaded_context.map_or(true, |loaded_context| loaded_context.is_empty())
1346                    {
1347                        return None;
1348                    }
1349
1350                    let mut request_message = LanguageModelRequestMessage {
1351                        role: language_model::Role::User,
1352                        content: Vec::new(),
1353                        cache: false,
1354                    };
1355
1356                    if let Some(loaded_context) = loaded_context {
1357                        loaded_context.add_to_request_message(&mut request_message);
1358                    }
1359
1360                    if !message_text.is_empty() {
1361                        request_message
1362                            .content
1363                            .push(MessageContent::Text(message_text));
1364                    }
1365
1366                    let request = language_model::LanguageModelRequest {
1367                        thread_id: None,
1368                        prompt_id: None,
1369                        intent: None,
1370                        mode: None,
1371                        messages: vec![request_message],
1372                        tools: vec![],
1373                        tool_choice: None,
1374                        stop: vec![],
1375                        temperature: AgentSettings::temperature_for_model(&model.model, cx),
1376                    };
1377
1378                    Some(model.model.count_tokens(request, cx))
1379                })
1380                .ok()
1381                .flatten()
1382            {
1383                task.await.log_err()
1384            } else {
1385                Some(0)
1386            };
1387
1388            this.update(cx, |this, cx| {
1389                if let Some(token_count) = token_count {
1390                    this.last_estimated_token_count = Some(token_count);
1391                    cx.emit(MessageEditorEvent::EstimatedTokenCount);
1392                }
1393                this.update_token_count_task.take();
1394            })
1395            .ok();
1396        }));
1397    }
1398}
1399
1400pub fn extract_message_creases(
1401    editor: &mut Editor,
1402    cx: &mut Context<'_, Editor>,
1403) -> Vec<MessageCrease> {
1404    let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1405    let mut contexts_by_crease_id = editor
1406        .addon_mut::<ContextCreasesAddon>()
1407        .map(std::mem::take)
1408        .unwrap_or_default()
1409        .into_inner()
1410        .into_iter()
1411        .flat_map(|(key, creases)| {
1412            let context = key.0;
1413            creases
1414                .into_iter()
1415                .map(move |(id, _)| (id, context.clone()))
1416        })
1417        .collect::<HashMap<_, _>>();
1418    // Filter the addon's list of creases based on what the editor reports,
1419    // since the addon might have removed creases in it.
1420    let creases = editor.display_map.update(cx, |display_map, cx| {
1421        display_map
1422            .snapshot(cx)
1423            .crease_snapshot
1424            .creases()
1425            .filter_map(|(id, crease)| {
1426                Some((
1427                    id,
1428                    (
1429                        crease.range().to_offset(&buffer_snapshot),
1430                        crease.metadata()?.clone(),
1431                    ),
1432                ))
1433            })
1434            .map(|(id, (range, metadata))| {
1435                let context = contexts_by_crease_id.remove(&id);
1436                MessageCrease {
1437                    range,
1438                    metadata,
1439                    context,
1440                }
1441            })
1442            .collect()
1443    });
1444    creases
1445}
1446
1447impl EventEmitter<MessageEditorEvent> for MessageEditor {}
1448
1449pub enum MessageEditorEvent {
1450    EstimatedTokenCount,
1451    Changed,
1452}
1453
1454impl Focusable for MessageEditor {
1455    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
1456        self.editor.focus_handle(cx)
1457    }
1458}
1459
1460impl Render for MessageEditor {
1461    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1462        let thread = self.thread.read(cx);
1463        let token_usage_ratio = thread
1464            .total_token_usage()
1465            .map_or(TokenUsageRatio::Normal, |total_token_usage| {
1466                total_token_usage.ratio()
1467            });
1468
1469        let action_log = self.thread.read(cx).action_log();
1470        let changed_buffers = action_log.read(cx).changed_buffers(cx);
1471
1472        let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
1473
1474        v_flex()
1475            .size_full()
1476            .when(changed_buffers.len() > 0, |parent| {
1477                parent.child(self.render_changed_buffers(&changed_buffers, window, cx))
1478            })
1479            .child(self.render_editor(window, cx))
1480            .children({
1481                let usage_callout = self.render_usage_callout(line_height, cx);
1482
1483                if usage_callout.is_some() {
1484                    usage_callout
1485                } else if token_usage_ratio != TokenUsageRatio::Normal {
1486                    self.render_token_limit_callout(line_height, token_usage_ratio, cx)
1487                } else {
1488                    None
1489                }
1490            })
1491    }
1492}
1493
1494pub fn insert_message_creases(
1495    editor: &mut Editor,
1496    message_creases: &[MessageCrease],
1497    context_store: &Entity<ContextStore>,
1498    window: &mut Window,
1499    cx: &mut Context<'_, Editor>,
1500) {
1501    let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1502    let creases = message_creases
1503        .iter()
1504        .map(|crease| {
1505            let start = buffer_snapshot.anchor_after(crease.range.start);
1506            let end = buffer_snapshot.anchor_before(crease.range.end);
1507            crease_for_mention(
1508                crease.metadata.label.clone(),
1509                crease.metadata.icon_path.clone(),
1510                start..end,
1511                cx.weak_entity(),
1512            )
1513        })
1514        .collect::<Vec<_>>();
1515    let ids = editor.insert_creases(creases.clone(), cx);
1516    editor.fold_creases(creases, false, window, cx);
1517    if let Some(addon) = editor.addon_mut::<ContextCreasesAddon>() {
1518        for (crease, id) in message_creases.iter().zip(ids) {
1519            if let Some(context) = crease.context.as_ref() {
1520                let key = AgentContextKey(context.clone());
1521                addon.add_creases(
1522                    context_store,
1523                    key,
1524                    vec![(id, crease.metadata.label.clone())],
1525                    cx,
1526                );
1527            }
1528        }
1529    }
1530}
1531impl Component for MessageEditor {
1532    fn scope() -> ComponentScope {
1533        ComponentScope::Agent
1534    }
1535
1536    fn description() -> Option<&'static str> {
1537        Some(
1538            "The composer experience of the Agent Panel. This interface handles context, composing messages, switching profiles, models and more.",
1539        )
1540    }
1541}
1542
1543impl AgentPreview for MessageEditor {
1544    fn agent_preview(
1545        workspace: WeakEntity<Workspace>,
1546        active_thread: Entity<ActiveThread>,
1547        window: &mut Window,
1548        cx: &mut App,
1549    ) -> Option<AnyElement> {
1550        if let Some(workspace) = workspace.upgrade() {
1551            let fs = workspace.read(cx).app_state().fs.clone();
1552            let user_store = workspace.read(cx).app_state().user_store.clone();
1553            let project = workspace.read(cx).project().clone();
1554            let weak_project = project.downgrade();
1555            let context_store = cx.new(|_cx| ContextStore::new(weak_project, None));
1556            let active_thread = active_thread.read(cx);
1557            let thread = active_thread.thread().clone();
1558            let thread_store = active_thread.thread_store().clone();
1559            let text_thread_store = active_thread.text_thread_store().clone();
1560
1561            let default_message_editor = cx.new(|cx| {
1562                MessageEditor::new(
1563                    fs,
1564                    workspace.downgrade(),
1565                    user_store,
1566                    context_store,
1567                    None,
1568                    thread_store.downgrade(),
1569                    text_thread_store.downgrade(),
1570                    thread,
1571                    window,
1572                    cx,
1573                )
1574            });
1575
1576            Some(
1577                v_flex()
1578                    .gap_4()
1579                    .children(vec![single_example(
1580                        "Default Message Editor",
1581                        div()
1582                            .w(px(540.))
1583                            .pt_12()
1584                            .bg(cx.theme().colors().panel_background)
1585                            .border_1()
1586                            .border_color(cx.theme().colors().border)
1587                            .child(default_message_editor.clone())
1588                            .into_any_element(),
1589                    )])
1590                    .into_any_element(),
1591            )
1592        } else {
1593            None
1594        }
1595    }
1596}
1597
1598register_agent_preview!(MessageEditor);