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;
  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, Entity, EventEmitter, Focusable, Subscription, Task, TextStyle,
  18    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
 275        let thread = self.thread.clone();
 276        let context_store = self.context_store.clone();
 277        let git_store = self.project.read(cx).git_store().clone();
 278        let checkpoint = git_store.update(cx, |git_store, cx| git_store.checkpoint(cx));
 279
 280        cx.spawn(async move |this, cx| {
 281            let checkpoint = checkpoint.await.ok();
 282            refresh_task.await;
 283
 284            thread
 285                .update(cx, |thread, cx| {
 286                    let context = context_store.read(cx).context().clone();
 287                    thread.insert_user_message(user_message, context, checkpoint, cx);
 288                })
 289                .log_err();
 290
 291            context_store
 292                .update(cx, |context_store, cx| {
 293                    let excerpt_ids = context_store
 294                        .context()
 295                        .iter()
 296                        .filter(|ctx| matches!(ctx, AssistantContext::Excerpt(_)))
 297                        .map(|ctx| ctx.id())
 298                        .collect::<Vec<_>>();
 299
 300                    for id in excerpt_ids {
 301                        context_store.remove_context(id, cx);
 302                    }
 303                })
 304                .log_err();
 305
 306            if let Some(wait_for_summaries) = context_store
 307                .update(cx, |context_store, cx| context_store.wait_for_summaries(cx))
 308                .log_err()
 309            {
 310                this.update(cx, |this, cx| {
 311                    this.waiting_for_summaries_to_send = true;
 312                    cx.notify();
 313                })
 314                .log_err();
 315
 316                wait_for_summaries.await;
 317
 318                this.update(cx, |this, cx| {
 319                    this.waiting_for_summaries_to_send = false;
 320                    cx.notify();
 321                })
 322                .log_err();
 323            }
 324
 325            // Send to model after summaries are done
 326            thread
 327                .update(cx, |thread, cx| {
 328                    thread.advance_prompt_id();
 329                    thread.send_to_model(model, cx);
 330                })
 331                .log_err();
 332        })
 333        .detach();
 334    }
 335
 336    fn stop_current_and_send_new_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 337        let cancelled = self
 338            .thread
 339            .update(cx, |thread, cx| thread.cancel_last_completion(cx));
 340
 341        if cancelled {
 342            self.set_editor_is_expanded(false, cx);
 343            self.send_to_model(window, cx);
 344        }
 345    }
 346
 347    fn handle_context_strip_event(
 348        &mut self,
 349        _context_strip: &Entity<ContextStrip>,
 350        event: &ContextStripEvent,
 351        window: &mut Window,
 352        cx: &mut Context<Self>,
 353    ) {
 354        match event {
 355            ContextStripEvent::PickerDismissed
 356            | ContextStripEvent::BlurredEmpty
 357            | ContextStripEvent::BlurredDown => {
 358                let editor_focus_handle = self.editor.focus_handle(cx);
 359                window.focus(&editor_focus_handle);
 360            }
 361            ContextStripEvent::BlurredUp => {}
 362        }
 363    }
 364
 365    fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 366        if self.context_picker_menu_handle.is_deployed() {
 367            cx.propagate();
 368        } else {
 369            self.context_strip.focus_handle(cx).focus(window);
 370        }
 371    }
 372
 373    fn handle_review_click(&self, window: &mut Window, cx: &mut Context<Self>) {
 374        AgentDiff::deploy(self.thread.clone(), self.workspace.clone(), window, cx).log_err();
 375    }
 376
 377    fn handle_file_click(
 378        &self,
 379        buffer: Entity<Buffer>,
 380        window: &mut Window,
 381        cx: &mut Context<Self>,
 382    ) {
 383        if let Ok(diff) = AgentDiff::deploy(self.thread.clone(), self.workspace.clone(), window, cx)
 384        {
 385            let path_key = multi_buffer::PathKey::for_buffer(&buffer, cx);
 386            diff.update(cx, |diff, cx| diff.move_to_path(path_key, window, cx));
 387        }
 388    }
 389
 390    fn render_editor(
 391        &self,
 392        font_size: Rems,
 393        line_height: Pixels,
 394        window: &mut Window,
 395        cx: &mut Context<Self>,
 396    ) -> Div {
 397        let thread = self.thread.read(cx);
 398
 399        let editor_bg_color = cx.theme().colors().editor_background;
 400        let is_generating = thread.is_generating();
 401        let focus_handle = self.editor.focus_handle(cx);
 402
 403        let is_model_selected = self.is_model_selected(cx);
 404        let is_editor_empty = self.is_editor_empty(cx);
 405
 406        let model = LanguageModelRegistry::read_global(cx)
 407            .default_model()
 408            .map(|default| default.model.clone());
 409
 410        let incompatible_tools = model
 411            .as_ref()
 412            .map(|model| {
 413                self.incompatible_tools_state.update(cx, |state, cx| {
 414                    state
 415                        .incompatible_tools(model, cx)
 416                        .iter()
 417                        .cloned()
 418                        .collect::<Vec<_>>()
 419                })
 420            })
 421            .unwrap_or_default();
 422
 423        let is_editor_expanded = self.editor_is_expanded;
 424        let expand_icon = if is_editor_expanded {
 425            IconName::Minimize
 426        } else {
 427            IconName::Maximize
 428        };
 429
 430        v_flex()
 431            .key_context("MessageEditor")
 432            .on_action(cx.listener(Self::chat))
 433            .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
 434                this.profile_selector
 435                    .read(cx)
 436                    .menu_handle()
 437                    .toggle(window, cx);
 438            }))
 439            .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
 440                this.model_selector
 441                    .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
 442            }))
 443            .on_action(cx.listener(Self::toggle_context_picker))
 444            .on_action(cx.listener(Self::remove_all_context))
 445            .on_action(cx.listener(Self::move_up))
 446            .on_action(cx.listener(Self::toggle_chat_mode))
 447            .on_action(cx.listener(Self::expand_message_editor))
 448            .gap_2()
 449            .p_2()
 450            .bg(editor_bg_color)
 451            .border_t_1()
 452            .border_color(cx.theme().colors().border)
 453            .child(
 454                h_flex()
 455                    .items_start()
 456                    .justify_between()
 457                    .child(self.context_strip.clone())
 458                    .child(
 459                        IconButton::new("toggle-height", expand_icon)
 460                            .icon_size(IconSize::XSmall)
 461                            .icon_color(Color::Muted)
 462                            .tooltip({
 463                                let focus_handle = focus_handle.clone();
 464                                move |window, cx| {
 465                                    let expand_label = if is_editor_expanded {
 466                                        "Minimize Message Editor".to_string()
 467                                    } else {
 468                                        "Expand Message Editor".to_string()
 469                                    };
 470
 471                                    Tooltip::for_action_in(
 472                                        expand_label,
 473                                        &ExpandMessageEditor,
 474                                        &focus_handle,
 475                                        window,
 476                                        cx,
 477                                    )
 478                                }
 479                            })
 480                            .on_click(cx.listener(|_, _, window, cx| {
 481                                window.dispatch_action(Box::new(ExpandMessageEditor), cx);
 482                            })),
 483                    ),
 484            )
 485            .child(
 486                v_flex()
 487                    .size_full()
 488                    .gap_4()
 489                    .when(is_editor_expanded, |this| {
 490                        this.h(vh(0.8, window)).justify_between()
 491                    })
 492                    .child(
 493                        div()
 494                            .min_h_16()
 495                            .when(is_editor_expanded, |this| this.h_full())
 496                            .child({
 497                                let settings = ThemeSettings::get_global(cx);
 498
 499                                let text_style = TextStyle {
 500                                    color: cx.theme().colors().text,
 501                                    font_family: settings.buffer_font.family.clone(),
 502                                    font_fallbacks: settings.buffer_font.fallbacks.clone(),
 503                                    font_features: settings.buffer_font.features.clone(),
 504                                    font_size: font_size.into(),
 505                                    line_height: line_height.into(),
 506                                    ..Default::default()
 507                                };
 508
 509                                EditorElement::new(
 510                                    &self.editor,
 511                                    EditorStyle {
 512                                        background: editor_bg_color,
 513                                        local_player: cx.theme().players().local(),
 514                                        text: text_style,
 515                                        syntax: cx.theme().syntax().clone(),
 516                                        ..Default::default()
 517                                    },
 518                                )
 519                                .into_any()
 520                            }),
 521                    )
 522                    .child(
 523                        h_flex()
 524                            .flex_none()
 525                            .justify_between()
 526                            .child(h_flex().gap_2().child(self.profile_selector.clone()))
 527                            .child(
 528                                h_flex()
 529                                    .gap_1()
 530                                    .when(!incompatible_tools.is_empty(), |this| {
 531                                        this.child(
 532                                            IconButton::new(
 533                                                "tools-incompatible-warning",
 534                                                IconName::Warning,
 535                                            )
 536                                            .icon_color(Color::Warning)
 537                                            .icon_size(IconSize::Small)
 538                                            .tooltip({
 539                                                move |_, cx| {
 540                                                    cx.new(|_| IncompatibleToolsTooltip {
 541                                                        incompatible_tools: incompatible_tools
 542                                                            .clone(),
 543                                                    })
 544                                                    .into()
 545                                                }
 546                                            }),
 547                                        )
 548                                    })
 549                                    .child(self.model_selector.clone())
 550                                    .map({
 551                                        let focus_handle = focus_handle.clone();
 552                                        move |parent| {
 553                                            if is_generating {
 554                                                parent
 555                                                    .when(is_editor_empty, |parent| {
 556                                                        parent.child(
 557                                                            IconButton::new(
 558                                                                "stop-generation",
 559                                                                IconName::StopFilled,
 560                                                            )
 561                                                            .icon_color(Color::Error)
 562                                                            .style(ButtonStyle::Tinted(
 563                                                                ui::TintColor::Error,
 564                                                            ))
 565                                                            .tooltip(move |window, cx| {
 566                                                                Tooltip::for_action(
 567                                                                    "Stop Generation",
 568                                                                    &editor::actions::Cancel,
 569                                                                    window,
 570                                                                    cx,
 571                                                                )
 572                                                            })
 573                                                            .on_click({
 574                                                                let focus_handle =
 575                                                                    focus_handle.clone();
 576                                                                move |_event, window, cx| {
 577                                                                    focus_handle.dispatch_action(
 578                                                                        &editor::actions::Cancel,
 579                                                                        window,
 580                                                                        cx,
 581                                                                    );
 582                                                                }
 583                                                            })
 584                                                            .with_animation(
 585                                                                "pulsating-label",
 586                                                                Animation::new(
 587                                                                    Duration::from_secs(2),
 588                                                                )
 589                                                                .repeat()
 590                                                                .with_easing(pulsating_between(
 591                                                                    0.4, 1.0,
 592                                                                )),
 593                                                                |icon_button, delta| {
 594                                                                    icon_button.alpha(delta)
 595                                                                },
 596                                                            ),
 597                                                        )
 598                                                    })
 599                                                    .when(!is_editor_empty, |parent| {
 600                                                        parent.child(
 601                                                    IconButton::new("send-message", IconName::Send)
 602                                                        .icon_color(Color::Accent)
 603                                                        .style(ButtonStyle::Filled)
 604                                                        .disabled(
 605                                                            !is_model_selected
 606                                                                || self
 607                                                                    .waiting_for_summaries_to_send,
 608                                                        )
 609                                                        .on_click({
 610                                                            let focus_handle = focus_handle.clone();
 611                                                            move |_event, window, cx| {
 612                                                                focus_handle.dispatch_action(
 613                                                                    &Chat, window, cx,
 614                                                                );
 615                                                            }
 616                                                        })
 617                                                        .tooltip(move |window, cx| {
 618                                                            Tooltip::for_action(
 619                                                                "Stop and Send New Message",
 620                                                                &Chat,
 621                                                                window,
 622                                                                cx,
 623                                                            )
 624                                                        }),
 625                                                )
 626                                                    })
 627                                            } else {
 628                                                parent.child(
 629                                                    IconButton::new("send-message", IconName::Send)
 630                                                        .icon_color(Color::Accent)
 631                                                        .style(ButtonStyle::Filled)
 632                                                        .disabled(
 633                                                            is_editor_empty
 634                                                                || !is_model_selected
 635                                                                || self
 636                                                                    .waiting_for_summaries_to_send,
 637                                                        )
 638                                                        .on_click({
 639                                                            let focus_handle = focus_handle.clone();
 640                                                            move |_event, window, cx| {
 641                                                                focus_handle.dispatch_action(
 642                                                                    &Chat, window, cx,
 643                                                                );
 644                                                            }
 645                                                        })
 646                                                        .when(
 647                                                            !is_editor_empty && is_model_selected,
 648                                                            |button| {
 649                                                                button.tooltip(move |window, cx| {
 650                                                                    Tooltip::for_action(
 651                                                                        "Send", &Chat, window, cx,
 652                                                                    )
 653                                                                })
 654                                                            },
 655                                                        )
 656                                                        .when(is_editor_empty, |button| {
 657                                                            button.tooltip(Tooltip::text(
 658                                                                "Type a message to submit",
 659                                                            ))
 660                                                        })
 661                                                        .when(!is_model_selected, |button| {
 662                                                            button.tooltip(Tooltip::text(
 663                                                                "Select a model to continue",
 664                                                            ))
 665                                                        }),
 666                                                )
 667                                            }
 668                                        }
 669                                    }),
 670                            ),
 671                    ),
 672            )
 673    }
 674
 675    fn render_changed_buffers(
 676        &self,
 677        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
 678        window: &mut Window,
 679        cx: &mut Context<Self>,
 680    ) -> Div {
 681        let focus_handle = self.editor.focus_handle(cx);
 682
 683        let editor_bg_color = cx.theme().colors().editor_background;
 684        let border_color = cx.theme().colors().border;
 685        let active_color = cx.theme().colors().element_selected;
 686        let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
 687        let is_edit_changes_expanded = self.edits_expanded;
 688
 689        v_flex()
 690            .mx_2()
 691            .bg(bg_edit_files_disclosure)
 692            .border_1()
 693            .border_b_0()
 694            .border_color(border_color)
 695            .rounded_t_md()
 696            .shadow(smallvec::smallvec![gpui::BoxShadow {
 697                color: gpui::black().opacity(0.15),
 698                offset: point(px(1.), px(-1.)),
 699                blur_radius: px(3.),
 700                spread_radius: px(0.),
 701            }])
 702            .child(
 703                h_flex()
 704                    .id("edits-container")
 705                    .cursor_pointer()
 706                    .p_1p5()
 707                    .justify_between()
 708                    .when(is_edit_changes_expanded, |this| {
 709                        this.border_b_1().border_color(border_color)
 710                    })
 711                    .on_click(
 712                        cx.listener(|this, _, window, cx| this.handle_review_click(window, cx)),
 713                    )
 714                    .child(
 715                        h_flex()
 716                            .gap_1()
 717                            .child(
 718                                Disclosure::new("edits-disclosure", is_edit_changes_expanded)
 719                                    .on_click(cx.listener(|this, _ev, _window, cx| {
 720                                        this.edits_expanded = !this.edits_expanded;
 721                                        cx.notify();
 722                                    })),
 723                            )
 724                            .child(
 725                                Label::new("Edits")
 726                                    .size(LabelSize::Small)
 727                                    .color(Color::Muted),
 728                            )
 729                            .child(Label::new("").size(LabelSize::XSmall).color(Color::Muted))
 730                            .child(
 731                                Label::new(format!(
 732                                    "{} {}",
 733                                    changed_buffers.len(),
 734                                    if changed_buffers.len() == 1 {
 735                                        "file"
 736                                    } else {
 737                                        "files"
 738                                    }
 739                                ))
 740                                .size(LabelSize::Small)
 741                                .color(Color::Muted),
 742                            ),
 743                    )
 744                    .child(
 745                        Button::new("review", "Review Changes")
 746                            .label_size(LabelSize::Small)
 747                            .key_binding(
 748                                KeyBinding::for_action_in(
 749                                    &OpenAgentDiff,
 750                                    &focus_handle,
 751                                    window,
 752                                    cx,
 753                                )
 754                                .map(|kb| kb.size(rems_from_px(12.))),
 755                            )
 756                            .on_click(cx.listener(|this, _, window, cx| {
 757                                this.handle_review_click(window, cx)
 758                            })),
 759                    ),
 760            )
 761            .when(is_edit_changes_expanded, |parent| {
 762                parent.child(
 763                    v_flex().children(changed_buffers.into_iter().enumerate().flat_map(
 764                        |(index, (buffer, _diff))| {
 765                            let file = buffer.read(cx).file()?;
 766                            let path = file.path();
 767
 768                            let parent_label = path.parent().and_then(|parent| {
 769                                let parent_str = parent.to_string_lossy();
 770
 771                                if parent_str.is_empty() {
 772                                    None
 773                                } else {
 774                                    Some(
 775                                        Label::new(format!(
 776                                            "/{}{}",
 777                                            parent_str,
 778                                            std::path::MAIN_SEPARATOR_STR
 779                                        ))
 780                                        .color(Color::Muted)
 781                                        .size(LabelSize::XSmall)
 782                                        .buffer_font(cx),
 783                                    )
 784                                }
 785                            });
 786
 787                            let name_label = path.file_name().map(|name| {
 788                                Label::new(name.to_string_lossy().to_string())
 789                                    .size(LabelSize::XSmall)
 790                                    .buffer_font(cx)
 791                            });
 792
 793                            let file_icon = FileIcons::get_icon(&path, cx)
 794                                .map(Icon::from_path)
 795                                .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
 796                                .unwrap_or_else(|| {
 797                                    Icon::new(IconName::File)
 798                                        .color(Color::Muted)
 799                                        .size(IconSize::Small)
 800                                });
 801
 802                            let hover_color = cx
 803                                .theme()
 804                                .colors()
 805                                .element_background
 806                                .blend(cx.theme().colors().editor_foreground.opacity(0.025));
 807
 808                            let overlay_gradient = linear_gradient(
 809                                90.,
 810                                linear_color_stop(editor_bg_color, 1.),
 811                                linear_color_stop(editor_bg_color.opacity(0.2), 0.),
 812                            );
 813
 814                            let overlay_gradient_hover = linear_gradient(
 815                                90.,
 816                                linear_color_stop(hover_color, 1.),
 817                                linear_color_stop(hover_color.opacity(0.2), 0.),
 818                            );
 819
 820                            let element = h_flex()
 821                                .group("edited-code")
 822                                .id(("file-container", index))
 823                                .cursor_pointer()
 824                                .relative()
 825                                .py_1()
 826                                .pl_2()
 827                                .pr_1()
 828                                .gap_2()
 829                                .justify_between()
 830                                .bg(cx.theme().colors().editor_background)
 831                                .hover(|style| style.bg(hover_color))
 832                                .when(index + 1 < changed_buffers.len(), |parent| {
 833                                    parent.border_color(border_color).border_b_1()
 834                                })
 835                                .child(
 836                                    h_flex()
 837                                        .id("file-name")
 838                                        .pr_8()
 839                                        .gap_1p5()
 840                                        .max_w_full()
 841                                        .overflow_x_scroll()
 842                                        .child(file_icon)
 843                                        .child(
 844                                            h_flex()
 845                                                .gap_0p5()
 846                                                .children(name_label)
 847                                                .children(parent_label),
 848                                        ) // TODO: show lines changed
 849                                        .child(Label::new("+").color(Color::Created))
 850                                        .child(Label::new("-").color(Color::Deleted)),
 851                                )
 852                                .child(
 853                                    div().visible_on_hover("edited-code").child(
 854                                        Button::new("review", "Review")
 855                                            .label_size(LabelSize::Small)
 856                                            .on_click({
 857                                                let buffer = buffer.clone();
 858                                                cx.listener(move |this, _, window, cx| {
 859                                                    this.handle_file_click(
 860                                                        buffer.clone(),
 861                                                        window,
 862                                                        cx,
 863                                                    );
 864                                                })
 865                                            }),
 866                                    ),
 867                                )
 868                                .child(
 869                                    div()
 870                                        .id("gradient-overlay")
 871                                        .absolute()
 872                                        .h_5_6()
 873                                        .w_12()
 874                                        .bottom_0()
 875                                        .right(px(52.))
 876                                        .bg(overlay_gradient)
 877                                        .group_hover("edited-code", |style| {
 878                                            style.bg(overlay_gradient_hover)
 879                                        }),
 880                                )
 881                                .on_click({
 882                                    let buffer = buffer.clone();
 883                                    cx.listener(move |this, _, window, cx| {
 884                                        this.handle_file_click(buffer.clone(), window, cx);
 885                                    })
 886                                });
 887
 888                            Some(element)
 889                        },
 890                    )),
 891                )
 892            })
 893    }
 894
 895    fn render_token_limit_callout(
 896        &self,
 897        line_height: Pixels,
 898        token_usage_ratio: TokenUsageRatio,
 899        cx: &mut Context<Self>,
 900    ) -> Div {
 901        let heading = if token_usage_ratio == TokenUsageRatio::Exceeded {
 902            "Thread reached the token limit"
 903        } else {
 904            "Thread reaching the token limit soon"
 905        };
 906
 907        h_flex()
 908            .p_2()
 909            .gap_2()
 910            .flex_wrap()
 911            .justify_between()
 912            .bg(
 913                if token_usage_ratio == TokenUsageRatio::Exceeded {
 914                    cx.theme().status().error_background.opacity(0.1)
 915                } else {
 916                    cx.theme().status().warning_background.opacity(0.1)
 917                })
 918            .border_t_1()
 919            .border_color(cx.theme().colors().border)
 920            .child(
 921                h_flex()
 922                    .gap_2()
 923                    .items_start()
 924                    .child(
 925                        h_flex()
 926                            .h(line_height)
 927                            .justify_center()
 928                            .child(
 929                                if token_usage_ratio == TokenUsageRatio::Exceeded {
 930                                    Icon::new(IconName::X)
 931                                        .color(Color::Error)
 932                                        .size(IconSize::XSmall)
 933                                } else {
 934                                    Icon::new(IconName::Warning)
 935                                        .color(Color::Warning)
 936                                        .size(IconSize::XSmall)
 937                                }
 938                            ),
 939                    )
 940                    .child(
 941                        v_flex()
 942                            .mr_auto()
 943                            .child(Label::new(heading).size(LabelSize::Small))
 944                            .child(
 945                                Label::new(
 946                                    "Start a new thread from a summary to continue the conversation.",
 947                                )
 948                                .size(LabelSize::Small)
 949                                .color(Color::Muted),
 950                            ),
 951                    ),
 952            )
 953            .child(
 954                Button::new("new-thread", "Start New Thread")
 955                    .on_click(cx.listener(|this, _, window, cx| {
 956                        let from_thread_id = Some(this.thread.read(cx).id().clone());
 957
 958                        window.dispatch_action(Box::new(NewThread {
 959                            from_thread_id
 960                        }), cx);
 961                    }))
 962                    .icon(IconName::Plus)
 963                    .icon_position(IconPosition::Start)
 964                    .icon_size(IconSize::Small)
 965                    .style(ButtonStyle::Tinted(ui::TintColor::Accent))
 966                    .label_size(LabelSize::Small),
 967            )
 968    }
 969
 970    pub fn last_estimated_token_count(&self) -> Option<usize> {
 971        self.last_estimated_token_count
 972    }
 973
 974    pub fn is_waiting_to_update_token_count(&self) -> bool {
 975        self.update_token_count_task.is_some()
 976    }
 977
 978    fn message_or_context_changed(&mut self, debounce: bool, cx: &mut Context<Self>) {
 979        cx.emit(MessageEditorEvent::Changed);
 980        self.update_token_count_task.take();
 981
 982        let Some(default_model) = LanguageModelRegistry::read_global(cx).default_model() else {
 983            self.last_estimated_token_count.take();
 984            return;
 985        };
 986
 987        let context_store = self.context_store.clone();
 988        let editor = self.editor.clone();
 989        let thread = self.thread.clone();
 990
 991        self.update_token_count_task = Some(cx.spawn(async move |this, cx| {
 992            if debounce {
 993                cx.background_executor()
 994                    .timer(Duration::from_millis(200))
 995                    .await;
 996            }
 997
 998            let token_count = if let Some(task) = cx.update(|cx| {
 999                let context = context_store.read(cx).context().iter();
1000                let new_context = thread.read(cx).filter_new_context(context);
1001                let context_text =
1002                    format_context_as_string(new_context, cx).unwrap_or(String::new());
1003                let message_text = editor.read(cx).text(cx);
1004
1005                let content = context_text + &message_text;
1006
1007                if content.is_empty() {
1008                    return None;
1009                }
1010
1011                let request = language_model::LanguageModelRequest {
1012                    thread_id: None,
1013                    prompt_id: None,
1014                    messages: vec![LanguageModelRequestMessage {
1015                        role: language_model::Role::User,
1016                        content: vec![content.into()],
1017                        cache: false,
1018                    }],
1019                    tools: vec![],
1020                    stop: vec![],
1021                    temperature: None,
1022                };
1023
1024                Some(default_model.model.count_tokens(request, cx))
1025            })? {
1026                task.await?
1027            } else {
1028                0
1029            };
1030
1031            this.update(cx, |this, cx| {
1032                this.last_estimated_token_count = Some(token_count);
1033                cx.emit(MessageEditorEvent::EstimatedTokenCount);
1034                this.update_token_count_task.take();
1035            })
1036        }));
1037    }
1038}
1039
1040impl EventEmitter<MessageEditorEvent> for MessageEditor {}
1041
1042pub enum MessageEditorEvent {
1043    EstimatedTokenCount,
1044    Changed,
1045}
1046
1047impl Focusable for MessageEditor {
1048    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
1049        self.editor.focus_handle(cx)
1050    }
1051}
1052
1053impl Render for MessageEditor {
1054    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1055        let thread = self.thread.read(cx);
1056        let total_token_usage = thread.total_token_usage(cx);
1057        let token_usage_ratio = total_token_usage.ratio();
1058
1059        let action_log = self.thread.read(cx).action_log();
1060        let changed_buffers = action_log.read(cx).changed_buffers(cx);
1061
1062        let font_size = TextSize::Small.rems(cx);
1063        let line_height = font_size.to_pixels(window.rem_size()) * 1.5;
1064
1065        v_flex()
1066            .size_full()
1067            .when(self.waiting_for_summaries_to_send, |parent| {
1068                parent.child(
1069                    h_flex().py_3().w_full().justify_center().child(
1070                        h_flex()
1071                            .flex_none()
1072                            .px_2()
1073                            .py_2()
1074                            .bg(cx.theme().colors().editor_background)
1075                            .border_1()
1076                            .border_color(cx.theme().colors().border_variant)
1077                            .rounded_lg()
1078                            .shadow_md()
1079                            .gap_1()
1080                            .child(
1081                                Icon::new(IconName::ArrowCircle)
1082                                    .size(IconSize::XSmall)
1083                                    .color(Color::Muted)
1084                                    .with_animation(
1085                                        "arrow-circle",
1086                                        Animation::new(Duration::from_secs(2)).repeat(),
1087                                        |icon, delta| {
1088                                            icon.transform(gpui::Transformation::rotate(
1089                                                gpui::percentage(delta),
1090                                            ))
1091                                        },
1092                                    ),
1093                            )
1094                            .child(
1095                                Label::new("Summarizing context…")
1096                                    .size(LabelSize::XSmall)
1097                                    .color(Color::Muted),
1098                            ),
1099                    ),
1100                )
1101            })
1102            .when(changed_buffers.len() > 0, |parent| {
1103                parent.child(self.render_changed_buffers(&changed_buffers, window, cx))
1104            })
1105            .child(self.render_editor(font_size, line_height, window, cx))
1106            .when(token_usage_ratio != TokenUsageRatio::Normal, |parent| {
1107                parent.child(self.render_token_limit_callout(line_height, token_usage_ratio, cx))
1108            })
1109    }
1110}