message_editor.rs

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