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