message_editor.rs

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