message_editor.rs

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