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