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