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