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", index))
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                                        )
1175                                        .on_click({
1176                                            let buffer = buffer.clone();
1177                                            cx.listener(move |this, _, window, cx| {
1178                                                this.handle_file_click(buffer.clone(), window, cx);
1179                                            })
1180                                        }), // TODO: Implement line diff
1181                                            // .child(Label::new("+").color(Color::Created))
1182                                            // .child(Label::new("-").color(Color::Deleted)),
1183                                            //
1184                                )
1185                                .child(
1186                                    h_flex()
1187                                        .gap_1()
1188                                        .visible_on_hover("edited-code")
1189                                        .child(
1190                                            Button::new("review", "Review")
1191                                                .label_size(LabelSize::Small)
1192                                                .on_click({
1193                                                    let buffer = buffer.clone();
1194                                                    cx.listener(move |this, _, window, cx| {
1195                                                        this.handle_file_click(
1196                                                            buffer.clone(),
1197                                                            window,
1198                                                            cx,
1199                                                        );
1200                                                    })
1201                                                }),
1202                                        )
1203                                        .child(
1204                                            Divider::vertical().color(DividerColor::BorderVariant),
1205                                        )
1206                                        .child(
1207                                            Button::new("reject-file", "Reject")
1208                                                .label_size(LabelSize::Small)
1209                                                .disabled(pending_edits)
1210                                                .on_click({
1211                                                    let buffer = buffer.clone();
1212                                                    cx.listener(move |this, _, window, cx| {
1213                                                        this.handle_reject_file_changes(
1214                                                            buffer.clone(),
1215                                                            window,
1216                                                            cx,
1217                                                        );
1218                                                    })
1219                                                }),
1220                                        )
1221                                        .child(
1222                                            Button::new("accept-file", "Accept")
1223                                                .label_size(LabelSize::Small)
1224                                                .disabled(pending_edits)
1225                                                .on_click({
1226                                                    let buffer = buffer.clone();
1227                                                    cx.listener(move |this, _, window, cx| {
1228                                                        this.handle_accept_file_changes(
1229                                                            buffer.clone(),
1230                                                            window,
1231                                                            cx,
1232                                                        );
1233                                                    })
1234                                                }),
1235                                        ),
1236                                )
1237                                .child(
1238                                    div()
1239                                        .id("gradient-overlay")
1240                                        .absolute()
1241                                        .h_full()
1242                                        .w_12()
1243                                        .top_0()
1244                                        .bottom_0()
1245                                        .right(px(152.))
1246                                        .bg(overlay_gradient),
1247                                );
1248
1249                            Some(element)
1250                        },
1251                    )),
1252                )
1253            })
1254    }
1255
1256    fn is_using_zed_provider(&self, cx: &App) -> bool {
1257        self.thread
1258            .read(cx)
1259            .configured_model()
1260            .map_or(false, |model| model.provider.id() == ZED_CLOUD_PROVIDER_ID)
1261    }
1262
1263    fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
1264        if !self.is_using_zed_provider(cx) {
1265            return None;
1266        }
1267
1268        let user_store = self.user_store.read(cx);
1269
1270        let ubb_enable = user_store
1271            .usage_based_billing_enabled()
1272            .map_or(false, |enabled| enabled);
1273
1274        if ubb_enable {
1275            return None;
1276        }
1277
1278        let plan = user_store
1279            .current_plan()
1280            .map(|plan| match plan {
1281                Plan::Free => zed_llm_client::Plan::ZedFree,
1282                Plan::ZedPro => zed_llm_client::Plan::ZedPro,
1283                Plan::ZedProTrial => zed_llm_client::Plan::ZedProTrial,
1284            })
1285            .unwrap_or(zed_llm_client::Plan::ZedFree);
1286
1287        let usage = user_store.model_request_usage()?;
1288
1289        Some(
1290            div()
1291                .child(UsageCallout::new(plan, usage))
1292                .line_height(line_height),
1293        )
1294    }
1295
1296    fn render_token_limit_callout(
1297        &self,
1298        line_height: Pixels,
1299        token_usage_ratio: TokenUsageRatio,
1300        cx: &mut Context<Self>,
1301    ) -> Option<Div> {
1302        let icon = if token_usage_ratio == TokenUsageRatio::Exceeded {
1303            Icon::new(IconName::X)
1304                .color(Color::Error)
1305                .size(IconSize::XSmall)
1306        } else {
1307            Icon::new(IconName::Warning)
1308                .color(Color::Warning)
1309                .size(IconSize::XSmall)
1310        };
1311
1312        let title = if token_usage_ratio == TokenUsageRatio::Exceeded {
1313            "Thread reached the token limit"
1314        } else {
1315            "Thread reaching the token limit soon"
1316        };
1317
1318        let description = if self.is_using_zed_provider(cx) {
1319            "To continue, start a new thread from a summary or turn burn mode on."
1320        } else {
1321            "To continue, start a new thread from a summary."
1322        };
1323
1324        let mut callout = Callout::new()
1325            .line_height(line_height)
1326            .icon(icon)
1327            .title(title)
1328            .description(description)
1329            .primary_action(
1330                Button::new("start-new-thread", "Start New Thread")
1331                    .label_size(LabelSize::Small)
1332                    .on_click(cx.listener(|this, _, window, cx| {
1333                        let from_thread_id = Some(this.thread.read(cx).id().clone());
1334                        window.dispatch_action(Box::new(NewThread { from_thread_id }), cx);
1335                    })),
1336            );
1337
1338        if self.is_using_zed_provider(cx) {
1339            callout = callout.secondary_action(
1340                IconButton::new("burn-mode-callout", IconName::ZedBurnMode)
1341                    .icon_size(IconSize::XSmall)
1342                    .on_click(cx.listener(|this, _event, window, cx| {
1343                        this.toggle_burn_mode(&ToggleBurnMode, window, cx);
1344                    })),
1345            );
1346        }
1347
1348        Some(
1349            div()
1350                .border_t_1()
1351                .border_color(cx.theme().colors().border)
1352                .child(callout),
1353        )
1354    }
1355
1356    pub fn last_estimated_token_count(&self) -> Option<u64> {
1357        self.last_estimated_token_count
1358    }
1359
1360    pub fn is_waiting_to_update_token_count(&self) -> bool {
1361        self.update_token_count_task.is_some()
1362    }
1363
1364    fn reload_context(&mut self, cx: &mut Context<Self>) -> Task<Option<ContextLoadResult>> {
1365        let load_task = cx.spawn(async move |this, cx| {
1366            let Ok(load_task) = this.update(cx, |this, cx| {
1367                let new_context = this
1368                    .context_store
1369                    .read(cx)
1370                    .new_context_for_thread(this.thread.read(cx), None);
1371                load_context(new_context, &this.project, &this.prompt_store, cx)
1372            }) else {
1373                return;
1374            };
1375            let result = load_task.await;
1376            this.update(cx, |this, cx| {
1377                this.last_loaded_context = Some(result);
1378                this.load_context_task = None;
1379                this.message_or_context_changed(false, cx);
1380            })
1381            .ok();
1382        });
1383        // Replace existing load task, if any, causing it to be cancelled.
1384        let load_task = load_task.shared();
1385        self.load_context_task = Some(load_task.clone());
1386        cx.spawn(async move |this, cx| {
1387            load_task.await;
1388            this.read_with(cx, |this, _cx| this.last_loaded_context.clone())
1389                .ok()
1390                .flatten()
1391        })
1392    }
1393
1394    fn handle_message_changed(&mut self, cx: &mut Context<Self>) {
1395        self.message_or_context_changed(true, cx);
1396    }
1397
1398    fn message_or_context_changed(&mut self, debounce: bool, cx: &mut Context<Self>) {
1399        cx.emit(MessageEditorEvent::Changed);
1400        self.update_token_count_task.take();
1401
1402        let Some(model) = self.thread.read(cx).configured_model() else {
1403            self.last_estimated_token_count.take();
1404            return;
1405        };
1406
1407        let editor = self.editor.clone();
1408
1409        self.update_token_count_task = Some(cx.spawn(async move |this, cx| {
1410            if debounce {
1411                cx.background_executor()
1412                    .timer(Duration::from_millis(200))
1413                    .await;
1414            }
1415
1416            let token_count = if let Some(task) = this
1417                .update(cx, |this, cx| {
1418                    let loaded_context = this
1419                        .last_loaded_context
1420                        .as_ref()
1421                        .map(|context_load_result| &context_load_result.loaded_context);
1422                    let message_text = editor.read(cx).text(cx);
1423
1424                    if message_text.is_empty()
1425                        && loaded_context.map_or(true, |loaded_context| loaded_context.is_empty())
1426                    {
1427                        return None;
1428                    }
1429
1430                    let mut request_message = LanguageModelRequestMessage {
1431                        role: language_model::Role::User,
1432                        content: Vec::new(),
1433                        cache: false,
1434                    };
1435
1436                    if let Some(loaded_context) = loaded_context {
1437                        loaded_context.add_to_request_message(&mut request_message);
1438                    }
1439
1440                    if !message_text.is_empty() {
1441                        request_message
1442                            .content
1443                            .push(MessageContent::Text(message_text));
1444                    }
1445
1446                    let request = language_model::LanguageModelRequest {
1447                        thread_id: None,
1448                        prompt_id: None,
1449                        intent: None,
1450                        mode: None,
1451                        messages: vec![request_message],
1452                        tools: vec![],
1453                        tool_choice: None,
1454                        stop: vec![],
1455                        temperature: AgentSettings::temperature_for_model(&model.model, cx),
1456                    };
1457
1458                    Some(model.model.count_tokens(request, cx))
1459                })
1460                .ok()
1461                .flatten()
1462            {
1463                task.await.log_err()
1464            } else {
1465                Some(0)
1466            };
1467
1468            this.update(cx, |this, cx| {
1469                if let Some(token_count) = token_count {
1470                    this.last_estimated_token_count = Some(token_count);
1471                    cx.emit(MessageEditorEvent::EstimatedTokenCount);
1472                }
1473                this.update_token_count_task.take();
1474            })
1475            .ok();
1476        }));
1477    }
1478}
1479
1480#[derive(Default)]
1481pub struct ContextCreasesAddon {
1482    creases: HashMap<AgentContextKey, Vec<(CreaseId, SharedString)>>,
1483    _subscription: Option<Subscription>,
1484}
1485
1486impl Addon for ContextCreasesAddon {
1487    fn to_any(&self) -> &dyn std::any::Any {
1488        self
1489    }
1490
1491    fn to_any_mut(&mut self) -> Option<&mut dyn std::any::Any> {
1492        Some(self)
1493    }
1494}
1495
1496impl ContextCreasesAddon {
1497    pub fn new() -> Self {
1498        Self {
1499            creases: HashMap::default(),
1500            _subscription: None,
1501        }
1502    }
1503
1504    pub fn add_creases(
1505        &mut self,
1506        context_store: &Entity<ContextStore>,
1507        key: AgentContextKey,
1508        creases: impl IntoIterator<Item = (CreaseId, SharedString)>,
1509        cx: &mut Context<Editor>,
1510    ) {
1511        self.creases.entry(key).or_default().extend(creases);
1512        self._subscription = Some(cx.subscribe(
1513            &context_store,
1514            |editor, _, event, cx| match event {
1515                ContextStoreEvent::ContextRemoved(key) => {
1516                    let Some(this) = editor.addon_mut::<Self>() else {
1517                        return;
1518                    };
1519                    let (crease_ids, replacement_texts): (Vec<_>, Vec<_>) = this
1520                        .creases
1521                        .remove(key)
1522                        .unwrap_or_default()
1523                        .into_iter()
1524                        .unzip();
1525                    let ranges = editor
1526                        .remove_creases(crease_ids, cx)
1527                        .into_iter()
1528                        .map(|(_, range)| range)
1529                        .collect::<Vec<_>>();
1530                    editor.unfold_ranges(&ranges, false, false, cx);
1531                    editor.edit(ranges.into_iter().zip(replacement_texts), cx);
1532                    cx.notify();
1533                }
1534            },
1535        ))
1536    }
1537
1538    pub fn into_inner(self) -> HashMap<AgentContextKey, Vec<(CreaseId, SharedString)>> {
1539        self.creases
1540    }
1541}
1542
1543pub fn extract_message_creases(
1544    editor: &mut Editor,
1545    cx: &mut Context<'_, Editor>,
1546) -> Vec<MessageCrease> {
1547    let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1548    let mut contexts_by_crease_id = editor
1549        .addon_mut::<ContextCreasesAddon>()
1550        .map(std::mem::take)
1551        .unwrap_or_default()
1552        .into_inner()
1553        .into_iter()
1554        .flat_map(|(key, creases)| {
1555            let context = key.0;
1556            creases
1557                .into_iter()
1558                .map(move |(id, _)| (id, context.clone()))
1559        })
1560        .collect::<HashMap<_, _>>();
1561    // Filter the addon's list of creases based on what the editor reports,
1562    // since the addon might have removed creases in it.
1563    let creases = editor.display_map.update(cx, |display_map, cx| {
1564        display_map
1565            .snapshot(cx)
1566            .crease_snapshot
1567            .creases()
1568            .filter_map(|(id, crease)| {
1569                Some((
1570                    id,
1571                    (
1572                        crease.range().to_offset(&buffer_snapshot),
1573                        crease.metadata()?.clone(),
1574                    ),
1575                ))
1576            })
1577            .map(|(id, (range, metadata))| {
1578                let context = contexts_by_crease_id.remove(&id);
1579                MessageCrease {
1580                    range,
1581                    context,
1582                    label: metadata.label,
1583                    icon_path: metadata.icon_path,
1584                }
1585            })
1586            .collect()
1587    });
1588    creases
1589}
1590
1591impl EventEmitter<MessageEditorEvent> for MessageEditor {}
1592
1593pub enum MessageEditorEvent {
1594    EstimatedTokenCount,
1595    Changed,
1596    ScrollThreadToBottom,
1597}
1598
1599impl Focusable for MessageEditor {
1600    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
1601        self.editor.focus_handle(cx)
1602    }
1603}
1604
1605impl Render for MessageEditor {
1606    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1607        let thread = self.thread.read(cx);
1608        let token_usage_ratio = thread
1609            .total_token_usage()
1610            .map_or(TokenUsageRatio::Normal, |total_token_usage| {
1611                total_token_usage.ratio()
1612            });
1613
1614        let burn_mode_enabled = thread.completion_mode() == CompletionMode::Burn;
1615
1616        let action_log = self.thread.read(cx).action_log();
1617        let changed_buffers = action_log.read(cx).changed_buffers(cx);
1618
1619        let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
1620
1621        v_flex()
1622            .size_full()
1623            .when(changed_buffers.len() > 0, |parent| {
1624                parent.child(self.render_edits_bar(&changed_buffers, window, cx))
1625            })
1626            .child(self.render_editor(window, cx))
1627            .children({
1628                let usage_callout = self.render_usage_callout(line_height, cx);
1629
1630                if usage_callout.is_some() {
1631                    usage_callout
1632                } else if token_usage_ratio != TokenUsageRatio::Normal && !burn_mode_enabled {
1633                    self.render_token_limit_callout(line_height, token_usage_ratio, cx)
1634                } else {
1635                    None
1636                }
1637            })
1638    }
1639}
1640
1641pub fn insert_message_creases(
1642    editor: &mut Editor,
1643    message_creases: &[MessageCrease],
1644    context_store: &Entity<ContextStore>,
1645    window: &mut Window,
1646    cx: &mut Context<'_, Editor>,
1647) {
1648    let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1649    let creases = message_creases
1650        .iter()
1651        .map(|crease| {
1652            let start = buffer_snapshot.anchor_after(crease.range.start);
1653            let end = buffer_snapshot.anchor_before(crease.range.end);
1654            crease_for_mention(
1655                crease.label.clone(),
1656                crease.icon_path.clone(),
1657                start..end,
1658                cx.weak_entity(),
1659            )
1660        })
1661        .collect::<Vec<_>>();
1662    let ids = editor.insert_creases(creases.clone(), cx);
1663    editor.fold_creases(creases, false, window, cx);
1664    if let Some(addon) = editor.addon_mut::<ContextCreasesAddon>() {
1665        for (crease, id) in message_creases.iter().zip(ids) {
1666            if let Some(context) = crease.context.as_ref() {
1667                let key = AgentContextKey(context.clone());
1668                addon.add_creases(context_store, key, vec![(id, crease.label.clone())], cx);
1669            }
1670        }
1671    }
1672}
1673impl Component for MessageEditor {
1674    fn scope() -> ComponentScope {
1675        ComponentScope::Agent
1676    }
1677
1678    fn description() -> Option<&'static str> {
1679        Some(
1680            "The composer experience of the Agent Panel. This interface handles context, composing messages, switching profiles, models and more.",
1681        )
1682    }
1683}
1684
1685impl AgentPreview for MessageEditor {
1686    fn agent_preview(
1687        workspace: WeakEntity<Workspace>,
1688        active_thread: Entity<ActiveThread>,
1689        window: &mut Window,
1690        cx: &mut App,
1691    ) -> Option<AnyElement> {
1692        if let Some(workspace) = workspace.upgrade() {
1693            let fs = workspace.read(cx).app_state().fs.clone();
1694            let user_store = workspace.read(cx).app_state().user_store.clone();
1695            let project = workspace.read(cx).project().clone();
1696            let weak_project = project.downgrade();
1697            let context_store = cx.new(|_cx| ContextStore::new(weak_project, None));
1698            let active_thread = active_thread.read(cx);
1699            let thread = active_thread.thread().clone();
1700            let thread_store = active_thread.thread_store().clone();
1701            let text_thread_store = active_thread.text_thread_store().clone();
1702
1703            let default_message_editor = cx.new(|cx| {
1704                MessageEditor::new(
1705                    fs,
1706                    workspace.downgrade(),
1707                    user_store,
1708                    context_store,
1709                    None,
1710                    thread_store.downgrade(),
1711                    text_thread_store.downgrade(),
1712                    thread,
1713                    window,
1714                    cx,
1715                )
1716            });
1717
1718            Some(
1719                v_flex()
1720                    .gap_4()
1721                    .children(vec![single_example(
1722                        "Default Message Editor",
1723                        div()
1724                            .w(px(540.))
1725                            .pt_12()
1726                            .bg(cx.theme().colors().panel_background)
1727                            .border_1()
1728                            .border_color(cx.theme().colors().border)
1729                            .child(default_message_editor.clone())
1730                            .into_any_element(),
1731                    )])
1732                    .into_any_element(),
1733            )
1734        } else {
1735            None
1736        }
1737    }
1738}
1739
1740register_agent_preview!(MessageEditor);