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