message_editor.rs

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