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