message_editor.rs

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