message_editor.rs

  1use std::sync::Arc;
  2
  3use crate::assistant_model_selector::ModelType;
  4use collections::HashSet;
  5use editor::actions::MoveUp;
  6use editor::{ContextMenuOptions, ContextMenuPlacement, Editor, EditorElement, EditorStyle};
  7use file_icons::FileIcons;
  8use fs::Fs;
  9use gpui::{
 10    Animation, AnimationExt, App, DismissEvent, Entity, Focusable, Subscription, TextStyle,
 11    WeakEntity, linear_color_stop, linear_gradient, point, pulsating_between,
 12};
 13use language::Buffer;
 14use language_model::{ConfiguredModel, LanguageModelRegistry};
 15use language_model_selector::ToggleModelSelector;
 16use multi_buffer;
 17use project::Project;
 18use settings::Settings;
 19use std::time::Duration;
 20use theme::ThemeSettings;
 21use ui::{Disclosure, KeyBinding, PopoverMenu, PopoverMenuHandle, Tooltip, prelude::*};
 22use util::ResultExt as _;
 23use workspace::Workspace;
 24
 25use crate::assistant_model_selector::AssistantModelSelector;
 26use crate::context_picker::{ConfirmBehavior, ContextPicker, ContextPickerCompletionProvider};
 27use crate::context_store::{ContextStore, refresh_context_store_text};
 28use crate::context_strip::{ContextStrip, ContextStripEvent, SuggestContextKind};
 29use crate::profile_selector::ProfileSelector;
 30use crate::thread::{RequestKind, Thread, TokenUsageRatio};
 31use crate::thread_store::ThreadStore;
 32use crate::{
 33    AgentDiff, Chat, ChatMode, NewThread, OpenAgentDiff, RemoveAllContext, ThreadEvent,
 34    ToggleContextPicker, ToggleProfileSelector,
 35};
 36
 37pub struct MessageEditor {
 38    thread: Entity<Thread>,
 39    editor: Entity<Editor>,
 40    #[allow(dead_code)]
 41    workspace: WeakEntity<Workspace>,
 42    project: Entity<Project>,
 43    context_store: Entity<ContextStore>,
 44    context_strip: Entity<ContextStrip>,
 45    context_picker_menu_handle: PopoverMenuHandle<ContextPicker>,
 46    inline_context_picker: Entity<ContextPicker>,
 47    inline_context_picker_menu_handle: PopoverMenuHandle<ContextPicker>,
 48    model_selector: Entity<AssistantModelSelector>,
 49    profile_selector: Entity<ProfileSelector>,
 50    edits_expanded: bool,
 51    waiting_for_summaries_to_send: bool,
 52    _subscriptions: Vec<Subscription>,
 53}
 54
 55impl MessageEditor {
 56    pub fn new(
 57        fs: Arc<dyn Fs>,
 58        workspace: WeakEntity<Workspace>,
 59        context_store: Entity<ContextStore>,
 60        thread_store: WeakEntity<ThreadStore>,
 61        thread: Entity<Thread>,
 62        window: &mut Window,
 63        cx: &mut Context<Self>,
 64    ) -> Self {
 65        let context_picker_menu_handle = PopoverMenuHandle::default();
 66        let inline_context_picker_menu_handle = PopoverMenuHandle::default();
 67        let model_selector_menu_handle = PopoverMenuHandle::default();
 68
 69        let editor = cx.new(|cx| {
 70            let mut editor = Editor::auto_height(10, window, cx);
 71            editor.set_placeholder_text("Ask anything, @ to mention, ↑ to select", cx);
 72            editor.set_show_indent_guides(false, cx);
 73            editor.set_context_menu_options(ContextMenuOptions {
 74                min_entries_visible: 12,
 75                max_entries_visible: 12,
 76                placement: Some(ContextMenuPlacement::Above),
 77            });
 78
 79            editor
 80        });
 81
 82        let editor_entity = editor.downgrade();
 83        editor.update(cx, |editor, _| {
 84            editor.set_completion_provider(Some(Box::new(ContextPickerCompletionProvider::new(
 85                workspace.clone(),
 86                context_store.downgrade(),
 87                Some(thread_store.clone()),
 88                editor_entity,
 89            ))));
 90        });
 91
 92        let inline_context_picker = cx.new(|cx| {
 93            ContextPicker::new(
 94                workspace.clone(),
 95                Some(thread_store.clone()),
 96                context_store.downgrade(),
 97                ConfirmBehavior::Close,
 98                window,
 99                cx,
100            )
101        });
102
103        let context_strip = cx.new(|cx| {
104            ContextStrip::new(
105                context_store.clone(),
106                workspace.clone(),
107                Some(thread_store.clone()),
108                context_picker_menu_handle.clone(),
109                SuggestContextKind::File,
110                window,
111                cx,
112            )
113        });
114
115        let subscriptions = vec![
116            cx.subscribe_in(
117                &inline_context_picker,
118                window,
119                Self::handle_inline_context_picker_event,
120            ),
121            cx.subscribe_in(&context_strip, window, Self::handle_context_strip_event),
122        ];
123
124        Self {
125            editor: editor.clone(),
126            project: thread.read(cx).project().clone(),
127            thread,
128            workspace,
129            context_store,
130            context_strip,
131            context_picker_menu_handle,
132            inline_context_picker,
133            inline_context_picker_menu_handle,
134            model_selector: cx.new(|cx| {
135                AssistantModelSelector::new(
136                    fs.clone(),
137                    model_selector_menu_handle,
138                    editor.focus_handle(cx),
139                    ModelType::Default,
140                    window,
141                    cx,
142                )
143            }),
144            edits_expanded: false,
145            waiting_for_summaries_to_send: false,
146            profile_selector: cx
147                .new(|cx| ProfileSelector::new(fs, thread_store, editor.focus_handle(cx), cx)),
148            _subscriptions: subscriptions,
149        }
150    }
151
152    fn toggle_chat_mode(&mut self, _: &ChatMode, _window: &mut Window, cx: &mut Context<Self>) {
153        cx.notify();
154    }
155
156    fn toggle_context_picker(
157        &mut self,
158        _: &ToggleContextPicker,
159        window: &mut Window,
160        cx: &mut Context<Self>,
161    ) {
162        self.context_picker_menu_handle.toggle(window, cx);
163    }
164    pub fn remove_all_context(
165        &mut self,
166        _: &RemoveAllContext,
167        _window: &mut Window,
168        cx: &mut Context<Self>,
169    ) {
170        self.context_store.update(cx, |store, _cx| store.clear());
171        cx.notify();
172    }
173
174    fn chat(&mut self, _: &Chat, window: &mut Window, cx: &mut Context<Self>) {
175        if self.is_editor_empty(cx) {
176            return;
177        }
178
179        if self.thread.read(cx).is_generating() {
180            return;
181        }
182
183        self.send_to_model(RequestKind::Chat, window, cx);
184    }
185
186    fn is_editor_empty(&self, cx: &App) -> bool {
187        self.editor.read(cx).text(cx).is_empty()
188    }
189
190    fn is_model_selected(&self, cx: &App) -> bool {
191        LanguageModelRegistry::read_global(cx)
192            .default_model()
193            .is_some()
194    }
195
196    fn send_to_model(
197        &mut self,
198        request_kind: RequestKind,
199        window: &mut Window,
200        cx: &mut Context<Self>,
201    ) {
202        let model_registry = LanguageModelRegistry::read_global(cx);
203        let Some(ConfiguredModel { model, provider }) = model_registry.default_model() else {
204            return;
205        };
206
207        if provider.must_accept_terms(cx) {
208            cx.notify();
209            return;
210        }
211
212        let user_message = self.editor.update(cx, |editor, cx| {
213            let text = editor.text(cx);
214            editor.clear(window, cx);
215            text
216        });
217
218        let refresh_task =
219            refresh_context_store_text(self.context_store.clone(), &HashSet::default(), cx);
220
221        let system_prompt_context_task = self.thread.read(cx).load_system_prompt_context(cx);
222
223        let thread = self.thread.clone();
224        let context_store = self.context_store.clone();
225        let checkpoint = self.project.read(cx).git_store().read(cx).checkpoint(cx);
226
227        cx.spawn(async move |this, cx| {
228            let checkpoint = checkpoint.await.ok();
229            refresh_task.await;
230            let (system_prompt_context, load_error) = system_prompt_context_task.await;
231
232            thread
233                .update(cx, |thread, cx| {
234                    thread.set_system_prompt_context(system_prompt_context);
235                    if let Some(load_error) = load_error {
236                        cx.emit(ThreadEvent::ShowError(load_error));
237                    }
238                })
239                .log_err();
240
241            thread
242                .update(cx, |thread, cx| {
243                    let context = context_store.read(cx).context().clone();
244                    thread.insert_user_message(user_message, context, checkpoint, cx);
245                })
246                .log_err();
247
248            if let Some(wait_for_summaries) = context_store
249                .update(cx, |context_store, cx| context_store.wait_for_summaries(cx))
250                .log_err()
251            {
252                this.update(cx, |this, cx| {
253                    this.waiting_for_summaries_to_send = true;
254                    cx.notify();
255                })
256                .log_err();
257
258                wait_for_summaries.await;
259
260                this.update(cx, |this, cx| {
261                    this.waiting_for_summaries_to_send = false;
262                    cx.notify();
263                })
264                .log_err();
265            }
266
267            // Send to model after summaries are done
268            thread
269                .update(cx, |thread, cx| {
270                    thread.send_to_model(model, request_kind, cx);
271                })
272                .log_err();
273        })
274        .detach();
275    }
276
277    fn handle_inline_context_picker_event(
278        &mut self,
279        _inline_context_picker: &Entity<ContextPicker>,
280        _event: &DismissEvent,
281        window: &mut Window,
282        cx: &mut Context<Self>,
283    ) {
284        let editor_focus_handle = self.editor.focus_handle(cx);
285        window.focus(&editor_focus_handle);
286    }
287
288    fn handle_context_strip_event(
289        &mut self,
290        _context_strip: &Entity<ContextStrip>,
291        event: &ContextStripEvent,
292        window: &mut Window,
293        cx: &mut Context<Self>,
294    ) {
295        match event {
296            ContextStripEvent::PickerDismissed
297            | ContextStripEvent::BlurredEmpty
298            | ContextStripEvent::BlurredDown => {
299                let editor_focus_handle = self.editor.focus_handle(cx);
300                window.focus(&editor_focus_handle);
301            }
302            ContextStripEvent::BlurredUp => {}
303        }
304    }
305
306    fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
307        if self.context_picker_menu_handle.is_deployed()
308            || self.inline_context_picker_menu_handle.is_deployed()
309        {
310            cx.propagate();
311        } else {
312            self.context_strip.focus_handle(cx).focus(window);
313        }
314    }
315
316    fn handle_review_click(&self, window: &mut Window, cx: &mut Context<Self>) {
317        AgentDiff::deploy(self.thread.clone(), self.workspace.clone(), window, cx).log_err();
318    }
319
320    fn handle_file_click(
321        &self,
322        buffer: Entity<Buffer>,
323        window: &mut Window,
324        cx: &mut Context<Self>,
325    ) {
326        if let Ok(diff) = AgentDiff::deploy(self.thread.clone(), self.workspace.clone(), window, cx)
327        {
328            let path_key = multi_buffer::PathKey::for_buffer(&buffer, cx);
329            diff.update(cx, |diff, cx| diff.move_to_path(path_key, window, cx));
330        }
331    }
332}
333
334impl Focusable for MessageEditor {
335    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
336        self.editor.focus_handle(cx)
337    }
338}
339
340impl Render for MessageEditor {
341    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
342        let font_size = TextSize::Default.rems(cx);
343        let line_height = font_size.to_pixels(window.rem_size()) * 1.5;
344
345        let focus_handle = self.editor.focus_handle(cx);
346        let inline_context_picker = self.inline_context_picker.clone();
347
348        let thread = self.thread.read(cx);
349        let is_generating = thread.is_generating();
350        let total_token_usage = thread.total_token_usage(cx);
351        let is_model_selected = self.is_model_selected(cx);
352        let is_editor_empty = self.is_editor_empty(cx);
353        let is_edit_changes_expanded = self.edits_expanded;
354
355        let action_log = self.thread.read(cx).action_log();
356        let changed_buffers = action_log.read(cx).changed_buffers(cx);
357        let changed_buffers_count = changed_buffers.len();
358
359        let editor_bg_color = cx.theme().colors().editor_background;
360        let border_color = cx.theme().colors().border;
361        let active_color = cx.theme().colors().element_selected;
362        let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
363
364        v_flex()
365            .size_full()
366            .when(self.waiting_for_summaries_to_send, |parent| {
367                parent.child(
368                    h_flex().py_3().w_full().justify_center().child(
369                        h_flex()
370                            .flex_none()
371                            .px_2()
372                            .py_2()
373                            .bg(editor_bg_color)
374                            .border_1()
375                            .border_color(cx.theme().colors().border_variant)
376                            .rounded_lg()
377                            .shadow_md()
378                            .gap_1()
379                            .child(
380                                Icon::new(IconName::ArrowCircle)
381                                    .size(IconSize::XSmall)
382                                    .color(Color::Muted)
383                                    .with_animation(
384                                        "arrow-circle",
385                                        Animation::new(Duration::from_secs(2)).repeat(),
386                                        |icon, delta| {
387                                            icon.transform(gpui::Transformation::rotate(
388                                                gpui::percentage(delta),
389                                            ))
390                                        },
391                                    ),
392                            )
393                            .child(
394                                Label::new("Summarizing context…")
395                                    .size(LabelSize::XSmall)
396                                    .color(Color::Muted),
397                            ),
398                    ),
399                )
400            })
401            .when(changed_buffers_count > 0, |parent| {
402                parent.child(
403                    v_flex()
404                        .mx_2()
405                        .bg(bg_edit_files_disclosure)
406                        .border_1()
407                        .border_b_0()
408                        .border_color(border_color)
409                        .rounded_t_md()
410                        .shadow(smallvec::smallvec![gpui::BoxShadow {
411                            color: gpui::black().opacity(0.15),
412                            offset: point(px(1.), px(-1.)),
413                            blur_radius: px(3.),
414                            spread_radius: px(0.),
415                        }])
416                        .child(
417                            h_flex()
418                                .id("edits-container")
419                                .cursor_pointer()
420                                .p_1p5()
421                                .justify_between()
422                                .when(is_edit_changes_expanded, |this| {
423                                    this.border_b_1().border_color(border_color)
424                                })
425                                .on_click(cx.listener(|this, _, window, cx| {
426                                    this.handle_review_click(window, cx)
427                                }))
428                                .child(
429                                    h_flex()
430                                        .gap_1()
431                                        .child(
432                                            Disclosure::new(
433                                                "edits-disclosure",
434                                                is_edit_changes_expanded,
435                                            )
436                                            .on_click(
437                                                cx.listener(|this, _ev, _window, cx| {
438                                                    this.edits_expanded = !this.edits_expanded;
439                                                    cx.notify();
440                                                }),
441                                            ),
442                                        )
443                                        .child(
444                                            Label::new("Edits")
445                                                .size(LabelSize::Small)
446                                                .color(Color::Muted),
447                                        )
448                                        .child(
449                                            Label::new("")
450                                                .size(LabelSize::XSmall)
451                                                .color(Color::Muted),
452                                        )
453                                        .child(
454                                            Label::new(format!(
455                                                "{} {}",
456                                                changed_buffers_count,
457                                                if changed_buffers_count == 1 {
458                                                    "file"
459                                                } else {
460                                                    "files"
461                                                }
462                                            ))
463                                            .size(LabelSize::Small)
464                                            .color(Color::Muted),
465                                        ),
466                                )
467                                .child(
468                                    Button::new("review", "Review Changes")
469                                        .label_size(LabelSize::Small)
470                                        .key_binding(
471                                            KeyBinding::for_action_in(
472                                                &OpenAgentDiff,
473                                                &focus_handle,
474                                                window,
475                                                cx,
476                                            )
477                                            .map(|kb| kb.size(rems_from_px(12.))),
478                                        )
479                                        .on_click(cx.listener(|this, _, window, cx| {
480                                            this.handle_review_click(window, cx)
481                                        })),
482                                ),
483                        )
484                        .when(is_edit_changes_expanded, |parent| {
485                            parent.child(
486                                v_flex().children(
487                                    changed_buffers.into_iter().enumerate().flat_map(
488                                        |(index, (buffer, _diff))| {
489                                            let file = buffer.read(cx).file()?;
490                                            let path = file.path();
491
492                                            let parent_label = path.parent().and_then(|parent| {
493                                                let parent_str = parent.to_string_lossy();
494
495                                                if parent_str.is_empty() {
496                                                    None
497                                                } else {
498                                                    Some(
499                                                        Label::new(format!(
500                                                            "/{}{}",
501                                                            parent_str,
502                                                            std::path::MAIN_SEPARATOR_STR
503                                                        ))
504                                                        .color(Color::Muted)
505                                                        .size(LabelSize::XSmall)
506                                                        .buffer_font(cx),
507                                                    )
508                                                }
509                                            });
510
511                                            let name_label = path.file_name().map(|name| {
512                                                Label::new(name.to_string_lossy().to_string())
513                                                    .size(LabelSize::XSmall)
514                                                    .buffer_font(cx)
515                                            });
516
517                                            let file_icon = FileIcons::get_icon(&path, cx)
518                                                .map(Icon::from_path)
519                                                .map(|icon| {
520                                                    icon.color(Color::Muted).size(IconSize::Small)
521                                                })
522                                                .unwrap_or_else(|| {
523                                                    Icon::new(IconName::File)
524                                                        .color(Color::Muted)
525                                                        .size(IconSize::Small)
526                                                });
527
528                                            let hover_color = cx.theme()
529                                                .colors()
530                                                .element_background
531                                                .blend(cx.theme().colors().editor_foreground.opacity(0.025));
532
533                                            let overlay_gradient = linear_gradient(
534                                                90.,
535                                                linear_color_stop(
536                                                    editor_bg_color,
537                                                    1.,
538                                                ),
539                                                linear_color_stop(
540                                                    editor_bg_color
541                                                        .opacity(0.2),
542                                                    0.,
543                                                ),
544                                            );
545
546                                            let overlay_gradient_hover = linear_gradient(
547                                                90.,
548                                                linear_color_stop(
549                                                    hover_color,
550                                                    1.,
551                                                ),
552                                                linear_color_stop(
553                                                    hover_color
554                                                        .opacity(0.2),
555                                                    0.,
556                                                ),
557                                            );
558
559                                            let element = h_flex()
560                                                .group("edited-code")
561                                                .id(("file-container", index))
562                                                .cursor_pointer()
563                                                .relative()
564                                                .py_1()
565                                                .pl_2()
566                                                .pr_1()
567                                                .gap_2()
568                                                .justify_between()
569                                                .bg(cx.theme().colors().editor_background)
570                                                .hover(|style| style.bg(hover_color))
571                                                .when(index + 1 < changed_buffers_count, |parent| {
572                                                    parent.border_color(border_color).border_b_1()
573                                                })
574                                                .child(
575                                                    h_flex()
576                                                        .id("file-name")
577                                                        .pr_8()
578                                                        .gap_1p5()
579                                                        .max_w_full()
580                                                        .overflow_x_scroll()
581                                                        .child(file_icon)
582                                                        .child(
583                                                            h_flex()
584                                                                .gap_0p5()
585                                                                .children(name_label)
586                                                                .children(parent_label)
587                                                        ) // TODO: show lines changed
588                                                        .child(
589                                                            Label::new("+")
590                                                                .color(Color::Created),
591                                                        )
592                                                        .child(
593                                                            Label::new("-")
594                                                                .color(Color::Deleted),
595                                                        ),
596                                                )
597                                                .child(
598                                                    div().visible_on_hover("edited-code").child(
599                                                        Button::new("review", "Review")
600                                                            .label_size(LabelSize::Small)
601                                                            .on_click({
602                                                                let buffer = buffer.clone();
603                                                                cx.listener(move |this, _, window, cx| {
604                                                                    this.handle_file_click(buffer.clone(), window, cx);
605                                                                })
606                                                            })
607                                                    )
608                                                )
609                                                .child(
610                                                    div()
611                                                        .id("gradient-overlay")
612                                                        .absolute()
613                                                        .h_5_6()
614                                                        .w_12()
615                                                        .bottom_0()
616                                                        .right(px(52.))
617                                                        .bg(overlay_gradient)
618                                                        .group_hover("edited-code", |style| style.bg(overlay_gradient_hover))
619                                                    ,
620                                                )
621                                                .on_click({
622                                                    let buffer = buffer.clone();
623                                                    cx.listener(move |this, _, window, cx| {
624                                                        this.handle_file_click(buffer.clone(), window, cx);
625                                                    })
626                                                });
627
628                                            Some(element)
629                                        },
630                                    ),
631                                ),
632                            )
633                        }),
634                )
635            })
636            .child(
637                v_flex()
638                    .key_context("MessageEditor")
639                    .on_action(cx.listener(Self::chat))
640                    .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
641                        this.profile_selector
642                            .read(cx)
643                            .menu_handle()
644                            .toggle(window, cx);
645                    }))
646                    .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
647                        this.model_selector
648                            .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
649                    }))
650                    .on_action(cx.listener(Self::toggle_context_picker))
651                    .on_action(cx.listener(Self::remove_all_context))
652                    .on_action(cx.listener(Self::move_up))
653                    .on_action(cx.listener(Self::toggle_chat_mode))
654                    .gap_2()
655                    .p_2()
656                    .bg(editor_bg_color)
657                    .border_t_1()
658                    .border_color(cx.theme().colors().border)
659                    .child(h_flex().justify_between().child(self.context_strip.clone()))
660                    .child(
661                        v_flex()
662                            .gap_5()
663                            .child({
664                                    let settings = ThemeSettings::get_global(cx);
665                                    let text_style = TextStyle {
666                                        color: cx.theme().colors().text,
667                                        font_family: settings.ui_font.family.clone(),
668                                        font_fallbacks: settings.ui_font.fallbacks.clone(),
669                                        font_features: settings.ui_font.features.clone(),
670                                        font_size: font_size.into(),
671                                        font_weight: settings.ui_font.weight,
672                                        line_height: line_height.into(),
673                                        ..Default::default()
674                                    };
675
676                                    EditorElement::new(
677                                        &self.editor,
678                                        EditorStyle {
679                                            background: editor_bg_color,
680                                            local_player: cx.theme().players().local(),
681                                            text: text_style,
682                                            syntax: cx.theme().syntax().clone(),
683                                            ..Default::default()
684                                        },
685                                    ).into_any()
686                            })
687                            .child(
688                                PopoverMenu::new("inline-context-picker")
689                                    .menu(move |window, cx| {
690                                        inline_context_picker.update(cx, |this, cx| {
691                                            this.init(window, cx);
692                                        });
693                                        Some(inline_context_picker.clone())
694                                    })
695                                    .attach(gpui::Corner::TopLeft)
696                                    .anchor(gpui::Corner::BottomLeft)
697                                    .offset(gpui::Point {
698                                        x: px(0.0),
699                                        y: (-ThemeSettings::get_global(cx).ui_font_size(cx) * 2)
700                                            - px(4.0),
701                                    })
702                                    .with_handle(self.inline_context_picker_menu_handle.clone()),
703                            )
704                            .child(
705                                h_flex()
706                                    .justify_between()
707                                    .child(h_flex().gap_2().child(self.profile_selector.clone()))
708                                    .child(
709                                        h_flex().gap_1().child(self.model_selector.clone())
710                                            .map(|parent| {
711                                                if is_generating {
712                                                    parent.child(
713                                                        IconButton::new("stop-generation", IconName::StopFilled)
714                                                            .icon_color(Color::Error)
715                                                            .style(ButtonStyle::Tinted(ui::TintColor::Error))
716                                                            .tooltip(move |window, cx| {
717                                                                Tooltip::for_action(
718                                                                    "Stop Generation",
719                                                                    &editor::actions::Cancel,
720                                                                    window,
721                                                                    cx,
722                                                                )
723                                                            })
724                                                            .on_click(move |_event, window, cx| {
725                                                                focus_handle.dispatch_action(
726                                                                    &editor::actions::Cancel,
727                                                                    window,
728                                                                    cx,
729                                                                );
730                                                            })
731                                                            .with_animation(
732                                                                "pulsating-label",
733                                                                Animation::new(Duration::from_secs(2))
734                                                                    .repeat()
735                                                                    .with_easing(pulsating_between(0.4, 1.0)),
736                                                                |icon_button, delta| icon_button.alpha(delta),
737                                                            ),
738                                                    )
739                                                } else {
740                                                    parent.child(
741                                                        IconButton::new("send-message", IconName::Send)
742                                                            .icon_color(Color::Accent)
743                                                            .style(ButtonStyle::Filled)
744                                                            .disabled(
745                                                                is_editor_empty
746                                                                    || !is_model_selected
747                                                                    || self.waiting_for_summaries_to_send
748                                                            )
749                                                            .on_click(move |_event, window, cx| {
750                                                                focus_handle.dispatch_action(&Chat, window, cx);
751                                                            })
752                                                            .when(!is_editor_empty && is_model_selected, |button| {
753                                                                button.tooltip(move |window, cx| {
754                                                                    Tooltip::for_action(
755                                                                        "Send",
756                                                                        &Chat,
757                                                                        window,
758                                                                        cx,
759                                                                    )
760                                                                })
761                                                            })
762                                                            .when(is_editor_empty, |button| {
763                                                                button.tooltip(Tooltip::text(
764                                                                    "Type a message to submit",
765                                                                ))
766                                                            })
767                                                            .when(!is_model_selected, |button| {
768                                                                button.tooltip(Tooltip::text(
769                                                                    "Select a model to continue",
770                                                                ))
771                                                            })
772                                                    )
773                                                }
774                                            })
775                                    ),
776                            ),
777                    )
778            )
779            .when(total_token_usage.ratio != TokenUsageRatio::Normal, |parent| {
780                parent.child(
781                    h_flex()
782                        .p_2()
783                        .gap_2()
784                        .flex_wrap()
785                        .justify_between()
786                        .bg(cx.theme().status().warning_background.opacity(0.1))
787                        .border_t_1()
788                        .border_color(cx.theme().colors().border)
789                        .child(
790                            h_flex()
791                                .gap_2()
792                                .items_start()
793                                .child(
794                                    h_flex()
795                                        .h(line_height)
796                                        .justify_center()
797                                        .child(
798                                            Icon::new(IconName::Warning)
799                                                .color(Color::Warning)
800                                                .size(IconSize::XSmall),
801                                        ),
802                                )
803                                .child(
804                                    v_flex()
805                                        .mr_auto()
806                                        .child(Label::new("Thread reaching the token limit soon").size(LabelSize::Small))
807                                        .child(
808                                            Label::new(
809                                                "Start a new thread from a summary to continue the conversation.",
810                                            )
811                                            .size(LabelSize::Small)
812                                            .color(Color::Muted),
813                                        ),
814                                ),
815                        )
816                        .child(
817                            Button::new("new-thread", "Start New Thread")
818                                .on_click(cx.listener(|this, _, window, cx| {
819                                    let from_thread_id = Some(this.thread.read(cx).id().clone());
820
821                                    window.dispatch_action(Box::new(NewThread {
822                                        from_thread_id
823                                    }), cx);
824                                }))
825                                .icon(IconName::Plus)
826                                .icon_position(IconPosition::Start)
827                                .icon_size(IconSize::Small)
828                                .style(ButtonStyle::Tinted(ui::TintColor::Accent))
829                                .label_size(LabelSize::Small),
830                        ),
831                )
832            })
833    }
834}