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 needs_confirmation =
345            thread.has_pending_tool_uses() && thread.tools_needing_confirmation().next().is_some();
346
347        let submit_label_color = if is_editor_empty {
348            Color::Muted
349        } else {
350            Color::Default
351        };
352
353        let vim_mode_enabled = VimModeSetting::get_global(cx).0;
354        let platform = PlatformStyle::platform();
355        let linux = platform == PlatformStyle::Linux;
356        let windows = platform == PlatformStyle::Windows;
357        let button_width = if linux || windows || vim_mode_enabled {
358            px(82.)
359        } else {
360            px(64.)
361        };
362
363        let action_log = self.thread.read(cx).action_log();
364        let changed_buffers = action_log.read(cx).changed_buffers(cx);
365        let changed_buffers_count = changed_buffers.len();
366
367        let editor_bg_color = cx.theme().colors().editor_background;
368        let border_color = cx.theme().colors().border;
369        let active_color = cx.theme().colors().element_selected;
370        let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
371
372        v_flex()
373            .size_full()
374            .when(self.waiting_for_summaries_to_send, |parent| {
375                parent.child(
376                    h_flex().py_3().w_full().justify_center().child(
377                        h_flex()
378                            .flex_none()
379                            .px_2()
380                            .py_2()
381                            .bg(editor_bg_color)
382                            .border_1()
383                            .border_color(cx.theme().colors().border_variant)
384                            .rounded_lg()
385                            .shadow_md()
386                            .gap_1()
387                            .child(
388                                Icon::new(IconName::ArrowCircle)
389                                    .size(IconSize::XSmall)
390                                    .color(Color::Muted)
391                                    .with_animation(
392                                        "arrow-circle",
393                                        Animation::new(Duration::from_secs(2)).repeat(),
394                                        |icon, delta| {
395                                            icon.transform(gpui::Transformation::rotate(
396                                                gpui::percentage(delta),
397                                            ))
398                                        },
399                                    ),
400                            )
401                            .child(
402                                Label::new("Summarizing context…")
403                                    .size(LabelSize::XSmall)
404                                    .color(Color::Muted),
405                            ),
406                    ),
407                )
408            })
409            .when(is_generating, |parent| {
410                let focus_handle = self.editor.focus_handle(cx).clone();
411                parent.child(
412                    h_flex().py_3().w_full().justify_center().child(
413                        h_flex()
414                            .flex_none()
415                            .pl_2()
416                            .pr_1()
417                            .py_1()
418                            .bg(editor_bg_color)
419                            .border_1()
420                            .border_color(cx.theme().colors().border_variant)
421                            .rounded_lg()
422                            .shadow_md()
423                            .gap_1()
424                            .child(
425                                Icon::new(IconName::ArrowCircle)
426                                    .size(IconSize::XSmall)
427                                    .color(Color::Muted)
428                                    .with_animation(
429                                        "arrow-circle",
430                                        Animation::new(Duration::from_secs(2)).repeat(),
431                                        |icon, delta| {
432                                            icon.transform(gpui::Transformation::rotate(
433                                                gpui::percentage(delta),
434                                            ))
435                                        },
436                                    ),
437                            )
438                            .child({
439
440
441                                Label::new(if needs_confirmation {
442                                    "Waiting for confirmation…"
443                                } else {
444                                    "Generating…"
445                                })
446                                .size(LabelSize::XSmall)
447                                .color(Color::Muted)
448                            })
449                            .child(ui::Divider::vertical())
450                            .child(
451                                Button::new("cancel-generation", "Cancel")
452                                    .label_size(LabelSize::XSmall)
453                                    .key_binding(
454                                        KeyBinding::for_action_in(
455                                            &editor::actions::Cancel,
456                                            &focus_handle,
457                                            window,
458                                            cx,
459                                        )
460                                        .map(|kb| kb.size(rems_from_px(10.))),
461                                    )
462                                    .on_click(move |_event, window, cx| {
463                                        focus_handle.dispatch_action(
464                                            &editor::actions::Cancel,
465                                            window,
466                                            cx,
467                                        );
468                                    }),
469                            ),
470                    ),
471                )
472            })
473            .when(changed_buffers_count > 0, |parent| {
474                parent.child(
475                    v_flex()
476                        .mx_2()
477                        .bg(bg_edit_files_disclosure)
478                        .border_1()
479                        .border_b_0()
480                        .border_color(border_color)
481                        .rounded_t_md()
482                        .shadow(smallvec::smallvec![gpui::BoxShadow {
483                            color: gpui::black().opacity(0.15),
484                            offset: point(px(1.), px(-1.)),
485                            blur_radius: px(3.),
486                            spread_radius: px(0.),
487                        }])
488                        .child(
489                            h_flex()
490                                .p_1p5()
491                                .justify_between()
492                                .when(self.edits_expanded, |this| {
493                                    this.border_b_1().border_color(border_color)
494                                })
495                                .child(
496                                    h_flex()
497                                        .gap_1()
498                                        .child(
499                                            Disclosure::new(
500                                                "edits-disclosure",
501                                                self.edits_expanded,
502                                            )
503                                            .on_click(
504                                                cx.listener(|this, _ev, _window, cx| {
505                                                    this.edits_expanded = !this.edits_expanded;
506                                                    cx.notify();
507                                                }),
508                                            ),
509                                        )
510                                        .child(
511                                            Label::new("Edits")
512                                                .size(LabelSize::Small)
513                                                .color(Color::Muted),
514                                        )
515                                        .child(
516                                            Label::new("")
517                                                .size(LabelSize::XSmall)
518                                                .color(Color::Muted),
519                                        )
520                                        .child(
521                                            Label::new(format!(
522                                                "{} {}",
523                                                changed_buffers_count,
524                                                if changed_buffers_count == 1 {
525                                                    "file"
526                                                } else {
527                                                    "files"
528                                                }
529                                            ))
530                                            .size(LabelSize::Small)
531                                            .color(Color::Muted),
532                                        ),
533                                )
534                                .child(
535                                    Button::new("review", "Review Changes")
536                                        .label_size(LabelSize::Small)
537                                        .key_binding(
538                                            KeyBinding::for_action_in(
539                                                &OpenAgentDiff,
540                                                &focus_handle,
541                                                window,
542                                                cx,
543                                            )
544                                            .map(|kb| kb.size(rems_from_px(12.))),
545                                        )
546                                        .on_click(cx.listener(|this, _, window, cx| {
547                                            this.handle_review_click(window, cx)
548                                        })),
549                                ),
550                        )
551                        .when(self.edits_expanded, |parent| {
552                            parent.child(
553                                v_flex().bg(cx.theme().colors().editor_background).children(
554                                    changed_buffers.into_iter().enumerate().flat_map(
555                                        |(index, (buffer, _diff))| {
556                                            let file = buffer.read(cx).file()?;
557                                            let path = file.path();
558
559                                            let parent_label = path.parent().and_then(|parent| {
560                                                let parent_str = parent.to_string_lossy();
561
562                                                if parent_str.is_empty() {
563                                                    None
564                                                } else {
565                                                    Some(
566                                                        Label::new(format!(
567                                                            "{}{}",
568                                                            parent_str,
569                                                            std::path::MAIN_SEPARATOR_STR
570                                                        ))
571                                                        .color(Color::Muted)
572                                                        .size(LabelSize::XSmall)
573                                                        .buffer_font(cx),
574                                                    )
575                                                }
576                                            });
577
578                                            let name_label = path.file_name().map(|name| {
579                                                Label::new(name.to_string_lossy().to_string())
580                                                    .size(LabelSize::XSmall)
581                                                    .buffer_font(cx)
582                                            });
583
584                                            let file_icon = FileIcons::get_icon(&path, cx)
585                                                .map(Icon::from_path)
586                                                .map(|icon| {
587                                                    icon.color(Color::Muted).size(IconSize::Small)
588                                                })
589                                                .unwrap_or_else(|| {
590                                                    Icon::new(IconName::File)
591                                                        .color(Color::Muted)
592                                                        .size(IconSize::Small)
593                                                });
594
595                                            let element = div()
596                                                .relative()
597                                                .py_1()
598                                                .px_2()
599                                                .when(index + 1 < changed_buffers_count, |parent| {
600                                                    parent.border_color(border_color).border_b_1()
601                                                })
602                                                .child(
603                                                    h_flex()
604                                                        .gap_2()
605                                                        .justify_between()
606                                                        .child(
607                                                            h_flex()
608                                                                .id("file-container")
609                                                                .pr_8()
610                                                                .gap_1p5()
611                                                                .max_w_full()
612                                                                .overflow_x_scroll()
613                                                                .child(file_icon)
614                                                                .child(
615                                                                    h_flex()
616                                                                        .children(parent_label)
617                                                                        .children(name_label),
618                                                                ) // TODO: show lines changed
619                                                                .child(
620                                                                    Label::new("+")
621                                                                        .color(Color::Created),
622                                                                )
623                                                                .child(
624                                                                    Label::new("-")
625                                                                        .color(Color::Deleted),
626                                                                ),
627                                                        )
628                                                        .child(
629                                                            div()
630                                                                .h_full()
631                                                                .absolute()
632                                                                .w_8()
633                                                                .bottom_0()
634                                                                .right_0()
635                                                                .bg(linear_gradient(
636                                                                    90.,
637                                                                    linear_color_stop(
638                                                                        editor_bg_color,
639                                                                        1.,
640                                                                    ),
641                                                                    linear_color_stop(
642                                                                        editor_bg_color
643                                                                            .opacity(0.2),
644                                                                        0.,
645                                                                    ),
646                                                                )),
647                                                        ),
648                                                );
649
650                                            Some(element)
651                                        },
652                                    ),
653                                ),
654                            )
655                        }),
656                )
657            })
658            .child(
659                v_flex()
660                    .key_context("MessageEditor")
661                    .on_action(cx.listener(Self::chat))
662                    .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
663                        this.profile_selector
664                            .read(cx)
665                            .menu_handle()
666                            .toggle(window, cx);
667                    }))
668                    .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
669                        this.model_selector
670                            .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
671                    }))
672                    .on_action(cx.listener(Self::toggle_context_picker))
673                    .on_action(cx.listener(Self::remove_all_context))
674                    .on_action(cx.listener(Self::move_up))
675                    .on_action(cx.listener(Self::toggle_chat_mode))
676                    .gap_2()
677                    .p_2()
678                    .bg(editor_bg_color)
679                    .border_t_1()
680                    .border_color(cx.theme().colors().border)
681                    .child(h_flex().justify_between().child(self.context_strip.clone()))
682                    .child(
683                        v_flex()
684                            .gap_5()
685                            .child({
686                                    let settings = ThemeSettings::get_global(cx);
687                                    let text_style = TextStyle {
688                                        color: cx.theme().colors().text,
689                                        font_family: settings.ui_font.family.clone(),
690                                        font_fallbacks: settings.ui_font.fallbacks.clone(),
691                                        font_features: settings.ui_font.features.clone(),
692                                        font_size: font_size.into(),
693                                        font_weight: settings.ui_font.weight,
694                                        line_height: line_height.into(),
695                                        ..Default::default()
696                                    };
697
698                                    EditorElement::new(
699                                        &self.editor,
700                                        EditorStyle {
701                                            background: editor_bg_color,
702                                            local_player: cx.theme().players().local(),
703                                            text: text_style,
704                                            syntax: cx.theme().syntax().clone(),
705                                            ..Default::default()
706                                        },
707                                    ).into_any()
708
709                            })
710                            .child(
711                                PopoverMenu::new("inline-context-picker")
712                                    .menu(move |window, cx| {
713                                        inline_context_picker.update(cx, |this, cx| {
714                                            this.init(window, cx);
715                                        });
716
717                                        Some(inline_context_picker.clone())
718                                    })
719                                    .attach(gpui::Corner::TopLeft)
720                                    .anchor(gpui::Corner::BottomLeft)
721                                    .offset(gpui::Point {
722                                        x: px(0.0),
723                                        y: (-ThemeSettings::get_global(cx).ui_font_size(cx) * 2)
724                                            - px(4.0),
725                                    })
726                                    .with_handle(self.inline_context_picker_menu_handle.clone()),
727                            )
728                            .child(
729                                h_flex()
730                                    .justify_between()
731                                    .child(h_flex().gap_2().child(self.profile_selector.clone()))
732                                    .child(
733                                        h_flex().gap_1().child(self.model_selector.clone()).child(
734                                            ButtonLike::new("submit-message")
735                                                .width(button_width.into())
736                                                .style(ButtonStyle::Filled)
737                                                .disabled(
738                                                    is_editor_empty
739                                                        || !is_model_selected
740                                                        || is_generating
741                                                        || self.waiting_for_summaries_to_send
742                                                )
743                                                .child(
744                                                    h_flex()
745                                                        .w_full()
746                                                        .justify_between()
747                                                        .child(
748                                                            Label::new("Submit")
749                                                                .size(LabelSize::Small)
750                                                                .color(submit_label_color),
751                                                        )
752                                                        .children(
753                                                            KeyBinding::for_action_in(
754                                                                &Chat,
755                                                                &focus_handle,
756                                                                window,
757                                                                cx,
758                                                            )
759                                                            .map(|binding| {
760                                                                binding
761                                                                    .when(vim_mode_enabled, |kb| {
762                                                                        kb.size(rems_from_px(12.))
763                                                                    })
764                                                                    .into_any_element()
765                                                            }),
766                                                        ),
767                                                )
768                                                .on_click(move |_event, window, cx| {
769                                                    focus_handle.dispatch_action(&Chat, window, cx);
770                                                })
771                                                .when(is_editor_empty, |button| {
772                                                    button.tooltip(Tooltip::text(
773                                                        "Type a message to submit",
774                                                    ))
775                                                })
776                                                .when(is_generating, |button| {
777                                                    button.tooltip(Tooltip::text(
778                                                        "Cancel to submit a new message",
779                                                    ))
780                                                })
781                                                .when(!is_model_selected, |button| {
782                                                    button.tooltip(Tooltip::text(
783                                                        "Select a model to continue",
784                                                    ))
785                                                }),
786                                        ),
787                                    ),
788                            ),
789                    )
790            )
791            .when(is_too_long, |parent| {
792                parent.child(
793                    h_flex()
794                        .p_2()
795                        .gap_2()
796                        .flex_wrap()
797                        .justify_between()
798                        .bg(cx.theme().status().warning_background.opacity(0.1))
799                        .border_t_1()
800                        .border_color(cx.theme().colors().border)
801                        .child(
802                            h_flex()
803                                .gap_2()
804                                .items_start()
805                                .child(
806                                    h_flex()
807                                        .h(line_height)
808                                        .justify_center()
809                                        .child(
810                                            Icon::new(IconName::Warning)
811                                                .color(Color::Warning)
812                                                .size(IconSize::XSmall),
813                                        ),
814                                )
815                                .child(
816                                    v_flex()
817                                        .mr_auto()
818                                        .child(Label::new("Thread reaching the token limit soon").size(LabelSize::Small))
819                                        .child(
820                                            Label::new(
821                                                "Start a new thread from a summary to continue the conversation.",
822                                            )
823                                            .size(LabelSize::Small)
824                                            .color(Color::Muted),
825                                        ),
826                                ),
827                        )
828                        .child(
829                            Button::new("new-thread", "Start New Thread")
830                                .on_click(cx.listener(|this, _, window, cx| {
831                                    let from_thread_id = Some(this.thread.read(cx).id().clone());
832
833                                    window.dispatch_action(Box::new(NewThread {
834                                        from_thread_id
835                                    }), cx);
836                                }))
837                                .icon(IconName::Plus)
838                                .icon_position(IconPosition::Start)
839                                .icon_size(IconSize::Small)
840                                .style(ButtonStyle::Tinted(ui::TintColor::Accent))
841                                .label_size(LabelSize::Small),
842                        ),
843                )
844            })
845    }
846}