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