message_editor.rs

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