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