message_editor.rs

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