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