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, ClipboardEntry, Entity, EventEmitter, Focusable, Subscription,
  28    Task, TextStyle, 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::{Disclosure, KeyBinding, PopoverMenuHandle, Tooltip, prelude::*};
  43use util::{ResultExt as _, maybe};
  44use workspace::{CollaboratorId, Workspace};
  45use zed_llm_client::CompletionIntent;
  46
  47use crate::context_picker::{ContextPicker, ContextPickerCompletionProvider, crease_for_mention};
  48use crate::context_store::ContextStore;
  49use crate::context_strip::{ContextStrip, ContextStripEvent, SuggestContextKind};
  50use crate::profile_selector::ProfileSelector;
  51use crate::thread::{MessageCrease, Thread, TokenUsageRatio};
  52use crate::thread_store::{TextThreadStore, ThreadStore};
  53use crate::{
  54    ActiveThread, AgentDiffPane, Chat, ChatWithFollow, ExpandMessageEditor, Follow, KeepAll,
  55    ModelUsageContext, NewThread, OpenAgentDiff, RejectAll, RemoveAllContext, ToggleBurnMode,
  56    ToggleContextPicker, ToggleProfileSelector, register_agent_preview,
  57};
  58
  59#[derive(RegisterComponent)]
  60pub struct MessageEditor {
  61    thread: Entity<Thread>,
  62    incompatible_tools_state: Entity<IncompatibleToolsState>,
  63    editor: Entity<Editor>,
  64    workspace: WeakEntity<Workspace>,
  65    project: Entity<Project>,
  66    user_store: Entity<UserStore>,
  67    context_store: Entity<ContextStore>,
  68    prompt_store: Option<Entity<PromptStore>>,
  69    context_strip: Entity<ContextStrip>,
  70    context_picker_menu_handle: PopoverMenuHandle<ContextPicker>,
  71    model_selector: Entity<AgentModelSelector>,
  72    last_loaded_context: Option<ContextLoadResult>,
  73    load_context_task: Option<Shared<Task<()>>>,
  74    profile_selector: Entity<ProfileSelector>,
  75    edits_expanded: bool,
  76    editor_is_expanded: bool,
  77    last_estimated_token_count: Option<usize>,
  78    update_token_count_task: Option<Task<()>>,
  79    _subscriptions: Vec<Subscription>,
  80}
  81
  82const MAX_EDITOR_LINES: usize = 8;
  83
  84pub(crate) fn create_editor(
  85    workspace: WeakEntity<Workspace>,
  86    context_store: WeakEntity<ContextStore>,
  87    thread_store: WeakEntity<ThreadStore>,
  88    text_thread_store: WeakEntity<TextThreadStore>,
  89    window: &mut Window,
  90    cx: &mut App,
  91) -> Entity<Editor> {
  92    let language = Language::new(
  93        language::LanguageConfig {
  94            completion_query_characters: HashSet::from_iter(['.', '-', '_', '@']),
  95            ..Default::default()
  96        },
  97        None,
  98    );
  99
 100    let editor = cx.new(|cx| {
 101        let buffer = cx.new(|cx| Buffer::local("", cx).with_language(Arc::new(language), cx));
 102        let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
 103        let mut editor = Editor::new(
 104            editor::EditorMode::AutoHeight {
 105                max_lines: MAX_EDITOR_LINES,
 106            },
 107            buffer,
 108            None,
 109            window,
 110            cx,
 111        );
 112        editor.set_placeholder_text("Message the agent – @ to include context", cx);
 113        editor.set_show_indent_guides(false, cx);
 114        editor.set_soft_wrap();
 115        editor.set_use_modal_editing(true);
 116        editor.set_context_menu_options(ContextMenuOptions {
 117            min_entries_visible: 12,
 118            max_entries_visible: 12,
 119            placement: Some(ContextMenuPlacement::Above),
 120        });
 121        editor.register_addon(ContextCreasesAddon::new());
 122        editor
 123    });
 124
 125    let editor_entity = editor.downgrade();
 126    editor.update(cx, |editor, _| {
 127        editor.set_completion_provider(Some(Rc::new(ContextPickerCompletionProvider::new(
 128            workspace,
 129            context_store,
 130            Some(thread_store),
 131            Some(text_thread_store),
 132            editor_entity,
 133            None,
 134        ))));
 135    });
 136    editor
 137}
 138
 139impl MessageEditor {
 140    pub fn new(
 141        fs: Arc<dyn Fs>,
 142        workspace: WeakEntity<Workspace>,
 143        user_store: Entity<UserStore>,
 144        context_store: Entity<ContextStore>,
 145        prompt_store: Option<Entity<PromptStore>>,
 146        thread_store: WeakEntity<ThreadStore>,
 147        text_thread_store: WeakEntity<TextThreadStore>,
 148        thread: Entity<Thread>,
 149        window: &mut Window,
 150        cx: &mut Context<Self>,
 151    ) -> Self {
 152        let context_picker_menu_handle = PopoverMenuHandle::default();
 153        let model_selector_menu_handle = PopoverMenuHandle::default();
 154
 155        let editor = create_editor(
 156            workspace.clone(),
 157            context_store.downgrade(),
 158            thread_store.clone(),
 159            text_thread_store.clone(),
 160            window,
 161            cx,
 162        );
 163
 164        let context_strip = cx.new(|cx| {
 165            ContextStrip::new(
 166                context_store.clone(),
 167                workspace.clone(),
 168                Some(thread_store.clone()),
 169                Some(text_thread_store.clone()),
 170                context_picker_menu_handle.clone(),
 171                SuggestContextKind::File,
 172                ModelUsageContext::Thread(thread.clone()),
 173                window,
 174                cx,
 175            )
 176        });
 177
 178        let incompatible_tools =
 179            cx.new(|cx| IncompatibleToolsState::new(thread.read(cx).tools().clone(), cx));
 180
 181        let subscriptions = vec![
 182            cx.subscribe_in(&context_strip, window, Self::handle_context_strip_event),
 183            cx.subscribe(&editor, |this, _, event, cx| match event {
 184                EditorEvent::BufferEdited => this.handle_message_changed(cx),
 185                _ => {}
 186            }),
 187            cx.observe(&context_store, |this, _, cx| {
 188                // When context changes, reload it for token counting.
 189                let _ = this.reload_context(cx);
 190            }),
 191            cx.observe(&thread.read(cx).action_log().clone(), |_, _, cx| {
 192                cx.notify()
 193            }),
 194        ];
 195
 196        let model_selector = cx.new(|cx| {
 197            AgentModelSelector::new(
 198                fs.clone(),
 199                model_selector_menu_handle,
 200                editor.focus_handle(cx),
 201                ModelUsageContext::Thread(thread.clone()),
 202                window,
 203                cx,
 204            )
 205        });
 206
 207        let profile_selector = cx.new(|cx| {
 208            ProfileSelector::new(
 209                fs,
 210                thread.clone(),
 211                thread_store,
 212                editor.focus_handle(cx),
 213                cx,
 214            )
 215        });
 216
 217        Self {
 218            editor: editor.clone(),
 219            project: thread.read(cx).project().clone(),
 220            user_store,
 221            thread,
 222            incompatible_tools_state: incompatible_tools.clone(),
 223            workspace,
 224            context_store,
 225            prompt_store,
 226            context_strip,
 227            context_picker_menu_handle,
 228            load_context_task: None,
 229            last_loaded_context: None,
 230            model_selector,
 231            edits_expanded: false,
 232            editor_is_expanded: false,
 233            profile_selector,
 234            last_estimated_token_count: None,
 235            update_token_count_task: None,
 236            _subscriptions: subscriptions,
 237        }
 238    }
 239
 240    pub fn context_store(&self) -> &Entity<ContextStore> {
 241        &self.context_store
 242    }
 243
 244    pub fn expand_message_editor(
 245        &mut self,
 246        _: &ExpandMessageEditor,
 247        _window: &mut Window,
 248        cx: &mut Context<Self>,
 249    ) {
 250        self.set_editor_is_expanded(!self.editor_is_expanded, cx);
 251    }
 252
 253    fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
 254        self.editor_is_expanded = is_expanded;
 255        self.editor.update(cx, |editor, _| {
 256            if self.editor_is_expanded {
 257                editor.set_mode(EditorMode::Full {
 258                    scale_ui_elements_with_buffer_font_size: false,
 259                    show_active_line_background: false,
 260                    sized_by_content: false,
 261                })
 262            } else {
 263                editor.set_mode(EditorMode::AutoHeight {
 264                    max_lines: MAX_EDITOR_LINES,
 265                })
 266            }
 267        });
 268        cx.notify();
 269    }
 270
 271    fn toggle_context_picker(
 272        &mut self,
 273        _: &ToggleContextPicker,
 274        window: &mut Window,
 275        cx: &mut Context<Self>,
 276    ) {
 277        self.context_picker_menu_handle.toggle(window, cx);
 278    }
 279
 280    pub fn remove_all_context(
 281        &mut self,
 282        _: &RemoveAllContext,
 283        _window: &mut Window,
 284        cx: &mut Context<Self>,
 285    ) {
 286        self.context_store.update(cx, |store, cx| store.clear(cx));
 287        cx.notify();
 288    }
 289
 290    fn chat(&mut self, _: &Chat, window: &mut Window, cx: &mut Context<Self>) {
 291        if self.is_editor_empty(cx) {
 292            return;
 293        }
 294
 295        self.thread.update(cx, |thread, cx| {
 296            thread.cancel_editing(cx);
 297        });
 298
 299        if self.thread.read(cx).is_generating() {
 300            self.stop_current_and_send_new_message(window, cx);
 301            return;
 302        }
 303
 304        self.set_editor_is_expanded(false, cx);
 305        self.send_to_model(window, cx);
 306
 307        cx.notify();
 308    }
 309
 310    fn chat_with_follow(
 311        &mut self,
 312        _: &ChatWithFollow,
 313        window: &mut Window,
 314        cx: &mut Context<Self>,
 315    ) {
 316        self.workspace
 317            .update(cx, |this, cx| {
 318                this.follow(CollaboratorId::Agent, window, cx)
 319            })
 320            .log_err();
 321
 322        self.chat(&Chat, window, cx);
 323    }
 324
 325    fn is_editor_empty(&self, cx: &App) -> bool {
 326        self.editor.read(cx).text(cx).trim().is_empty()
 327    }
 328
 329    pub fn is_editor_fully_empty(&self, cx: &App) -> bool {
 330        self.editor.read(cx).is_empty(cx)
 331    }
 332
 333    fn send_to_model(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 334        let Some(ConfiguredModel { model, provider }) = self
 335            .thread
 336            .update(cx, |thread, cx| thread.get_or_init_configured_model(cx))
 337        else {
 338            return;
 339        };
 340
 341        if provider.must_accept_terms(cx) {
 342            cx.notify();
 343            return;
 344        }
 345
 346        let (user_message, user_message_creases) = self.editor.update(cx, |editor, cx| {
 347            let creases = extract_message_creases(editor, cx);
 348            let text = editor.text(cx);
 349            editor.clear(window, cx);
 350            (text, creases)
 351        });
 352
 353        self.last_estimated_token_count.take();
 354        cx.emit(MessageEditorEvent::EstimatedTokenCount);
 355
 356        let thread = self.thread.clone();
 357        let git_store = self.project.read(cx).git_store().clone();
 358        let checkpoint = git_store.update(cx, |git_store, cx| git_store.checkpoint(cx));
 359        let context_task = self.reload_context(cx);
 360        let window_handle = window.window_handle();
 361
 362        cx.spawn(async move |_this, cx| {
 363            let (checkpoint, loaded_context) = future::join(checkpoint, context_task).await;
 364            let loaded_context = loaded_context.unwrap_or_default();
 365
 366            thread
 367                .update(cx, |thread, cx| {
 368                    thread.insert_user_message(
 369                        user_message,
 370                        loaded_context,
 371                        checkpoint.ok(),
 372                        user_message_creases,
 373                        cx,
 374                    );
 375                })
 376                .log_err();
 377
 378            thread
 379                .update(cx, |thread, cx| {
 380                    thread.advance_prompt_id();
 381                    thread.send_to_model(
 382                        model,
 383                        CompletionIntent::UserPrompt,
 384                        Some(window_handle),
 385                        cx,
 386                    );
 387                })
 388                .log_err();
 389        })
 390        .detach();
 391    }
 392
 393    fn stop_current_and_send_new_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 394        self.thread.update(cx, |thread, cx| {
 395            thread.cancel_editing(cx);
 396        });
 397
 398        let cancelled = self.thread.update(cx, |thread, cx| {
 399            thread.cancel_last_completion(Some(window.window_handle()), cx)
 400        });
 401
 402        if cancelled {
 403            self.set_editor_is_expanded(false, cx);
 404            self.send_to_model(window, cx);
 405        }
 406    }
 407
 408    fn handle_context_strip_event(
 409        &mut self,
 410        _context_strip: &Entity<ContextStrip>,
 411        event: &ContextStripEvent,
 412        window: &mut Window,
 413        cx: &mut Context<Self>,
 414    ) {
 415        match event {
 416            ContextStripEvent::PickerDismissed
 417            | ContextStripEvent::BlurredEmpty
 418            | ContextStripEvent::BlurredDown => {
 419                let editor_focus_handle = self.editor.focus_handle(cx);
 420                window.focus(&editor_focus_handle);
 421            }
 422            ContextStripEvent::BlurredUp => {}
 423        }
 424    }
 425
 426    fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 427        if self.context_picker_menu_handle.is_deployed() {
 428            cx.propagate();
 429        } else if self.context_strip.read(cx).has_context_items(cx) {
 430            self.context_strip.focus_handle(cx).focus(window);
 431        }
 432    }
 433
 434    fn paste(&mut self, _: &Paste, _: &mut Window, cx: &mut Context<Self>) {
 435        let images = cx
 436            .read_from_clipboard()
 437            .map(|item| {
 438                item.into_entries()
 439                    .filter_map(|entry| {
 440                        if let ClipboardEntry::Image(image) = entry {
 441                            Some(image)
 442                        } else {
 443                            None
 444                        }
 445                    })
 446                    .collect::<Vec<_>>()
 447            })
 448            .unwrap_or_default();
 449
 450        if images.is_empty() {
 451            return;
 452        }
 453        cx.stop_propagation();
 454
 455        self.context_store.update(cx, |store, cx| {
 456            for image in images {
 457                store.add_image_instance(Arc::new(image), cx);
 458            }
 459        });
 460    }
 461
 462    fn handle_review_click(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 463        if self.thread.read(cx).has_pending_edit_tool_uses() {
 464            return;
 465        }
 466
 467        self.edits_expanded = true;
 468        AgentDiffPane::deploy(self.thread.clone(), self.workspace.clone(), window, cx).log_err();
 469        cx.notify();
 470    }
 471
 472    fn handle_edit_bar_expand(&mut self, cx: &mut Context<Self>) {
 473        self.edits_expanded = !self.edits_expanded;
 474        cx.notify();
 475    }
 476
 477    fn handle_file_click(
 478        &self,
 479        buffer: Entity<Buffer>,
 480        window: &mut Window,
 481        cx: &mut Context<Self>,
 482    ) {
 483        if let Ok(diff) =
 484            AgentDiffPane::deploy(self.thread.clone(), self.workspace.clone(), window, cx)
 485        {
 486            let path_key = multi_buffer::PathKey::for_buffer(&buffer, cx);
 487            diff.update(cx, |diff, cx| diff.move_to_path(path_key, window, cx));
 488        }
 489    }
 490
 491    pub fn toggle_burn_mode(
 492        &mut self,
 493        _: &ToggleBurnMode,
 494        _window: &mut Window,
 495        cx: &mut Context<Self>,
 496    ) {
 497        self.thread.update(cx, |thread, _cx| {
 498            let active_completion_mode = thread.completion_mode();
 499
 500            thread.set_completion_mode(match active_completion_mode {
 501                CompletionMode::Burn => CompletionMode::Normal,
 502                CompletionMode::Normal => CompletionMode::Burn,
 503            });
 504        });
 505    }
 506
 507    fn handle_accept_all(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
 508        if self.thread.read(cx).has_pending_edit_tool_uses() {
 509            return;
 510        }
 511
 512        self.thread.update(cx, |thread, cx| {
 513            thread.keep_all_edits(cx);
 514        });
 515        cx.notify();
 516    }
 517
 518    fn handle_reject_all(&mut self, _window: &mut Window, cx: &mut Context<Self>) {
 519        if self.thread.read(cx).has_pending_edit_tool_uses() {
 520            return;
 521        }
 522
 523        // Since there's no reject_all_edits method in the thread API,
 524        // we need to iterate through all buffers and reject their edits
 525        let action_log = self.thread.read(cx).action_log().clone();
 526        let changed_buffers = action_log.read(cx).changed_buffers(cx);
 527
 528        for (buffer, _) in changed_buffers {
 529            self.thread.update(cx, |thread, cx| {
 530                let buffer_snapshot = buffer.read(cx);
 531                let start = buffer_snapshot.anchor_before(Point::new(0, 0));
 532                let end = buffer_snapshot.anchor_after(buffer_snapshot.max_point());
 533                thread
 534                    .reject_edits_in_ranges(buffer, vec![start..end], cx)
 535                    .detach();
 536            });
 537        }
 538        cx.notify();
 539    }
 540
 541    fn render_max_mode_toggle(&self, cx: &mut Context<Self>) -> Option<AnyElement> {
 542        let thread = self.thread.read(cx);
 543        let model = thread.configured_model();
 544        if !model?.model.supports_max_mode() {
 545            return None;
 546        }
 547
 548        let active_completion_mode = thread.completion_mode();
 549        let burn_mode_enabled = active_completion_mode == CompletionMode::Burn;
 550        let icon = if burn_mode_enabled {
 551            IconName::ZedBurnModeOn
 552        } else {
 553            IconName::ZedBurnMode
 554        };
 555
 556        Some(
 557            IconButton::new("burn-mode", icon)
 558                .icon_size(IconSize::Small)
 559                .icon_color(Color::Muted)
 560                .toggle_state(burn_mode_enabled)
 561                .selected_icon_color(Color::Error)
 562                .on_click(cx.listener(|this, _event, window, cx| {
 563                    this.toggle_burn_mode(&ToggleBurnMode, window, cx);
 564                }))
 565                .tooltip(move |_window, cx| {
 566                    cx.new(|_| MaxModeTooltip::new().selected(burn_mode_enabled))
 567                        .into()
 568                })
 569                .into_any_element(),
 570        )
 571    }
 572
 573    fn render_follow_toggle(&self, cx: &mut Context<Self>) -> impl IntoElement {
 574        let following = self
 575            .workspace
 576            .read_with(cx, |workspace, _| {
 577                workspace.is_being_followed(CollaboratorId::Agent)
 578            })
 579            .unwrap_or(false);
 580
 581        IconButton::new("follow-agent", IconName::Crosshair)
 582            .icon_size(IconSize::Small)
 583            .icon_color(Color::Muted)
 584            .toggle_state(following)
 585            .selected_icon_color(Some(Color::Custom(cx.theme().players().agent().cursor)))
 586            .tooltip(move |window, cx| {
 587                if following {
 588                    Tooltip::for_action("Stop Following Agent", &Follow, window, cx)
 589                } else {
 590                    Tooltip::with_meta(
 591                        "Follow Agent",
 592                        Some(&Follow),
 593                        "Track the agent's location as it reads and edits files.",
 594                        window,
 595                        cx,
 596                    )
 597                }
 598            })
 599            .on_click(cx.listener(move |this, _, window, cx| {
 600                this.workspace
 601                    .update(cx, |workspace, cx| {
 602                        if following {
 603                            workspace.unfollow(CollaboratorId::Agent, window, cx);
 604                        } else {
 605                            workspace.follow(CollaboratorId::Agent, window, cx);
 606                        }
 607                    })
 608                    .ok();
 609            }))
 610    }
 611
 612    fn render_editor(&self, window: &mut Window, cx: &mut Context<Self>) -> Div {
 613        let thread = self.thread.read(cx);
 614        let model = thread.configured_model();
 615
 616        let editor_bg_color = cx.theme().colors().editor_background;
 617        let is_generating = thread.is_generating();
 618        let focus_handle = self.editor.focus_handle(cx);
 619
 620        let is_model_selected = model.is_some();
 621        let is_editor_empty = self.is_editor_empty(cx);
 622
 623        let incompatible_tools = model
 624            .as_ref()
 625            .map(|model| {
 626                self.incompatible_tools_state.update(cx, |state, cx| {
 627                    state
 628                        .incompatible_tools(&model.model, cx)
 629                        .iter()
 630                        .cloned()
 631                        .collect::<Vec<_>>()
 632                })
 633            })
 634            .unwrap_or_default();
 635
 636        let is_editor_expanded = self.editor_is_expanded;
 637        let expand_icon = if is_editor_expanded {
 638            IconName::Minimize
 639        } else {
 640            IconName::Maximize
 641        };
 642
 643        v_flex()
 644            .key_context("MessageEditor")
 645            .on_action(cx.listener(Self::chat))
 646            .on_action(cx.listener(Self::chat_with_follow))
 647            .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
 648                this.profile_selector
 649                    .read(cx)
 650                    .menu_handle()
 651                    .toggle(window, cx);
 652            }))
 653            .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
 654                this.model_selector
 655                    .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
 656            }))
 657            .on_action(cx.listener(Self::toggle_context_picker))
 658            .on_action(cx.listener(Self::remove_all_context))
 659            .on_action(cx.listener(Self::move_up))
 660            .on_action(cx.listener(Self::expand_message_editor))
 661            .on_action(cx.listener(Self::toggle_burn_mode))
 662            .on_action(
 663                cx.listener(|this, _: &KeepAll, window, cx| this.handle_accept_all(window, cx)),
 664            )
 665            .on_action(
 666                cx.listener(|this, _: &RejectAll, window, cx| this.handle_reject_all(window, cx)),
 667            )
 668            .capture_action(cx.listener(Self::paste))
 669            .gap_2()
 670            .p_2()
 671            .bg(editor_bg_color)
 672            .border_t_1()
 673            .border_color(cx.theme().colors().border)
 674            .child(
 675                h_flex()
 676                    .items_start()
 677                    .justify_between()
 678                    .child(self.context_strip.clone())
 679                    .child(
 680                        h_flex()
 681                            .gap_1()
 682                            .when(focus_handle.is_focused(window), |this| {
 683                                this.child(
 684                                    IconButton::new("toggle-height", expand_icon)
 685                                        .icon_size(IconSize::XSmall)
 686                                        .icon_color(Color::Muted)
 687                                        .tooltip({
 688                                            let focus_handle = focus_handle.clone();
 689                                            move |window, cx| {
 690                                                let expand_label = if is_editor_expanded {
 691                                                    "Minimize Message Editor".to_string()
 692                                                } else {
 693                                                    "Expand Message Editor".to_string()
 694                                                };
 695
 696                                                Tooltip::for_action_in(
 697                                                    expand_label,
 698                                                    &ExpandMessageEditor,
 699                                                    &focus_handle,
 700                                                    window,
 701                                                    cx,
 702                                                )
 703                                            }
 704                                        })
 705                                        .on_click(cx.listener(|_, _, window, cx| {
 706                                            window
 707                                                .dispatch_action(Box::new(ExpandMessageEditor), cx);
 708                                        })),
 709                                )
 710                            }),
 711                    ),
 712            )
 713            .child(
 714                v_flex()
 715                    .size_full()
 716                    .gap_4()
 717                    .when(is_editor_expanded, |this| {
 718                        this.h(vh(0.8, window)).justify_between()
 719                    })
 720                    .child(
 721                        v_flex()
 722                            .min_h_16()
 723                            .when(is_editor_expanded, |this| this.h_full())
 724                            .child({
 725                                let settings = ThemeSettings::get_global(cx);
 726                                let font_size = TextSize::Small
 727                                    .rems(cx)
 728                                    .to_pixels(settings.agent_font_size(cx));
 729                                let line_height = settings.buffer_line_height.value() * font_size;
 730
 731                                let text_style = TextStyle {
 732                                    color: cx.theme().colors().text,
 733                                    font_family: settings.buffer_font.family.clone(),
 734                                    font_fallbacks: settings.buffer_font.fallbacks.clone(),
 735                                    font_features: settings.buffer_font.features.clone(),
 736                                    font_size: font_size.into(),
 737                                    line_height: line_height.into(),
 738                                    ..Default::default()
 739                                };
 740
 741                                EditorElement::new(
 742                                    &self.editor,
 743                                    EditorStyle {
 744                                        background: editor_bg_color,
 745                                        local_player: cx.theme().players().local(),
 746                                        text: text_style,
 747                                        syntax: cx.theme().syntax().clone(),
 748                                        ..Default::default()
 749                                    },
 750                                )
 751                                .into_any()
 752                            }),
 753                    )
 754                    .child(
 755                        h_flex()
 756                            .flex_none()
 757                            .justify_between()
 758                            .child(
 759                                h_flex()
 760                                    .child(self.render_follow_toggle(cx))
 761                                    .children(self.render_max_mode_toggle(cx)),
 762                            )
 763                            .child(
 764                                h_flex()
 765                                    .gap_1()
 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(ui::Divider::vertical().color(ui::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 parent_label = 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 name_label = 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 hover_color = cx
1118                                .theme()
1119                                .colors()
1120                                .element_background
1121                                .blend(cx.theme().colors().editor_foreground.opacity(0.025));
1122
1123                            let overlay_gradient = linear_gradient(
1124                                90.,
1125                                linear_color_stop(editor_bg_color, 1.),
1126                                linear_color_stop(editor_bg_color.opacity(0.2), 0.),
1127                            );
1128
1129                            let overlay_gradient_hover = linear_gradient(
1130                                90.,
1131                                linear_color_stop(hover_color, 1.),
1132                                linear_color_stop(hover_color.opacity(0.2), 0.),
1133                            );
1134
1135                            let element = h_flex()
1136                                .group("edited-code")
1137                                .id(("file-container", index))
1138                                .cursor_pointer()
1139                                .relative()
1140                                .py_1()
1141                                .pl_2()
1142                                .pr_1()
1143                                .gap_2()
1144                                .justify_between()
1145                                .bg(cx.theme().colors().editor_background)
1146                                .hover(|style| style.bg(hover_color))
1147                                .when(index < changed_buffers.len() - 1, |parent| {
1148                                    parent.border_color(border_color).border_b_1()
1149                                })
1150                                .child(
1151                                    h_flex()
1152                                        .id("file-name")
1153                                        .pr_8()
1154                                        .gap_1p5()
1155                                        .max_w_full()
1156                                        .overflow_x_scroll()
1157                                        .child(file_icon)
1158                                        .child(
1159                                            h_flex()
1160                                                .gap_0p5()
1161                                                .children(name_label)
1162                                                .children(parent_label),
1163                                        ), // TODO: Implement line diff
1164                                           // .child(Label::new("+").color(Color::Created))
1165                                           // .child(Label::new("-").color(Color::Deleted)),
1166                                )
1167                                .child(
1168                                    div().visible_on_hover("edited-code").child(
1169                                        Button::new("review", "Review")
1170                                            .label_size(LabelSize::Small)
1171                                            .on_click({
1172                                                let buffer = buffer.clone();
1173                                                cx.listener(move |this, _, window, cx| {
1174                                                    this.handle_file_click(
1175                                                        buffer.clone(),
1176                                                        window,
1177                                                        cx,
1178                                                    );
1179                                                })
1180                                            }),
1181                                    ),
1182                                )
1183                                .child(
1184                                    div()
1185                                        .id("gradient-overlay")
1186                                        .absolute()
1187                                        .h_5_6()
1188                                        .w_12()
1189                                        .bottom_0()
1190                                        .right(px(52.))
1191                                        .bg(overlay_gradient)
1192                                        .group_hover("edited-code", |style| {
1193                                            style.bg(overlay_gradient_hover)
1194                                        }),
1195                                )
1196                                .on_click({
1197                                    let buffer = buffer.clone();
1198                                    cx.listener(move |this, _, window, cx| {
1199                                        this.handle_file_click(buffer.clone(), window, cx);
1200                                    })
1201                                });
1202
1203                            Some(element)
1204                        },
1205                    )),
1206                )
1207            })
1208    }
1209
1210    fn render_usage_callout(&self, line_height: Pixels, cx: &mut Context<Self>) -> Option<Div> {
1211        let is_using_zed_provider = self
1212            .thread
1213            .read(cx)
1214            .configured_model()
1215            .map_or(false, |model| {
1216                model.provider.id().0 == ZED_CLOUD_PROVIDER_ID
1217            });
1218        if !is_using_zed_provider {
1219            return None;
1220        }
1221
1222        let user_store = self.user_store.read(cx);
1223
1224        let ubb_enable = user_store
1225            .usage_based_billing_enabled()
1226            .map_or(false, |enabled| enabled);
1227
1228        if ubb_enable {
1229            return None;
1230        }
1231
1232        let plan = user_store
1233            .current_plan()
1234            .map(|plan| match plan {
1235                Plan::Free => zed_llm_client::Plan::ZedFree,
1236                Plan::ZedPro => zed_llm_client::Plan::ZedPro,
1237                Plan::ZedProTrial => zed_llm_client::Plan::ZedProTrial,
1238            })
1239            .unwrap_or(zed_llm_client::Plan::ZedFree);
1240        let usage = self.thread.read(cx).last_usage().or_else(|| {
1241            maybe!({
1242                let amount = user_store.model_request_usage_amount()?;
1243                let limit = user_store.model_request_usage_limit()?.variant?;
1244
1245                Some(RequestUsage {
1246                    amount: amount as i32,
1247                    limit: match limit {
1248                        proto::usage_limit::Variant::Limited(limited) => {
1249                            zed_llm_client::UsageLimit::Limited(limited.limit as i32)
1250                        }
1251                        proto::usage_limit::Variant::Unlimited(_) => {
1252                            zed_llm_client::UsageLimit::Unlimited
1253                        }
1254                    },
1255                })
1256            })
1257        })?;
1258
1259        Some(
1260            div()
1261                .child(UsageCallout::new(plan, usage))
1262                .line_height(line_height),
1263        )
1264    }
1265
1266    fn render_token_limit_callout(
1267        &self,
1268        line_height: Pixels,
1269        token_usage_ratio: TokenUsageRatio,
1270        cx: &mut Context<Self>,
1271    ) -> Option<Div> {
1272        let title = if token_usage_ratio == TokenUsageRatio::Exceeded {
1273            "Thread reached the token limit"
1274        } else {
1275            "Thread reaching the token limit soon"
1276        };
1277
1278        let message = "Start a new thread from a summary to continue the conversation.";
1279
1280        let icon = if token_usage_ratio == TokenUsageRatio::Exceeded {
1281            Icon::new(IconName::X)
1282                .color(Color::Error)
1283                .size(IconSize::XSmall)
1284        } else {
1285            Icon::new(IconName::Warning)
1286                .color(Color::Warning)
1287                .size(IconSize::XSmall)
1288        };
1289
1290        Some(
1291            div()
1292                .child(ui::Callout::multi_line(
1293                    title,
1294                    message,
1295                    icon,
1296                    "Start New Thread",
1297                    Box::new(cx.listener(|this, _, window, cx| {
1298                        let from_thread_id = Some(this.thread.read(cx).id().clone());
1299                        window.dispatch_action(Box::new(NewThread { from_thread_id }), cx);
1300                    })),
1301                ))
1302                .line_height(line_height),
1303        )
1304    }
1305
1306    pub fn last_estimated_token_count(&self) -> Option<usize> {
1307        self.last_estimated_token_count
1308    }
1309
1310    pub fn is_waiting_to_update_token_count(&self) -> bool {
1311        self.update_token_count_task.is_some()
1312    }
1313
1314    fn reload_context(&mut self, cx: &mut Context<Self>) -> Task<Option<ContextLoadResult>> {
1315        let load_task = cx.spawn(async move |this, cx| {
1316            let Ok(load_task) = this.update(cx, |this, cx| {
1317                let new_context = this
1318                    .context_store
1319                    .read(cx)
1320                    .new_context_for_thread(this.thread.read(cx), None);
1321                load_context(new_context, &this.project, &this.prompt_store, cx)
1322            }) else {
1323                return;
1324            };
1325            let result = load_task.await;
1326            this.update(cx, |this, cx| {
1327                this.last_loaded_context = Some(result);
1328                this.load_context_task = None;
1329                this.message_or_context_changed(false, cx);
1330            })
1331            .ok();
1332        });
1333        // Replace existing load task, if any, causing it to be cancelled.
1334        let load_task = load_task.shared();
1335        self.load_context_task = Some(load_task.clone());
1336        cx.spawn(async move |this, cx| {
1337            load_task.await;
1338            this.read_with(cx, |this, _cx| this.last_loaded_context.clone())
1339                .ok()
1340                .flatten()
1341        })
1342    }
1343
1344    fn handle_message_changed(&mut self, cx: &mut Context<Self>) {
1345        self.message_or_context_changed(true, cx);
1346    }
1347
1348    fn message_or_context_changed(&mut self, debounce: bool, cx: &mut Context<Self>) {
1349        cx.emit(MessageEditorEvent::Changed);
1350        self.update_token_count_task.take();
1351
1352        let Some(model) = self.thread.read(cx).configured_model() else {
1353            self.last_estimated_token_count.take();
1354            return;
1355        };
1356
1357        let editor = self.editor.clone();
1358
1359        self.update_token_count_task = Some(cx.spawn(async move |this, cx| {
1360            if debounce {
1361                cx.background_executor()
1362                    .timer(Duration::from_millis(200))
1363                    .await;
1364            }
1365
1366            let token_count = if let Some(task) = this
1367                .update(cx, |this, cx| {
1368                    let loaded_context = this
1369                        .last_loaded_context
1370                        .as_ref()
1371                        .map(|context_load_result| &context_load_result.loaded_context);
1372                    let message_text = editor.read(cx).text(cx);
1373
1374                    if message_text.is_empty()
1375                        && loaded_context.map_or(true, |loaded_context| loaded_context.is_empty())
1376                    {
1377                        return None;
1378                    }
1379
1380                    let mut request_message = LanguageModelRequestMessage {
1381                        role: language_model::Role::User,
1382                        content: Vec::new(),
1383                        cache: false,
1384                    };
1385
1386                    if let Some(loaded_context) = loaded_context {
1387                        loaded_context.add_to_request_message(&mut request_message);
1388                    }
1389
1390                    if !message_text.is_empty() {
1391                        request_message
1392                            .content
1393                            .push(MessageContent::Text(message_text));
1394                    }
1395
1396                    let request = language_model::LanguageModelRequest {
1397                        thread_id: None,
1398                        prompt_id: None,
1399                        intent: None,
1400                        mode: None,
1401                        messages: vec![request_message],
1402                        tools: vec![],
1403                        tool_choice: None,
1404                        stop: vec![],
1405                        temperature: AgentSettings::temperature_for_model(&model.model, cx),
1406                    };
1407
1408                    Some(model.model.count_tokens(request, cx))
1409                })
1410                .ok()
1411                .flatten()
1412            {
1413                task.await.log_err()
1414            } else {
1415                Some(0)
1416            };
1417
1418            this.update(cx, |this, cx| {
1419                if let Some(token_count) = token_count {
1420                    this.last_estimated_token_count = Some(token_count);
1421                    cx.emit(MessageEditorEvent::EstimatedTokenCount);
1422                }
1423                this.update_token_count_task.take();
1424            })
1425            .ok();
1426        }));
1427    }
1428}
1429
1430pub fn extract_message_creases(
1431    editor: &mut Editor,
1432    cx: &mut Context<'_, Editor>,
1433) -> Vec<MessageCrease> {
1434    let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1435    let mut contexts_by_crease_id = editor
1436        .addon_mut::<ContextCreasesAddon>()
1437        .map(std::mem::take)
1438        .unwrap_or_default()
1439        .into_inner()
1440        .into_iter()
1441        .flat_map(|(key, creases)| {
1442            let context = key.0;
1443            creases
1444                .into_iter()
1445                .map(move |(id, _)| (id, context.clone()))
1446        })
1447        .collect::<HashMap<_, _>>();
1448    // Filter the addon's list of creases based on what the editor reports,
1449    // since the addon might have removed creases in it.
1450    let creases = editor.display_map.update(cx, |display_map, cx| {
1451        display_map
1452            .snapshot(cx)
1453            .crease_snapshot
1454            .creases()
1455            .filter_map(|(id, crease)| {
1456                Some((
1457                    id,
1458                    (
1459                        crease.range().to_offset(&buffer_snapshot),
1460                        crease.metadata()?.clone(),
1461                    ),
1462                ))
1463            })
1464            .map(|(id, (range, metadata))| {
1465                let context = contexts_by_crease_id.remove(&id);
1466                MessageCrease {
1467                    range,
1468                    metadata,
1469                    context,
1470                }
1471            })
1472            .collect()
1473    });
1474    creases
1475}
1476
1477impl EventEmitter<MessageEditorEvent> for MessageEditor {}
1478
1479pub enum MessageEditorEvent {
1480    EstimatedTokenCount,
1481    Changed,
1482}
1483
1484impl Focusable for MessageEditor {
1485    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
1486        self.editor.focus_handle(cx)
1487    }
1488}
1489
1490impl Render for MessageEditor {
1491    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1492        let thread = self.thread.read(cx);
1493        let token_usage_ratio = thread
1494            .total_token_usage()
1495            .map_or(TokenUsageRatio::Normal, |total_token_usage| {
1496                total_token_usage.ratio()
1497            });
1498
1499        let action_log = self.thread.read(cx).action_log();
1500        let changed_buffers = action_log.read(cx).changed_buffers(cx);
1501
1502        let line_height = TextSize::Small.rems(cx).to_pixels(window.rem_size()) * 1.5;
1503
1504        v_flex()
1505            .size_full()
1506            .when(changed_buffers.len() > 0, |parent| {
1507                parent.child(self.render_changed_buffers(&changed_buffers, window, cx))
1508            })
1509            .child(self.render_editor(window, cx))
1510            .children({
1511                let usage_callout = self.render_usage_callout(line_height, cx);
1512
1513                if usage_callout.is_some() {
1514                    usage_callout
1515                } else if token_usage_ratio != TokenUsageRatio::Normal {
1516                    self.render_token_limit_callout(line_height, token_usage_ratio, cx)
1517                } else {
1518                    None
1519                }
1520            })
1521    }
1522}
1523
1524pub fn insert_message_creases(
1525    editor: &mut Editor,
1526    message_creases: &[MessageCrease],
1527    context_store: &Entity<ContextStore>,
1528    window: &mut Window,
1529    cx: &mut Context<'_, Editor>,
1530) {
1531    let buffer_snapshot = editor.buffer().read(cx).snapshot(cx);
1532    let creases = message_creases
1533        .iter()
1534        .map(|crease| {
1535            let start = buffer_snapshot.anchor_after(crease.range.start);
1536            let end = buffer_snapshot.anchor_before(crease.range.end);
1537            crease_for_mention(
1538                crease.metadata.label.clone(),
1539                crease.metadata.icon_path.clone(),
1540                start..end,
1541                cx.weak_entity(),
1542            )
1543        })
1544        .collect::<Vec<_>>();
1545    let ids = editor.insert_creases(creases.clone(), cx);
1546    editor.fold_creases(creases, false, window, cx);
1547    if let Some(addon) = editor.addon_mut::<ContextCreasesAddon>() {
1548        for (crease, id) in message_creases.iter().zip(ids) {
1549            if let Some(context) = crease.context.as_ref() {
1550                let key = AgentContextKey(context.clone());
1551                addon.add_creases(
1552                    context_store,
1553                    key,
1554                    vec![(id, crease.metadata.label.clone())],
1555                    cx,
1556                );
1557            }
1558        }
1559    }
1560}
1561impl Component for MessageEditor {
1562    fn scope() -> ComponentScope {
1563        ComponentScope::Agent
1564    }
1565
1566    fn description() -> Option<&'static str> {
1567        Some(
1568            "The composer experience of the Agent Panel. This interface handles context, composing messages, switching profiles, models and more.",
1569        )
1570    }
1571}
1572
1573impl AgentPreview for MessageEditor {
1574    fn agent_preview(
1575        workspace: WeakEntity<Workspace>,
1576        active_thread: Entity<ActiveThread>,
1577        window: &mut Window,
1578        cx: &mut App,
1579    ) -> Option<AnyElement> {
1580        if let Some(workspace) = workspace.upgrade() {
1581            let fs = workspace.read(cx).app_state().fs.clone();
1582            let user_store = workspace.read(cx).app_state().user_store.clone();
1583            let project = workspace.read(cx).project().clone();
1584            let weak_project = project.downgrade();
1585            let context_store = cx.new(|_cx| ContextStore::new(weak_project, None));
1586            let active_thread = active_thread.read(cx);
1587            let thread = active_thread.thread().clone();
1588            let thread_store = active_thread.thread_store().clone();
1589            let text_thread_store = active_thread.text_thread_store().clone();
1590
1591            let default_message_editor = cx.new(|cx| {
1592                MessageEditor::new(
1593                    fs,
1594                    workspace.downgrade(),
1595                    user_store,
1596                    context_store,
1597                    None,
1598                    thread_store.downgrade(),
1599                    text_thread_store.downgrade(),
1600                    thread,
1601                    window,
1602                    cx,
1603                )
1604            });
1605
1606            Some(
1607                v_flex()
1608                    .gap_4()
1609                    .children(vec![single_example(
1610                        "Default Message Editor",
1611                        div()
1612                            .w(px(540.))
1613                            .pt_12()
1614                            .bg(cx.theme().colors().panel_background)
1615                            .border_1()
1616                            .border_color(cx.theme().colors().border)
1617                            .child(default_message_editor.clone())
1618                            .into_any_element(),
1619                    )])
1620                    .into_any_element(),
1621            )
1622        } else {
1623            None
1624        }
1625    }
1626}
1627
1628register_agent_preview!(MessageEditor);