message_editor.rs

   1use std::collections::BTreeMap;
   2use std::sync::Arc;
   3
   4use crate::assistant_model_selector::ModelType;
   5use crate::context::{AssistantContext, format_context_as_string};
   6use crate::tool_compatibility::{IncompatibleToolsState, IncompatibleToolsTooltip};
   7use buffer_diff::BufferDiff;
   8use collections::HashSet;
   9use editor::actions::{MoveUp, Paste};
  10use editor::{
  11    ContextMenuOptions, ContextMenuPlacement, Editor, EditorElement, EditorEvent, EditorMode,
  12    EditorStyle, MultiBuffer,
  13};
  14use file_icons::FileIcons;
  15use fs::Fs;
  16use gpui::{
  17    Animation, AnimationExt, App, ClipboardEntry, Entity, EventEmitter, Focusable, Subscription,
  18    Task, TextStyle, WeakEntity, linear_color_stop, linear_gradient, point, pulsating_between,
  19};
  20use language::{Buffer, Language};
  21use language_model::{ConfiguredModel, LanguageModelRegistry, LanguageModelRequestMessage};
  22use language_model_selector::ToggleModelSelector;
  23use multi_buffer;
  24use project::Project;
  25use settings::Settings;
  26use std::time::Duration;
  27use theme::ThemeSettings;
  28use ui::{Disclosure, KeyBinding, PopoverMenuHandle, Tooltip, prelude::*};
  29use util::ResultExt as _;
  30use workspace::Workspace;
  31
  32use crate::assistant_model_selector::AssistantModelSelector;
  33use crate::context_picker::{ContextPicker, ContextPickerCompletionProvider};
  34use crate::context_store::{ContextStore, refresh_context_store_text};
  35use crate::context_strip::{ContextStrip, ContextStripEvent, SuggestContextKind};
  36use crate::profile_selector::ProfileSelector;
  37use crate::thread::{Thread, TokenUsageRatio};
  38use crate::thread_store::ThreadStore;
  39use crate::{
  40    AgentDiff, Chat, ChatMode, ExpandMessageEditor, NewThread, OpenAgentDiff, RemoveAllContext,
  41    ToggleContextPicker, ToggleProfileSelector,
  42};
  43
  44pub struct MessageEditor {
  45    thread: Entity<Thread>,
  46    incompatible_tools_state: Entity<IncompatibleToolsState>,
  47    editor: Entity<Editor>,
  48    #[allow(dead_code)]
  49    workspace: WeakEntity<Workspace>,
  50    project: Entity<Project>,
  51    context_store: Entity<ContextStore>,
  52    context_strip: Entity<ContextStrip>,
  53    context_picker_menu_handle: PopoverMenuHandle<ContextPicker>,
  54    model_selector: Entity<AssistantModelSelector>,
  55    profile_selector: Entity<ProfileSelector>,
  56    edits_expanded: bool,
  57    editor_is_expanded: bool,
  58    waiting_for_summaries_to_send: bool,
  59    last_estimated_token_count: Option<usize>,
  60    update_token_count_task: Option<Task<anyhow::Result<()>>>,
  61    _subscriptions: Vec<Subscription>,
  62}
  63
  64const MAX_EDITOR_LINES: usize = 8;
  65
  66impl MessageEditor {
  67    pub fn new(
  68        fs: Arc<dyn Fs>,
  69        workspace: WeakEntity<Workspace>,
  70        context_store: Entity<ContextStore>,
  71        thread_store: WeakEntity<ThreadStore>,
  72        thread: Entity<Thread>,
  73        window: &mut Window,
  74        cx: &mut Context<Self>,
  75    ) -> Self {
  76        let context_picker_menu_handle = PopoverMenuHandle::default();
  77        let model_selector_menu_handle = PopoverMenuHandle::default();
  78
  79        let language = Language::new(
  80            language::LanguageConfig {
  81                completion_query_characters: HashSet::from_iter(['.', '-', '_', '@']),
  82                ..Default::default()
  83            },
  84            None,
  85        );
  86
  87        let editor = cx.new(|cx| {
  88            let buffer = cx.new(|cx| Buffer::local("", cx).with_language(Arc::new(language), cx));
  89            let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
  90            let mut editor = Editor::new(
  91                editor::EditorMode::AutoHeight {
  92                    max_lines: MAX_EDITOR_LINES,
  93                },
  94                buffer,
  95                None,
  96                window,
  97                cx,
  98            );
  99            editor.set_placeholder_text("Ask anything, @ to mention, ↑ to select", cx);
 100            editor.set_show_indent_guides(false, cx);
 101            editor.set_soft_wrap();
 102            editor.set_context_menu_options(ContextMenuOptions {
 103                min_entries_visible: 12,
 104                max_entries_visible: 12,
 105                placement: Some(ContextMenuPlacement::Above),
 106            });
 107            editor
 108        });
 109
 110        let editor_entity = editor.downgrade();
 111        editor.update(cx, |editor, _| {
 112            editor.set_completion_provider(Some(Box::new(ContextPickerCompletionProvider::new(
 113                workspace.clone(),
 114                context_store.downgrade(),
 115                Some(thread_store.clone()),
 116                editor_entity,
 117            ))));
 118        });
 119
 120        let context_strip = cx.new(|cx| {
 121            ContextStrip::new(
 122                context_store.clone(),
 123                workspace.clone(),
 124                Some(thread_store.clone()),
 125                context_picker_menu_handle.clone(),
 126                SuggestContextKind::File,
 127                window,
 128                cx,
 129            )
 130        });
 131
 132        let incompatible_tools =
 133            cx.new(|cx| IncompatibleToolsState::new(thread.read(cx).tools().clone(), cx));
 134
 135        let subscriptions = vec![
 136            cx.subscribe_in(&context_strip, window, Self::handle_context_strip_event),
 137            cx.subscribe(&editor, |this, _, event, cx| match event {
 138                EditorEvent::BufferEdited => {
 139                    this.message_or_context_changed(true, cx);
 140                }
 141                _ => {}
 142            }),
 143            cx.observe(&context_store, |this, _, cx| {
 144                this.message_or_context_changed(false, cx);
 145            }),
 146        ];
 147
 148        Self {
 149            editor: editor.clone(),
 150            project: thread.read(cx).project().clone(),
 151            thread,
 152            incompatible_tools_state: incompatible_tools.clone(),
 153            workspace,
 154            context_store,
 155            context_strip,
 156            context_picker_menu_handle,
 157            model_selector: cx.new(|cx| {
 158                AssistantModelSelector::new(
 159                    fs.clone(),
 160                    model_selector_menu_handle,
 161                    editor.focus_handle(cx),
 162                    ModelType::Default,
 163                    window,
 164                    cx,
 165                )
 166            }),
 167            edits_expanded: false,
 168            editor_is_expanded: false,
 169            waiting_for_summaries_to_send: false,
 170            profile_selector: cx
 171                .new(|cx| ProfileSelector::new(fs, thread_store, editor.focus_handle(cx), cx)),
 172            last_estimated_token_count: None,
 173            update_token_count_task: None,
 174            _subscriptions: subscriptions,
 175        }
 176    }
 177
 178    fn toggle_chat_mode(&mut self, _: &ChatMode, _window: &mut Window, cx: &mut Context<Self>) {
 179        cx.notify();
 180    }
 181
 182    pub fn expand_message_editor(
 183        &mut self,
 184        _: &ExpandMessageEditor,
 185        _window: &mut Window,
 186        cx: &mut Context<Self>,
 187    ) {
 188        self.set_editor_is_expanded(!self.editor_is_expanded, cx);
 189    }
 190
 191    fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
 192        self.editor_is_expanded = is_expanded;
 193        self.editor.update(cx, |editor, _| {
 194            if self.editor_is_expanded {
 195                editor.set_mode(EditorMode::Full {
 196                    scale_ui_elements_with_buffer_font_size: false,
 197                    show_active_line_background: false,
 198                })
 199            } else {
 200                editor.set_mode(EditorMode::AutoHeight {
 201                    max_lines: MAX_EDITOR_LINES,
 202                })
 203            }
 204        });
 205        cx.notify();
 206    }
 207
 208    fn toggle_context_picker(
 209        &mut self,
 210        _: &ToggleContextPicker,
 211        window: &mut Window,
 212        cx: &mut Context<Self>,
 213    ) {
 214        self.context_picker_menu_handle.toggle(window, cx);
 215    }
 216    pub fn remove_all_context(
 217        &mut self,
 218        _: &RemoveAllContext,
 219        _window: &mut Window,
 220        cx: &mut Context<Self>,
 221    ) {
 222        self.context_store.update(cx, |store, _cx| store.clear());
 223        cx.notify();
 224    }
 225
 226    fn chat(&mut self, _: &Chat, window: &mut Window, cx: &mut Context<Self>) {
 227        if self.is_editor_empty(cx) {
 228            return;
 229        }
 230
 231        if self.thread.read(cx).is_generating() {
 232            self.stop_current_and_send_new_message(window, cx);
 233            return;
 234        }
 235
 236        self.set_editor_is_expanded(false, cx);
 237        self.send_to_model(window, cx);
 238
 239        cx.notify();
 240    }
 241
 242    fn is_editor_empty(&self, cx: &App) -> bool {
 243        self.editor.read(cx).text(cx).trim().is_empty()
 244    }
 245
 246    fn is_model_selected(&self, cx: &App) -> bool {
 247        LanguageModelRegistry::read_global(cx)
 248            .default_model()
 249            .is_some()
 250    }
 251
 252    fn send_to_model(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 253        let model_registry = LanguageModelRegistry::read_global(cx);
 254        let Some(ConfiguredModel { model, provider }) = model_registry.default_model() else {
 255            return;
 256        };
 257
 258        if provider.must_accept_terms(cx) {
 259            cx.notify();
 260            return;
 261        }
 262
 263        let user_message = self.editor.update(cx, |editor, cx| {
 264            let text = editor.text(cx);
 265            editor.clear(window, cx);
 266            text
 267        });
 268
 269        self.last_estimated_token_count.take();
 270        cx.emit(MessageEditorEvent::EstimatedTokenCount);
 271
 272        let refresh_task =
 273            refresh_context_store_text(self.context_store.clone(), &HashSet::default(), cx);
 274        let wait_for_images = self.context_store.read(cx).wait_for_images(cx);
 275
 276        let thread = self.thread.clone();
 277        let context_store = self.context_store.clone();
 278        let git_store = self.project.read(cx).git_store().clone();
 279        let checkpoint = git_store.update(cx, |git_store, cx| git_store.checkpoint(cx));
 280
 281        cx.spawn(async move |this, cx| {
 282            let checkpoint = checkpoint.await.ok();
 283            refresh_task.await;
 284            wait_for_images.await;
 285
 286            thread
 287                .update(cx, |thread, cx| {
 288                    let context = context_store.read(cx).context().clone();
 289                    thread.insert_user_message(user_message, context, checkpoint, cx);
 290                })
 291                .log_err();
 292
 293            context_store
 294                .update(cx, |context_store, cx| {
 295                    let excerpt_ids = context_store
 296                        .context()
 297                        .iter()
 298                        .filter(|ctx| {
 299                            matches!(
 300                                ctx,
 301                                AssistantContext::Selection(_) | AssistantContext::Image(_)
 302                            )
 303                        })
 304                        .map(|ctx| ctx.id())
 305                        .collect::<Vec<_>>();
 306
 307                    for id in excerpt_ids {
 308                        context_store.remove_context(id, cx);
 309                    }
 310                })
 311                .log_err();
 312
 313            if let Some(wait_for_summaries) = context_store
 314                .update(cx, |context_store, cx| context_store.wait_for_summaries(cx))
 315                .log_err()
 316            {
 317                this.update(cx, |this, cx| {
 318                    this.waiting_for_summaries_to_send = true;
 319                    cx.notify();
 320                })
 321                .log_err();
 322
 323                wait_for_summaries.await;
 324
 325                this.update(cx, |this, cx| {
 326                    this.waiting_for_summaries_to_send = false;
 327                    cx.notify();
 328                })
 329                .log_err();
 330            }
 331
 332            // Send to model after summaries are done
 333            thread
 334                .update(cx, |thread, cx| {
 335                    thread.advance_prompt_id();
 336                    thread.send_to_model(model, cx);
 337                })
 338                .log_err();
 339        })
 340        .detach();
 341    }
 342
 343    fn stop_current_and_send_new_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 344        let cancelled = self
 345            .thread
 346            .update(cx, |thread, cx| thread.cancel_last_completion(cx));
 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(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        AgentDiff::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) = AgentDiff::deploy(self.thread.clone(), self.workspace.clone(), window, cx)
 421        {
 422            let path_key = multi_buffer::PathKey::for_buffer(&buffer, cx);
 423            diff.update(cx, |diff, cx| diff.move_to_path(path_key, window, cx));
 424        }
 425    }
 426
 427    fn render_editor(
 428        &self,
 429        font_size: Rems,
 430        line_height: Pixels,
 431        window: &mut Window,
 432        cx: &mut Context<Self>,
 433    ) -> Div {
 434        let thread = self.thread.read(cx);
 435
 436        let editor_bg_color = cx.theme().colors().editor_background;
 437        let is_generating = thread.is_generating();
 438        let focus_handle = self.editor.focus_handle(cx);
 439
 440        let is_model_selected = self.is_model_selected(cx);
 441        let is_editor_empty = self.is_editor_empty(cx);
 442
 443        let model = LanguageModelRegistry::read_global(cx)
 444            .default_model()
 445            .map(|default| default.model.clone());
 446
 447        let incompatible_tools = model
 448            .as_ref()
 449            .map(|model| {
 450                self.incompatible_tools_state.update(cx, |state, cx| {
 451                    state
 452                        .incompatible_tools(model, cx)
 453                        .iter()
 454                        .cloned()
 455                        .collect::<Vec<_>>()
 456                })
 457            })
 458            .unwrap_or_default();
 459
 460        let is_editor_expanded = self.editor_is_expanded;
 461        let expand_icon = if is_editor_expanded {
 462            IconName::Minimize
 463        } else {
 464            IconName::Maximize
 465        };
 466
 467        v_flex()
 468            .key_context("MessageEditor")
 469            .on_action(cx.listener(Self::chat))
 470            .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
 471                this.profile_selector
 472                    .read(cx)
 473                    .menu_handle()
 474                    .toggle(window, cx);
 475            }))
 476            .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
 477                this.model_selector
 478                    .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
 479            }))
 480            .on_action(cx.listener(Self::toggle_context_picker))
 481            .on_action(cx.listener(Self::remove_all_context))
 482            .on_action(cx.listener(Self::move_up))
 483            .on_action(cx.listener(Self::toggle_chat_mode))
 484            .on_action(cx.listener(Self::expand_message_editor))
 485            .capture_action(cx.listener(Self::paste))
 486            .gap_2()
 487            .p_2()
 488            .bg(editor_bg_color)
 489            .border_t_1()
 490            .border_color(cx.theme().colors().border)
 491            .child(
 492                h_flex()
 493                    .items_start()
 494                    .justify_between()
 495                    .child(self.context_strip.clone())
 496                    .child(
 497                        IconButton::new("toggle-height", expand_icon)
 498                            .icon_size(IconSize::XSmall)
 499                            .icon_color(Color::Muted)
 500                            .tooltip({
 501                                let focus_handle = focus_handle.clone();
 502                                move |window, cx| {
 503                                    let expand_label = if is_editor_expanded {
 504                                        "Minimize Message Editor".to_string()
 505                                    } else {
 506                                        "Expand Message Editor".to_string()
 507                                    };
 508
 509                                    Tooltip::for_action_in(
 510                                        expand_label,
 511                                        &ExpandMessageEditor,
 512                                        &focus_handle,
 513                                        window,
 514                                        cx,
 515                                    )
 516                                }
 517                            })
 518                            .on_click(cx.listener(|_, _, window, cx| {
 519                                window.dispatch_action(Box::new(ExpandMessageEditor), cx);
 520                            })),
 521                    ),
 522            )
 523            .child(
 524                v_flex()
 525                    .size_full()
 526                    .gap_4()
 527                    .when(is_editor_expanded, |this| {
 528                        this.h(vh(0.8, window)).justify_between()
 529                    })
 530                    .child(
 531                        div()
 532                            .min_h_16()
 533                            .when(is_editor_expanded, |this| this.h_full())
 534                            .child({
 535                                let settings = ThemeSettings::get_global(cx);
 536
 537                                let text_style = TextStyle {
 538                                    color: cx.theme().colors().text,
 539                                    font_family: settings.buffer_font.family.clone(),
 540                                    font_fallbacks: settings.buffer_font.fallbacks.clone(),
 541                                    font_features: settings.buffer_font.features.clone(),
 542                                    font_size: font_size.into(),
 543                                    line_height: line_height.into(),
 544                                    ..Default::default()
 545                                };
 546
 547                                EditorElement::new(
 548                                    &self.editor,
 549                                    EditorStyle {
 550                                        background: editor_bg_color,
 551                                        local_player: cx.theme().players().local(),
 552                                        text: text_style,
 553                                        syntax: cx.theme().syntax().clone(),
 554                                        ..Default::default()
 555                                    },
 556                                )
 557                                .into_any()
 558                            }),
 559                    )
 560                    .child(
 561                        h_flex()
 562                            .flex_none()
 563                            .justify_between()
 564                            .child(h_flex().gap_2().child(self.profile_selector.clone()))
 565                            .child(
 566                                h_flex()
 567                                    .gap_1()
 568                                    .when(!incompatible_tools.is_empty(), |this| {
 569                                        this.child(
 570                                            IconButton::new(
 571                                                "tools-incompatible-warning",
 572                                                IconName::Warning,
 573                                            )
 574                                            .icon_color(Color::Warning)
 575                                            .icon_size(IconSize::Small)
 576                                            .tooltip({
 577                                                move |_, cx| {
 578                                                    cx.new(|_| IncompatibleToolsTooltip {
 579                                                        incompatible_tools: incompatible_tools
 580                                                            .clone(),
 581                                                    })
 582                                                    .into()
 583                                                }
 584                                            }),
 585                                        )
 586                                    })
 587                                    .child(self.model_selector.clone())
 588                                    .map({
 589                                        let focus_handle = focus_handle.clone();
 590                                        move |parent| {
 591                                            if is_generating {
 592                                                parent
 593                                                    .when(is_editor_empty, |parent| {
 594                                                        parent.child(
 595                                                            IconButton::new(
 596                                                                "stop-generation",
 597                                                                IconName::StopFilled,
 598                                                            )
 599                                                            .icon_color(Color::Error)
 600                                                            .style(ButtonStyle::Tinted(
 601                                                                ui::TintColor::Error,
 602                                                            ))
 603                                                            .tooltip(move |window, cx| {
 604                                                                Tooltip::for_action(
 605                                                                    "Stop Generation",
 606                                                                    &editor::actions::Cancel,
 607                                                                    window,
 608                                                                    cx,
 609                                                                )
 610                                                            })
 611                                                            .on_click({
 612                                                                let focus_handle =
 613                                                                    focus_handle.clone();
 614                                                                move |_event, window, cx| {
 615                                                                    focus_handle.dispatch_action(
 616                                                                        &editor::actions::Cancel,
 617                                                                        window,
 618                                                                        cx,
 619                                                                    );
 620                                                                }
 621                                                            })
 622                                                            .with_animation(
 623                                                                "pulsating-label",
 624                                                                Animation::new(
 625                                                                    Duration::from_secs(2),
 626                                                                )
 627                                                                .repeat()
 628                                                                .with_easing(pulsating_between(
 629                                                                    0.4, 1.0,
 630                                                                )),
 631                                                                |icon_button, delta| {
 632                                                                    icon_button.alpha(delta)
 633                                                                },
 634                                                            ),
 635                                                        )
 636                                                    })
 637                                                    .when(!is_editor_empty, |parent| {
 638                                                        parent.child(
 639                                                    IconButton::new("send-message", IconName::Send)
 640                                                        .icon_color(Color::Accent)
 641                                                        .style(ButtonStyle::Filled)
 642                                                        .disabled(
 643                                                            !is_model_selected
 644                                                                || self
 645                                                                    .waiting_for_summaries_to_send,
 646                                                        )
 647                                                        .on_click({
 648                                                            let focus_handle = focus_handle.clone();
 649                                                            move |_event, window, cx| {
 650                                                                focus_handle.dispatch_action(
 651                                                                    &Chat, window, cx,
 652                                                                );
 653                                                            }
 654                                                        })
 655                                                        .tooltip(move |window, cx| {
 656                                                            Tooltip::for_action(
 657                                                                "Stop and Send New Message",
 658                                                                &Chat,
 659                                                                window,
 660                                                                cx,
 661                                                            )
 662                                                        }),
 663                                                )
 664                                                    })
 665                                            } else {
 666                                                parent.child(
 667                                                    IconButton::new("send-message", IconName::Send)
 668                                                        .icon_color(Color::Accent)
 669                                                        .style(ButtonStyle::Filled)
 670                                                        .disabled(
 671                                                            is_editor_empty
 672                                                                || !is_model_selected
 673                                                                || self
 674                                                                    .waiting_for_summaries_to_send,
 675                                                        )
 676                                                        .on_click({
 677                                                            let focus_handle = focus_handle.clone();
 678                                                            move |_event, window, cx| {
 679                                                                focus_handle.dispatch_action(
 680                                                                    &Chat, window, cx,
 681                                                                );
 682                                                            }
 683                                                        })
 684                                                        .when(
 685                                                            !is_editor_empty && is_model_selected,
 686                                                            |button| {
 687                                                                button.tooltip(move |window, cx| {
 688                                                                    Tooltip::for_action(
 689                                                                        "Send", &Chat, window, cx,
 690                                                                    )
 691                                                                })
 692                                                            },
 693                                                        )
 694                                                        .when(is_editor_empty, |button| {
 695                                                            button.tooltip(Tooltip::text(
 696                                                                "Type a message to submit",
 697                                                            ))
 698                                                        })
 699                                                        .when(!is_model_selected, |button| {
 700                                                            button.tooltip(Tooltip::text(
 701                                                                "Select a model to continue",
 702                                                            ))
 703                                                        }),
 704                                                )
 705                                            }
 706                                        }
 707                                    }),
 708                            ),
 709                    ),
 710            )
 711    }
 712
 713    fn render_changed_buffers(
 714        &self,
 715        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
 716        window: &mut Window,
 717        cx: &mut Context<Self>,
 718    ) -> Div {
 719        let focus_handle = self.editor.focus_handle(cx);
 720
 721        let editor_bg_color = cx.theme().colors().editor_background;
 722        let border_color = cx.theme().colors().border;
 723        let active_color = cx.theme().colors().element_selected;
 724        let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
 725        let is_edit_changes_expanded = self.edits_expanded;
 726
 727        v_flex()
 728            .mx_2()
 729            .bg(bg_edit_files_disclosure)
 730            .border_1()
 731            .border_b_0()
 732            .border_color(border_color)
 733            .rounded_t_md()
 734            .shadow(smallvec::smallvec![gpui::BoxShadow {
 735                color: gpui::black().opacity(0.15),
 736                offset: point(px(1.), px(-1.)),
 737                blur_radius: px(3.),
 738                spread_radius: px(0.),
 739            }])
 740            .child(
 741                h_flex()
 742                    .id("edits-container")
 743                    .cursor_pointer()
 744                    .p_1p5()
 745                    .justify_between()
 746                    .when(is_edit_changes_expanded, |this| {
 747                        this.border_b_1().border_color(border_color)
 748                    })
 749                    .on_click(
 750                        cx.listener(|this, _, window, cx| this.handle_review_click(window, cx)),
 751                    )
 752                    .child(
 753                        h_flex()
 754                            .gap_1()
 755                            .child(
 756                                Disclosure::new("edits-disclosure", is_edit_changes_expanded)
 757                                    .on_click(cx.listener(|this, _ev, _window, cx| {
 758                                        this.edits_expanded = !this.edits_expanded;
 759                                        cx.notify();
 760                                    })),
 761                            )
 762                            .child(
 763                                Label::new("Edits")
 764                                    .size(LabelSize::Small)
 765                                    .color(Color::Muted),
 766                            )
 767                            .child(Label::new("").size(LabelSize::XSmall).color(Color::Muted))
 768                            .child(
 769                                Label::new(format!(
 770                                    "{} {}",
 771                                    changed_buffers.len(),
 772                                    if changed_buffers.len() == 1 {
 773                                        "file"
 774                                    } else {
 775                                        "files"
 776                                    }
 777                                ))
 778                                .size(LabelSize::Small)
 779                                .color(Color::Muted),
 780                            ),
 781                    )
 782                    .child(
 783                        Button::new("review", "Review Changes")
 784                            .label_size(LabelSize::Small)
 785                            .key_binding(
 786                                KeyBinding::for_action_in(
 787                                    &OpenAgentDiff,
 788                                    &focus_handle,
 789                                    window,
 790                                    cx,
 791                                )
 792                                .map(|kb| kb.size(rems_from_px(12.))),
 793                            )
 794                            .on_click(cx.listener(|this, _, window, cx| {
 795                                this.handle_review_click(window, cx)
 796                            })),
 797                    ),
 798            )
 799            .when(is_edit_changes_expanded, |parent| {
 800                parent.child(
 801                    v_flex().children(changed_buffers.into_iter().enumerate().flat_map(
 802                        |(index, (buffer, _diff))| {
 803                            let file = buffer.read(cx).file()?;
 804                            let path = file.path();
 805
 806                            let parent_label = path.parent().and_then(|parent| {
 807                                let parent_str = parent.to_string_lossy();
 808
 809                                if parent_str.is_empty() {
 810                                    None
 811                                } else {
 812                                    Some(
 813                                        Label::new(format!(
 814                                            "/{}{}",
 815                                            parent_str,
 816                                            std::path::MAIN_SEPARATOR_STR
 817                                        ))
 818                                        .color(Color::Muted)
 819                                        .size(LabelSize::XSmall)
 820                                        .buffer_font(cx),
 821                                    )
 822                                }
 823                            });
 824
 825                            let name_label = path.file_name().map(|name| {
 826                                Label::new(name.to_string_lossy().to_string())
 827                                    .size(LabelSize::XSmall)
 828                                    .buffer_font(cx)
 829                            });
 830
 831                            let file_icon = FileIcons::get_icon(&path, cx)
 832                                .map(Icon::from_path)
 833                                .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
 834                                .unwrap_or_else(|| {
 835                                    Icon::new(IconName::File)
 836                                        .color(Color::Muted)
 837                                        .size(IconSize::Small)
 838                                });
 839
 840                            let hover_color = cx
 841                                .theme()
 842                                .colors()
 843                                .element_background
 844                                .blend(cx.theme().colors().editor_foreground.opacity(0.025));
 845
 846                            let overlay_gradient = linear_gradient(
 847                                90.,
 848                                linear_color_stop(editor_bg_color, 1.),
 849                                linear_color_stop(editor_bg_color.opacity(0.2), 0.),
 850                            );
 851
 852                            let overlay_gradient_hover = linear_gradient(
 853                                90.,
 854                                linear_color_stop(hover_color, 1.),
 855                                linear_color_stop(hover_color.opacity(0.2), 0.),
 856                            );
 857
 858                            let element = h_flex()
 859                                .group("edited-code")
 860                                .id(("file-container", index))
 861                                .cursor_pointer()
 862                                .relative()
 863                                .py_1()
 864                                .pl_2()
 865                                .pr_1()
 866                                .gap_2()
 867                                .justify_between()
 868                                .bg(cx.theme().colors().editor_background)
 869                                .hover(|style| style.bg(hover_color))
 870                                .when(index + 1 < changed_buffers.len(), |parent| {
 871                                    parent.border_color(border_color).border_b_1()
 872                                })
 873                                .child(
 874                                    h_flex()
 875                                        .id("file-name")
 876                                        .pr_8()
 877                                        .gap_1p5()
 878                                        .max_w_full()
 879                                        .overflow_x_scroll()
 880                                        .child(file_icon)
 881                                        .child(
 882                                            h_flex()
 883                                                .gap_0p5()
 884                                                .children(name_label)
 885                                                .children(parent_label),
 886                                        ) // TODO: show lines changed
 887                                        .child(Label::new("+").color(Color::Created))
 888                                        .child(Label::new("-").color(Color::Deleted)),
 889                                )
 890                                .child(
 891                                    div().visible_on_hover("edited-code").child(
 892                                        Button::new("review", "Review")
 893                                            .label_size(LabelSize::Small)
 894                                            .on_click({
 895                                                let buffer = buffer.clone();
 896                                                cx.listener(move |this, _, window, cx| {
 897                                                    this.handle_file_click(
 898                                                        buffer.clone(),
 899                                                        window,
 900                                                        cx,
 901                                                    );
 902                                                })
 903                                            }),
 904                                    ),
 905                                )
 906                                .child(
 907                                    div()
 908                                        .id("gradient-overlay")
 909                                        .absolute()
 910                                        .h_5_6()
 911                                        .w_12()
 912                                        .bottom_0()
 913                                        .right(px(52.))
 914                                        .bg(overlay_gradient)
 915                                        .group_hover("edited-code", |style| {
 916                                            style.bg(overlay_gradient_hover)
 917                                        }),
 918                                )
 919                                .on_click({
 920                                    let buffer = buffer.clone();
 921                                    cx.listener(move |this, _, window, cx| {
 922                                        this.handle_file_click(buffer.clone(), window, cx);
 923                                    })
 924                                });
 925
 926                            Some(element)
 927                        },
 928                    )),
 929                )
 930            })
 931    }
 932
 933    fn render_token_limit_callout(
 934        &self,
 935        line_height: Pixels,
 936        token_usage_ratio: TokenUsageRatio,
 937        cx: &mut Context<Self>,
 938    ) -> Div {
 939        let heading = if token_usage_ratio == TokenUsageRatio::Exceeded {
 940            "Thread reached the token limit"
 941        } else {
 942            "Thread reaching the token limit soon"
 943        };
 944
 945        h_flex()
 946            .p_2()
 947            .gap_2()
 948            .flex_wrap()
 949            .justify_between()
 950            .bg(
 951                if token_usage_ratio == TokenUsageRatio::Exceeded {
 952                    cx.theme().status().error_background.opacity(0.1)
 953                } else {
 954                    cx.theme().status().warning_background.opacity(0.1)
 955                })
 956            .border_t_1()
 957            .border_color(cx.theme().colors().border)
 958            .child(
 959                h_flex()
 960                    .gap_2()
 961                    .items_start()
 962                    .child(
 963                        h_flex()
 964                            .h(line_height)
 965                            .justify_center()
 966                            .child(
 967                                if token_usage_ratio == TokenUsageRatio::Exceeded {
 968                                    Icon::new(IconName::X)
 969                                        .color(Color::Error)
 970                                        .size(IconSize::XSmall)
 971                                } else {
 972                                    Icon::new(IconName::Warning)
 973                                        .color(Color::Warning)
 974                                        .size(IconSize::XSmall)
 975                                }
 976                            ),
 977                    )
 978                    .child(
 979                        v_flex()
 980                            .mr_auto()
 981                            .child(Label::new(heading).size(LabelSize::Small))
 982                            .child(
 983                                Label::new(
 984                                    "Start a new thread from a summary to continue the conversation.",
 985                                )
 986                                .size(LabelSize::Small)
 987                                .color(Color::Muted),
 988                            ),
 989                    ),
 990            )
 991            .child(
 992                Button::new("new-thread", "Start New Thread")
 993                    .on_click(cx.listener(|this, _, window, cx| {
 994                        let from_thread_id = Some(this.thread.read(cx).id().clone());
 995
 996                        window.dispatch_action(Box::new(NewThread {
 997                            from_thread_id
 998                        }), cx);
 999                    }))
1000                    .icon(IconName::Plus)
1001                    .icon_position(IconPosition::Start)
1002                    .icon_size(IconSize::Small)
1003                    .style(ButtonStyle::Tinted(ui::TintColor::Accent))
1004                    .label_size(LabelSize::Small),
1005            )
1006    }
1007
1008    pub fn last_estimated_token_count(&self) -> Option<usize> {
1009        self.last_estimated_token_count
1010    }
1011
1012    pub fn is_waiting_to_update_token_count(&self) -> bool {
1013        self.update_token_count_task.is_some()
1014    }
1015
1016    fn message_or_context_changed(&mut self, debounce: bool, cx: &mut Context<Self>) {
1017        cx.emit(MessageEditorEvent::Changed);
1018        self.update_token_count_task.take();
1019
1020        let Some(default_model) = LanguageModelRegistry::read_global(cx).default_model() else {
1021            self.last_estimated_token_count.take();
1022            return;
1023        };
1024
1025        let context_store = self.context_store.clone();
1026        let editor = self.editor.clone();
1027        let thread = self.thread.clone();
1028
1029        self.update_token_count_task = Some(cx.spawn(async move |this, cx| {
1030            if debounce {
1031                cx.background_executor()
1032                    .timer(Duration::from_millis(200))
1033                    .await;
1034            }
1035
1036            let token_count = if let Some(task) = cx.update(|cx| {
1037                let context = context_store.read(cx).context().iter();
1038                let new_context = thread.read(cx).filter_new_context(context);
1039                let context_text =
1040                    format_context_as_string(new_context, cx).unwrap_or(String::new());
1041                let message_text = editor.read(cx).text(cx);
1042
1043                let content = context_text + &message_text;
1044
1045                if content.is_empty() {
1046                    return None;
1047                }
1048
1049                let request = language_model::LanguageModelRequest {
1050                    thread_id: None,
1051                    prompt_id: None,
1052                    messages: vec![LanguageModelRequestMessage {
1053                        role: language_model::Role::User,
1054                        content: vec![content.into()],
1055                        cache: false,
1056                    }],
1057                    tools: vec![],
1058                    stop: vec![],
1059                    temperature: None,
1060                };
1061
1062                Some(default_model.model.count_tokens(request, cx))
1063            })? {
1064                task.await?
1065            } else {
1066                0
1067            };
1068
1069            this.update(cx, |this, cx| {
1070                this.last_estimated_token_count = Some(token_count);
1071                cx.emit(MessageEditorEvent::EstimatedTokenCount);
1072                this.update_token_count_task.take();
1073            })
1074        }));
1075    }
1076}
1077
1078impl EventEmitter<MessageEditorEvent> for MessageEditor {}
1079
1080pub enum MessageEditorEvent {
1081    EstimatedTokenCount,
1082    Changed,
1083}
1084
1085impl Focusable for MessageEditor {
1086    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
1087        self.editor.focus_handle(cx)
1088    }
1089}
1090
1091impl Render for MessageEditor {
1092    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1093        let thread = self.thread.read(cx);
1094        let total_token_usage = thread.total_token_usage(cx);
1095        let token_usage_ratio = total_token_usage.ratio();
1096
1097        let action_log = self.thread.read(cx).action_log();
1098        let changed_buffers = action_log.read(cx).changed_buffers(cx);
1099
1100        let font_size = TextSize::Small.rems(cx);
1101        let line_height = font_size.to_pixels(window.rem_size()) * 1.5;
1102
1103        v_flex()
1104            .size_full()
1105            .when(self.waiting_for_summaries_to_send, |parent| {
1106                parent.child(
1107                    h_flex().py_3().w_full().justify_center().child(
1108                        h_flex()
1109                            .flex_none()
1110                            .px_2()
1111                            .py_2()
1112                            .bg(cx.theme().colors().editor_background)
1113                            .border_1()
1114                            .border_color(cx.theme().colors().border_variant)
1115                            .rounded_lg()
1116                            .shadow_md()
1117                            .gap_1()
1118                            .child(
1119                                Icon::new(IconName::ArrowCircle)
1120                                    .size(IconSize::XSmall)
1121                                    .color(Color::Muted)
1122                                    .with_animation(
1123                                        "arrow-circle",
1124                                        Animation::new(Duration::from_secs(2)).repeat(),
1125                                        |icon, delta| {
1126                                            icon.transform(gpui::Transformation::rotate(
1127                                                gpui::percentage(delta),
1128                                            ))
1129                                        },
1130                                    ),
1131                            )
1132                            .child(
1133                                Label::new("Summarizing context…")
1134                                    .size(LabelSize::XSmall)
1135                                    .color(Color::Muted),
1136                            ),
1137                    ),
1138                )
1139            })
1140            .when(changed_buffers.len() > 0, |parent| {
1141                parent.child(self.render_changed_buffers(&changed_buffers, window, cx))
1142            })
1143            .child(self.render_editor(font_size, line_height, window, cx))
1144            .when(token_usage_ratio != TokenUsageRatio::Normal, |parent| {
1145                parent.child(self.render_token_limit_callout(line_height, token_usage_ratio, cx))
1146            })
1147    }
1148}