message_editor.rs

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