message_editor.rs

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