message_editor.rs

   1use std::collections::BTreeMap;
   2use std::sync::Arc;
   3
   4use crate::assistant_model_selector::ModelType;
   5use crate::context::{AssistantContext, format_context_as_string};
   6use crate::tool_compatibility::{IncompatibleToolsState, IncompatibleToolsTooltip};
   7use buffer_diff::BufferDiff;
   8use collections::HashSet;
   9use editor::actions::MoveUp;
  10use editor::{
  11    ContextMenuOptions, ContextMenuPlacement, Editor, EditorElement, EditorEvent, EditorMode,
  12    EditorStyle, MultiBuffer,
  13};
  14use file_icons::FileIcons;
  15use fs::Fs;
  16use gpui::{
  17    Animation, AnimationExt, App, Entity, EventEmitter, Focusable, Subscription, Task, TextStyle,
  18    WeakEntity, linear_color_stop, linear_gradient, point, pulsating_between,
  19};
  20use language::{Buffer, Language};
  21use language_model::{ConfiguredModel, LanguageModelRegistry, LanguageModelRequestMessage};
  22use language_model_selector::ToggleModelSelector;
  23use multi_buffer;
  24use project::Project;
  25use settings::Settings;
  26use std::time::Duration;
  27use theme::ThemeSettings;
  28use ui::{Disclosure, KeyBinding, PopoverMenuHandle, Tooltip, prelude::*};
  29use util::ResultExt as _;
  30use workspace::Workspace;
  31
  32use crate::assistant_model_selector::AssistantModelSelector;
  33use crate::context_picker::{ContextPicker, ContextPickerCompletionProvider};
  34use crate::context_store::{ContextStore, refresh_context_store_text};
  35use crate::context_strip::{ContextStrip, ContextStripEvent, SuggestContextKind};
  36use crate::profile_selector::ProfileSelector;
  37use crate::thread::{RequestKind, Thread, TokenUsageRatio};
  38use crate::thread_store::ThreadStore;
  39use crate::{
  40    AgentDiff, Chat, ChatMode, ExpandMessageEditor, NewThread, OpenAgentDiff, RemoveAllContext,
  41    ToggleContextPicker, ToggleProfileSelector,
  42};
  43
  44pub struct MessageEditor {
  45    thread: Entity<Thread>,
  46    incompatible_tools_state: Entity<IncompatibleToolsState>,
  47    editor: Entity<Editor>,
  48    #[allow(dead_code)]
  49    workspace: WeakEntity<Workspace>,
  50    project: Entity<Project>,
  51    context_store: Entity<ContextStore>,
  52    context_strip: Entity<ContextStrip>,
  53    context_picker_menu_handle: PopoverMenuHandle<ContextPicker>,
  54    model_selector: Entity<AssistantModelSelector>,
  55    profile_selector: Entity<ProfileSelector>,
  56    edits_expanded: bool,
  57    editor_is_expanded: bool,
  58    waiting_for_summaries_to_send: bool,
  59    last_estimated_token_count: Option<usize>,
  60    update_token_count_task: Option<Task<anyhow::Result<()>>>,
  61    _subscriptions: Vec<Subscription>,
  62}
  63
  64const MAX_EDITOR_LINES: usize = 8;
  65
  66impl MessageEditor {
  67    pub fn new(
  68        fs: Arc<dyn Fs>,
  69        workspace: WeakEntity<Workspace>,
  70        context_store: Entity<ContextStore>,
  71        thread_store: WeakEntity<ThreadStore>,
  72        thread: Entity<Thread>,
  73        window: &mut Window,
  74        cx: &mut Context<Self>,
  75    ) -> Self {
  76        let context_picker_menu_handle = PopoverMenuHandle::default();
  77        let model_selector_menu_handle = PopoverMenuHandle::default();
  78
  79        let language = Language::new(
  80            language::LanguageConfig {
  81                completion_query_characters: HashSet::from_iter(['.', '-', '_', '@']),
  82                ..Default::default()
  83            },
  84            None,
  85        );
  86
  87        let editor = cx.new(|cx| {
  88            let buffer = cx.new(|cx| Buffer::local("", cx).with_language(Arc::new(language), cx));
  89            let buffer = cx.new(|cx| MultiBuffer::singleton(buffer, cx));
  90            let mut editor = Editor::new(
  91                editor::EditorMode::AutoHeight {
  92                    max_lines: MAX_EDITOR_LINES,
  93                },
  94                buffer,
  95                None,
  96                window,
  97                cx,
  98            );
  99            editor.set_placeholder_text("Ask anything, @ to mention, ↑ to select", cx);
 100            editor.set_show_indent_guides(false, cx);
 101            editor.set_soft_wrap();
 102            editor.set_context_menu_options(ContextMenuOptions {
 103                min_entries_visible: 12,
 104                max_entries_visible: 12,
 105                placement: Some(ContextMenuPlacement::Above),
 106            });
 107            editor
 108        });
 109
 110        let editor_entity = editor.downgrade();
 111        editor.update(cx, |editor, _| {
 112            editor.set_completion_provider(Some(Box::new(ContextPickerCompletionProvider::new(
 113                workspace.clone(),
 114                context_store.downgrade(),
 115                Some(thread_store.clone()),
 116                editor_entity,
 117            ))));
 118        });
 119
 120        let context_strip = cx.new(|cx| {
 121            ContextStrip::new(
 122                context_store.clone(),
 123                workspace.clone(),
 124                Some(thread_store.clone()),
 125                context_picker_menu_handle.clone(),
 126                SuggestContextKind::File,
 127                window,
 128                cx,
 129            )
 130        });
 131
 132        let incompatible_tools =
 133            cx.new(|cx| IncompatibleToolsState::new(thread.read(cx).tools().clone(), cx));
 134
 135        let subscriptions = vec![
 136            cx.subscribe_in(&context_strip, window, Self::handle_context_strip_event),
 137            cx.subscribe(&editor, |this, _, event, cx| match event {
 138                EditorEvent::BufferEdited => {
 139                    this.message_or_context_changed(true, cx);
 140                }
 141                _ => {}
 142            }),
 143            cx.observe(&context_store, |this, _, cx| {
 144                this.message_or_context_changed(false, cx);
 145            }),
 146        ];
 147
 148        Self {
 149            editor: editor.clone(),
 150            project: thread.read(cx).project().clone(),
 151            thread,
 152            incompatible_tools_state: incompatible_tools.clone(),
 153            workspace,
 154            context_store,
 155            context_strip,
 156            context_picker_menu_handle,
 157            model_selector: cx.new(|cx| {
 158                AssistantModelSelector::new(
 159                    fs.clone(),
 160                    model_selector_menu_handle,
 161                    editor.focus_handle(cx),
 162                    ModelType::Default,
 163                    window,
 164                    cx,
 165                )
 166            }),
 167            edits_expanded: false,
 168            editor_is_expanded: false,
 169            waiting_for_summaries_to_send: false,
 170            profile_selector: cx
 171                .new(|cx| ProfileSelector::new(fs, thread_store, editor.focus_handle(cx), cx)),
 172            last_estimated_token_count: None,
 173            update_token_count_task: None,
 174            _subscriptions: subscriptions,
 175        }
 176    }
 177
 178    fn toggle_chat_mode(&mut self, _: &ChatMode, _window: &mut Window, cx: &mut Context<Self>) {
 179        cx.notify();
 180    }
 181
 182    pub fn expand_message_editor(
 183        &mut self,
 184        _: &ExpandMessageEditor,
 185        _window: &mut Window,
 186        cx: &mut Context<Self>,
 187    ) {
 188        self.set_editor_is_expanded(!self.editor_is_expanded, cx);
 189    }
 190
 191    fn set_editor_is_expanded(&mut self, is_expanded: bool, cx: &mut Context<Self>) {
 192        self.editor_is_expanded = is_expanded;
 193        self.editor.update(cx, |editor, _| {
 194            if self.editor_is_expanded {
 195                editor.set_mode(EditorMode::Full {
 196                    scale_ui_elements_with_buffer_font_size: false,
 197                    show_active_line_background: false,
 198                })
 199            } else {
 200                editor.set_mode(EditorMode::AutoHeight {
 201                    max_lines: MAX_EDITOR_LINES,
 202                })
 203            }
 204        });
 205        cx.notify();
 206    }
 207
 208    fn toggle_context_picker(
 209        &mut self,
 210        _: &ToggleContextPicker,
 211        window: &mut Window,
 212        cx: &mut Context<Self>,
 213    ) {
 214        self.context_picker_menu_handle.toggle(window, cx);
 215    }
 216    pub fn remove_all_context(
 217        &mut self,
 218        _: &RemoveAllContext,
 219        _window: &mut Window,
 220        cx: &mut Context<Self>,
 221    ) {
 222        self.context_store.update(cx, |store, _cx| store.clear());
 223        cx.notify();
 224    }
 225
 226    fn chat(&mut self, _: &Chat, window: &mut Window, cx: &mut Context<Self>) {
 227        if self.is_editor_empty(cx) {
 228            return;
 229        }
 230
 231        if self.thread.read(cx).is_generating() {
 232            self.stop_current_and_send_new_message(window, cx);
 233            return;
 234        }
 235
 236        self.set_editor_is_expanded(false, cx);
 237        self.send_to_model(RequestKind::Chat, window, cx);
 238
 239        cx.notify();
 240    }
 241
 242    fn is_editor_empty(&self, cx: &App) -> bool {
 243        self.editor.read(cx).text(cx).trim().is_empty()
 244    }
 245
 246    fn is_model_selected(&self, cx: &App) -> bool {
 247        LanguageModelRegistry::read_global(cx)
 248            .default_model()
 249            .is_some()
 250    }
 251
 252    fn send_to_model(
 253        &mut self,
 254        request_kind: RequestKind,
 255        window: &mut Window,
 256        cx: &mut Context<Self>,
 257    ) {
 258        let model_registry = LanguageModelRegistry::read_global(cx);
 259        let Some(ConfiguredModel { model, provider }) = model_registry.default_model() else {
 260            return;
 261        };
 262
 263        if provider.must_accept_terms(cx) {
 264            cx.notify();
 265            return;
 266        }
 267
 268        let user_message = self.editor.update(cx, |editor, cx| {
 269            let text = editor.text(cx);
 270            editor.clear(window, cx);
 271            text
 272        });
 273
 274        self.last_estimated_token_count.take();
 275        cx.emit(MessageEditorEvent::EstimatedTokenCount);
 276
 277        let refresh_task =
 278            refresh_context_store_text(self.context_store.clone(), &HashSet::default(), cx);
 279
 280        let thread = self.thread.clone();
 281        let context_store = self.context_store.clone();
 282        let git_store = self.project.read(cx).git_store().clone();
 283        let checkpoint = git_store.update(cx, |git_store, cx| git_store.checkpoint(cx));
 284
 285        cx.spawn(async move |this, cx| {
 286            let checkpoint = checkpoint.await.ok();
 287            refresh_task.await;
 288
 289            thread
 290                .update(cx, |thread, cx| {
 291                    let context = context_store.read(cx).context().clone();
 292                    thread.insert_user_message(user_message, context, checkpoint, cx);
 293                })
 294                .log_err();
 295
 296            context_store
 297                .update(cx, |context_store, cx| {
 298                    let excerpt_ids = context_store
 299                        .context()
 300                        .iter()
 301                        .filter(|ctx| matches!(ctx, AssistantContext::Excerpt(_)))
 302                        .map(|ctx| ctx.id())
 303                        .collect::<Vec<_>>();
 304
 305                    for id in excerpt_ids {
 306                        context_store.remove_context(id, cx);
 307                    }
 308                })
 309                .log_err();
 310
 311            if let Some(wait_for_summaries) = context_store
 312                .update(cx, |context_store, cx| context_store.wait_for_summaries(cx))
 313                .log_err()
 314            {
 315                this.update(cx, |this, cx| {
 316                    this.waiting_for_summaries_to_send = true;
 317                    cx.notify();
 318                })
 319                .log_err();
 320
 321                wait_for_summaries.await;
 322
 323                this.update(cx, |this, cx| {
 324                    this.waiting_for_summaries_to_send = false;
 325                    cx.notify();
 326                })
 327                .log_err();
 328            }
 329
 330            // Send to model after summaries are done
 331            thread
 332                .update(cx, |thread, cx| {
 333                    thread.advance_prompt_id();
 334                    thread.send_to_model(model, request_kind, cx);
 335                })
 336                .log_err();
 337        })
 338        .detach();
 339    }
 340
 341    fn stop_current_and_send_new_message(&mut self, window: &mut Window, cx: &mut Context<Self>) {
 342        let cancelled = self
 343            .thread
 344            .update(cx, |thread, cx| thread.cancel_last_completion(cx));
 345
 346        if cancelled {
 347            self.set_editor_is_expanded(false, cx);
 348            self.send_to_model(RequestKind::Chat, window, cx);
 349        }
 350    }
 351
 352    fn handle_context_strip_event(
 353        &mut self,
 354        _context_strip: &Entity<ContextStrip>,
 355        event: &ContextStripEvent,
 356        window: &mut Window,
 357        cx: &mut Context<Self>,
 358    ) {
 359        match event {
 360            ContextStripEvent::PickerDismissed
 361            | ContextStripEvent::BlurredEmpty
 362            | ContextStripEvent::BlurredDown => {
 363                let editor_focus_handle = self.editor.focus_handle(cx);
 364                window.focus(&editor_focus_handle);
 365            }
 366            ContextStripEvent::BlurredUp => {}
 367        }
 368    }
 369
 370    fn move_up(&mut self, _: &MoveUp, window: &mut Window, cx: &mut Context<Self>) {
 371        if self.context_picker_menu_handle.is_deployed() {
 372            cx.propagate();
 373        } else {
 374            self.context_strip.focus_handle(cx).focus(window);
 375        }
 376    }
 377
 378    fn handle_review_click(&self, window: &mut Window, cx: &mut Context<Self>) {
 379        AgentDiff::deploy(self.thread.clone(), self.workspace.clone(), window, cx).log_err();
 380    }
 381
 382    fn handle_file_click(
 383        &self,
 384        buffer: Entity<Buffer>,
 385        window: &mut Window,
 386        cx: &mut Context<Self>,
 387    ) {
 388        if let Ok(diff) = AgentDiff::deploy(self.thread.clone(), self.workspace.clone(), window, cx)
 389        {
 390            let path_key = multi_buffer::PathKey::for_buffer(&buffer, cx);
 391            diff.update(cx, |diff, cx| diff.move_to_path(path_key, window, cx));
 392        }
 393    }
 394
 395    fn render_editor(
 396        &self,
 397        font_size: Rems,
 398        line_height: Pixels,
 399        window: &mut Window,
 400        cx: &mut Context<Self>,
 401    ) -> Div {
 402        let thread = self.thread.read(cx);
 403
 404        let editor_bg_color = cx.theme().colors().editor_background;
 405        let is_generating = thread.is_generating();
 406        let focus_handle = self.editor.focus_handle(cx);
 407
 408        let is_model_selected = self.is_model_selected(cx);
 409        let is_editor_empty = self.is_editor_empty(cx);
 410
 411        let model = LanguageModelRegistry::read_global(cx)
 412            .default_model()
 413            .map(|default| default.model.clone());
 414
 415        let incompatible_tools = model
 416            .as_ref()
 417            .map(|model| {
 418                self.incompatible_tools_state.update(cx, |state, cx| {
 419                    state
 420                        .incompatible_tools(model, cx)
 421                        .iter()
 422                        .cloned()
 423                        .collect::<Vec<_>>()
 424                })
 425            })
 426            .unwrap_or_default();
 427
 428        let is_editor_expanded = self.editor_is_expanded;
 429        let expand_icon = if is_editor_expanded {
 430            IconName::Minimize
 431        } else {
 432            IconName::Maximize
 433        };
 434
 435        v_flex()
 436            .key_context("MessageEditor")
 437            .on_action(cx.listener(Self::chat))
 438            .on_action(cx.listener(|this, _: &ToggleProfileSelector, window, cx| {
 439                this.profile_selector
 440                    .read(cx)
 441                    .menu_handle()
 442                    .toggle(window, cx);
 443            }))
 444            .on_action(cx.listener(|this, _: &ToggleModelSelector, window, cx| {
 445                this.model_selector
 446                    .update(cx, |model_selector, cx| model_selector.toggle(window, cx));
 447            }))
 448            .on_action(cx.listener(Self::toggle_context_picker))
 449            .on_action(cx.listener(Self::remove_all_context))
 450            .on_action(cx.listener(Self::move_up))
 451            .on_action(cx.listener(Self::toggle_chat_mode))
 452            .on_action(cx.listener(Self::expand_message_editor))
 453            .gap_2()
 454            .p_2()
 455            .bg(editor_bg_color)
 456            .border_t_1()
 457            .border_color(cx.theme().colors().border)
 458            .child(
 459                h_flex()
 460                    .items_start()
 461                    .justify_between()
 462                    .child(self.context_strip.clone())
 463                    .child(
 464                        IconButton::new("toggle-height", expand_icon)
 465                            .icon_size(IconSize::XSmall)
 466                            .icon_color(Color::Muted)
 467                            .tooltip({
 468                                let focus_handle = focus_handle.clone();
 469                                move |window, cx| {
 470                                    let expand_label = if is_editor_expanded {
 471                                        "Minimize Message Editor".to_string()
 472                                    } else {
 473                                        "Expand Message Editor".to_string()
 474                                    };
 475
 476                                    Tooltip::for_action_in(
 477                                        expand_label,
 478                                        &ExpandMessageEditor,
 479                                        &focus_handle,
 480                                        window,
 481                                        cx,
 482                                    )
 483                                }
 484                            })
 485                            .on_click(cx.listener(|_, _, window, cx| {
 486                                window.dispatch_action(Box::new(ExpandMessageEditor), cx);
 487                            })),
 488                    ),
 489            )
 490            .child(
 491                v_flex()
 492                    .size_full()
 493                    .gap_4()
 494                    .when(is_editor_expanded, |this| {
 495                        this.h(vh(0.8, window)).justify_between()
 496                    })
 497                    .child(
 498                        div()
 499                            .min_h_16()
 500                            .when(is_editor_expanded, |this| this.h_full())
 501                            .child({
 502                                let settings = ThemeSettings::get_global(cx);
 503
 504                                let text_style = TextStyle {
 505                                    color: cx.theme().colors().text,
 506                                    font_family: settings.buffer_font.family.clone(),
 507                                    font_fallbacks: settings.buffer_font.fallbacks.clone(),
 508                                    font_features: settings.buffer_font.features.clone(),
 509                                    font_size: font_size.into(),
 510                                    line_height: line_height.into(),
 511                                    ..Default::default()
 512                                };
 513
 514                                EditorElement::new(
 515                                    &self.editor,
 516                                    EditorStyle {
 517                                        background: editor_bg_color,
 518                                        local_player: cx.theme().players().local(),
 519                                        text: text_style,
 520                                        syntax: cx.theme().syntax().clone(),
 521                                        ..Default::default()
 522                                    },
 523                                )
 524                                .into_any()
 525                            }),
 526                    )
 527                    .child(
 528                        h_flex()
 529                            .flex_none()
 530                            .justify_between()
 531                            .child(h_flex().gap_2().child(self.profile_selector.clone()))
 532                            .child(
 533                                h_flex()
 534                                    .gap_1()
 535                                    .when(!incompatible_tools.is_empty(), |this| {
 536                                        this.child(
 537                                            IconButton::new(
 538                                                "tools-incompatible-warning",
 539                                                IconName::Warning,
 540                                            )
 541                                            .icon_color(Color::Warning)
 542                                            .icon_size(IconSize::Small)
 543                                            .tooltip({
 544                                                move |_, cx| {
 545                                                    cx.new(|_| IncompatibleToolsTooltip {
 546                                                        incompatible_tools: incompatible_tools
 547                                                            .clone(),
 548                                                    })
 549                                                    .into()
 550                                                }
 551                                            }),
 552                                        )
 553                                    })
 554                                    .child(self.model_selector.clone())
 555                                    .map({
 556                                        let focus_handle = focus_handle.clone();
 557                                        move |parent| {
 558                                            if is_generating {
 559                                                parent
 560                                                    .when(is_editor_empty, |parent| {
 561                                                        parent.child(
 562                                                            IconButton::new(
 563                                                                "stop-generation",
 564                                                                IconName::StopFilled,
 565                                                            )
 566                                                            .icon_color(Color::Error)
 567                                                            .style(ButtonStyle::Tinted(
 568                                                                ui::TintColor::Error,
 569                                                            ))
 570                                                            .tooltip(move |window, cx| {
 571                                                                Tooltip::for_action(
 572                                                                    "Stop Generation",
 573                                                                    &editor::actions::Cancel,
 574                                                                    window,
 575                                                                    cx,
 576                                                                )
 577                                                            })
 578                                                            .on_click({
 579                                                                let focus_handle =
 580                                                                    focus_handle.clone();
 581                                                                move |_event, window, cx| {
 582                                                                    focus_handle.dispatch_action(
 583                                                                        &editor::actions::Cancel,
 584                                                                        window,
 585                                                                        cx,
 586                                                                    );
 587                                                                }
 588                                                            })
 589                                                            .with_animation(
 590                                                                "pulsating-label",
 591                                                                Animation::new(
 592                                                                    Duration::from_secs(2),
 593                                                                )
 594                                                                .repeat()
 595                                                                .with_easing(pulsating_between(
 596                                                                    0.4, 1.0,
 597                                                                )),
 598                                                                |icon_button, delta| {
 599                                                                    icon_button.alpha(delta)
 600                                                                },
 601                                                            ),
 602                                                        )
 603                                                    })
 604                                                    .when(!is_editor_empty, |parent| {
 605                                                        parent.child(
 606                                                    IconButton::new("send-message", IconName::Send)
 607                                                        .icon_color(Color::Accent)
 608                                                        .style(ButtonStyle::Filled)
 609                                                        .disabled(
 610                                                            !is_model_selected
 611                                                                || self
 612                                                                    .waiting_for_summaries_to_send,
 613                                                        )
 614                                                        .on_click({
 615                                                            let focus_handle = focus_handle.clone();
 616                                                            move |_event, window, cx| {
 617                                                                focus_handle.dispatch_action(
 618                                                                    &Chat, window, cx,
 619                                                                );
 620                                                            }
 621                                                        })
 622                                                        .tooltip(move |window, cx| {
 623                                                            Tooltip::for_action(
 624                                                                "Stop and Send New Message",
 625                                                                &Chat,
 626                                                                window,
 627                                                                cx,
 628                                                            )
 629                                                        }),
 630                                                )
 631                                                    })
 632                                            } else {
 633                                                parent.child(
 634                                                    IconButton::new("send-message", IconName::Send)
 635                                                        .icon_color(Color::Accent)
 636                                                        .style(ButtonStyle::Filled)
 637                                                        .disabled(
 638                                                            is_editor_empty
 639                                                                || !is_model_selected
 640                                                                || self
 641                                                                    .waiting_for_summaries_to_send,
 642                                                        )
 643                                                        .on_click({
 644                                                            let focus_handle = focus_handle.clone();
 645                                                            move |_event, window, cx| {
 646                                                                focus_handle.dispatch_action(
 647                                                                    &Chat, window, cx,
 648                                                                );
 649                                                            }
 650                                                        })
 651                                                        .when(
 652                                                            !is_editor_empty && is_model_selected,
 653                                                            |button| {
 654                                                                button.tooltip(move |window, cx| {
 655                                                                    Tooltip::for_action(
 656                                                                        "Send", &Chat, window, cx,
 657                                                                    )
 658                                                                })
 659                                                            },
 660                                                        )
 661                                                        .when(is_editor_empty, |button| {
 662                                                            button.tooltip(Tooltip::text(
 663                                                                "Type a message to submit",
 664                                                            ))
 665                                                        })
 666                                                        .when(!is_model_selected, |button| {
 667                                                            button.tooltip(Tooltip::text(
 668                                                                "Select a model to continue",
 669                                                            ))
 670                                                        }),
 671                                                )
 672                                            }
 673                                        }
 674                                    }),
 675                            ),
 676                    ),
 677            )
 678    }
 679
 680    fn render_changed_buffers(
 681        &self,
 682        changed_buffers: &BTreeMap<Entity<Buffer>, Entity<BufferDiff>>,
 683        window: &mut Window,
 684        cx: &mut Context<Self>,
 685    ) -> Div {
 686        let focus_handle = self.editor.focus_handle(cx);
 687
 688        let editor_bg_color = cx.theme().colors().editor_background;
 689        let border_color = cx.theme().colors().border;
 690        let active_color = cx.theme().colors().element_selected;
 691        let bg_edit_files_disclosure = editor_bg_color.blend(active_color.opacity(0.3));
 692        let is_edit_changes_expanded = self.edits_expanded;
 693
 694        v_flex()
 695            .mx_2()
 696            .bg(bg_edit_files_disclosure)
 697            .border_1()
 698            .border_b_0()
 699            .border_color(border_color)
 700            .rounded_t_md()
 701            .shadow(smallvec::smallvec![gpui::BoxShadow {
 702                color: gpui::black().opacity(0.15),
 703                offset: point(px(1.), px(-1.)),
 704                blur_radius: px(3.),
 705                spread_radius: px(0.),
 706            }])
 707            .child(
 708                h_flex()
 709                    .id("edits-container")
 710                    .cursor_pointer()
 711                    .p_1p5()
 712                    .justify_between()
 713                    .when(is_edit_changes_expanded, |this| {
 714                        this.border_b_1().border_color(border_color)
 715                    })
 716                    .on_click(
 717                        cx.listener(|this, _, window, cx| this.handle_review_click(window, cx)),
 718                    )
 719                    .child(
 720                        h_flex()
 721                            .gap_1()
 722                            .child(
 723                                Disclosure::new("edits-disclosure", is_edit_changes_expanded)
 724                                    .on_click(cx.listener(|this, _ev, _window, cx| {
 725                                        this.edits_expanded = !this.edits_expanded;
 726                                        cx.notify();
 727                                    })),
 728                            )
 729                            .child(
 730                                Label::new("Edits")
 731                                    .size(LabelSize::Small)
 732                                    .color(Color::Muted),
 733                            )
 734                            .child(Label::new("").size(LabelSize::XSmall).color(Color::Muted))
 735                            .child(
 736                                Label::new(format!(
 737                                    "{} {}",
 738                                    changed_buffers.len(),
 739                                    if changed_buffers.len() == 1 {
 740                                        "file"
 741                                    } else {
 742                                        "files"
 743                                    }
 744                                ))
 745                                .size(LabelSize::Small)
 746                                .color(Color::Muted),
 747                            ),
 748                    )
 749                    .child(
 750                        Button::new("review", "Review Changes")
 751                            .label_size(LabelSize::Small)
 752                            .key_binding(
 753                                KeyBinding::for_action_in(
 754                                    &OpenAgentDiff,
 755                                    &focus_handle,
 756                                    window,
 757                                    cx,
 758                                )
 759                                .map(|kb| kb.size(rems_from_px(12.))),
 760                            )
 761                            .on_click(cx.listener(|this, _, window, cx| {
 762                                this.handle_review_click(window, cx)
 763                            })),
 764                    ),
 765            )
 766            .when(is_edit_changes_expanded, |parent| {
 767                parent.child(
 768                    v_flex().children(changed_buffers.into_iter().enumerate().flat_map(
 769                        |(index, (buffer, _diff))| {
 770                            let file = buffer.read(cx).file()?;
 771                            let path = file.path();
 772
 773                            let parent_label = path.parent().and_then(|parent| {
 774                                let parent_str = parent.to_string_lossy();
 775
 776                                if parent_str.is_empty() {
 777                                    None
 778                                } else {
 779                                    Some(
 780                                        Label::new(format!(
 781                                            "/{}{}",
 782                                            parent_str,
 783                                            std::path::MAIN_SEPARATOR_STR
 784                                        ))
 785                                        .color(Color::Muted)
 786                                        .size(LabelSize::XSmall)
 787                                        .buffer_font(cx),
 788                                    )
 789                                }
 790                            });
 791
 792                            let name_label = path.file_name().map(|name| {
 793                                Label::new(name.to_string_lossy().to_string())
 794                                    .size(LabelSize::XSmall)
 795                                    .buffer_font(cx)
 796                            });
 797
 798                            let file_icon = FileIcons::get_icon(&path, cx)
 799                                .map(Icon::from_path)
 800                                .map(|icon| icon.color(Color::Muted).size(IconSize::Small))
 801                                .unwrap_or_else(|| {
 802                                    Icon::new(IconName::File)
 803                                        .color(Color::Muted)
 804                                        .size(IconSize::Small)
 805                                });
 806
 807                            let hover_color = cx
 808                                .theme()
 809                                .colors()
 810                                .element_background
 811                                .blend(cx.theme().colors().editor_foreground.opacity(0.025));
 812
 813                            let overlay_gradient = linear_gradient(
 814                                90.,
 815                                linear_color_stop(editor_bg_color, 1.),
 816                                linear_color_stop(editor_bg_color.opacity(0.2), 0.),
 817                            );
 818
 819                            let overlay_gradient_hover = linear_gradient(
 820                                90.,
 821                                linear_color_stop(hover_color, 1.),
 822                                linear_color_stop(hover_color.opacity(0.2), 0.),
 823                            );
 824
 825                            let element = h_flex()
 826                                .group("edited-code")
 827                                .id(("file-container", index))
 828                                .cursor_pointer()
 829                                .relative()
 830                                .py_1()
 831                                .pl_2()
 832                                .pr_1()
 833                                .gap_2()
 834                                .justify_between()
 835                                .bg(cx.theme().colors().editor_background)
 836                                .hover(|style| style.bg(hover_color))
 837                                .when(index + 1 < changed_buffers.len(), |parent| {
 838                                    parent.border_color(border_color).border_b_1()
 839                                })
 840                                .child(
 841                                    h_flex()
 842                                        .id("file-name")
 843                                        .pr_8()
 844                                        .gap_1p5()
 845                                        .max_w_full()
 846                                        .overflow_x_scroll()
 847                                        .child(file_icon)
 848                                        .child(
 849                                            h_flex()
 850                                                .gap_0p5()
 851                                                .children(name_label)
 852                                                .children(parent_label),
 853                                        ) // TODO: show lines changed
 854                                        .child(Label::new("+").color(Color::Created))
 855                                        .child(Label::new("-").color(Color::Deleted)),
 856                                )
 857                                .child(
 858                                    div().visible_on_hover("edited-code").child(
 859                                        Button::new("review", "Review")
 860                                            .label_size(LabelSize::Small)
 861                                            .on_click({
 862                                                let buffer = buffer.clone();
 863                                                cx.listener(move |this, _, window, cx| {
 864                                                    this.handle_file_click(
 865                                                        buffer.clone(),
 866                                                        window,
 867                                                        cx,
 868                                                    );
 869                                                })
 870                                            }),
 871                                    ),
 872                                )
 873                                .child(
 874                                    div()
 875                                        .id("gradient-overlay")
 876                                        .absolute()
 877                                        .h_5_6()
 878                                        .w_12()
 879                                        .bottom_0()
 880                                        .right(px(52.))
 881                                        .bg(overlay_gradient)
 882                                        .group_hover("edited-code", |style| {
 883                                            style.bg(overlay_gradient_hover)
 884                                        }),
 885                                )
 886                                .on_click({
 887                                    let buffer = buffer.clone();
 888                                    cx.listener(move |this, _, window, cx| {
 889                                        this.handle_file_click(buffer.clone(), window, cx);
 890                                    })
 891                                });
 892
 893                            Some(element)
 894                        },
 895                    )),
 896                )
 897            })
 898    }
 899
 900    fn render_token_limit_callout(
 901        &self,
 902        line_height: Pixels,
 903        token_usage_ratio: TokenUsageRatio,
 904        cx: &mut Context<Self>,
 905    ) -> Div {
 906        let heading = if token_usage_ratio == TokenUsageRatio::Exceeded {
 907            "Thread reached the token limit"
 908        } else {
 909            "Thread reaching the token limit soon"
 910        };
 911
 912        h_flex()
 913            .p_2()
 914            .gap_2()
 915            .flex_wrap()
 916            .justify_between()
 917            .bg(
 918                if token_usage_ratio == TokenUsageRatio::Exceeded {
 919                    cx.theme().status().error_background.opacity(0.1)
 920                } else {
 921                    cx.theme().status().warning_background.opacity(0.1)
 922                })
 923            .border_t_1()
 924            .border_color(cx.theme().colors().border)
 925            .child(
 926                h_flex()
 927                    .gap_2()
 928                    .items_start()
 929                    .child(
 930                        h_flex()
 931                            .h(line_height)
 932                            .justify_center()
 933                            .child(
 934                                if token_usage_ratio == TokenUsageRatio::Exceeded {
 935                                    Icon::new(IconName::X)
 936                                        .color(Color::Error)
 937                                        .size(IconSize::XSmall)
 938                                } else {
 939                                    Icon::new(IconName::Warning)
 940                                        .color(Color::Warning)
 941                                        .size(IconSize::XSmall)
 942                                }
 943                            ),
 944                    )
 945                    .child(
 946                        v_flex()
 947                            .mr_auto()
 948                            .child(Label::new(heading).size(LabelSize::Small))
 949                            .child(
 950                                Label::new(
 951                                    "Start a new thread from a summary to continue the conversation.",
 952                                )
 953                                .size(LabelSize::Small)
 954                                .color(Color::Muted),
 955                            ),
 956                    ),
 957            )
 958            .child(
 959                Button::new("new-thread", "Start New Thread")
 960                    .on_click(cx.listener(|this, _, window, cx| {
 961                        let from_thread_id = Some(this.thread.read(cx).id().clone());
 962
 963                        window.dispatch_action(Box::new(NewThread {
 964                            from_thread_id
 965                        }), cx);
 966                    }))
 967                    .icon(IconName::Plus)
 968                    .icon_position(IconPosition::Start)
 969                    .icon_size(IconSize::Small)
 970                    .style(ButtonStyle::Tinted(ui::TintColor::Accent))
 971                    .label_size(LabelSize::Small),
 972            )
 973    }
 974
 975    pub fn last_estimated_token_count(&self) -> Option<usize> {
 976        self.last_estimated_token_count
 977    }
 978
 979    pub fn is_waiting_to_update_token_count(&self) -> bool {
 980        self.update_token_count_task.is_some()
 981    }
 982
 983    fn message_or_context_changed(&mut self, debounce: bool, cx: &mut Context<Self>) {
 984        cx.emit(MessageEditorEvent::Changed);
 985        self.update_token_count_task.take();
 986
 987        let Some(default_model) = LanguageModelRegistry::read_global(cx).default_model() else {
 988            self.last_estimated_token_count.take();
 989            return;
 990        };
 991
 992        let context_store = self.context_store.clone();
 993        let editor = self.editor.clone();
 994        let thread = self.thread.clone();
 995
 996        self.update_token_count_task = Some(cx.spawn(async move |this, cx| {
 997            if debounce {
 998                cx.background_executor()
 999                    .timer(Duration::from_millis(200))
1000                    .await;
1001            }
1002
1003            let token_count = if let Some(task) = cx.update(|cx| {
1004                let context = context_store.read(cx).context().iter();
1005                let new_context = thread.read(cx).filter_new_context(context);
1006                let context_text =
1007                    format_context_as_string(new_context, cx).unwrap_or(String::new());
1008                let message_text = editor.read(cx).text(cx);
1009
1010                let content = context_text + &message_text;
1011
1012                if content.is_empty() {
1013                    return None;
1014                }
1015
1016                let request = language_model::LanguageModelRequest {
1017                    thread_id: None,
1018                    prompt_id: None,
1019                    messages: vec![LanguageModelRequestMessage {
1020                        role: language_model::Role::User,
1021                        content: vec![content.into()],
1022                        cache: false,
1023                    }],
1024                    tools: vec![],
1025                    stop: vec![],
1026                    temperature: None,
1027                };
1028
1029                Some(default_model.model.count_tokens(request, cx))
1030            })? {
1031                task.await?
1032            } else {
1033                0
1034            };
1035
1036            this.update(cx, |this, cx| {
1037                this.last_estimated_token_count = Some(token_count);
1038                cx.emit(MessageEditorEvent::EstimatedTokenCount);
1039                this.update_token_count_task.take();
1040            })
1041        }));
1042    }
1043}
1044
1045impl EventEmitter<MessageEditorEvent> for MessageEditor {}
1046
1047pub enum MessageEditorEvent {
1048    EstimatedTokenCount,
1049    Changed,
1050}
1051
1052impl Focusable for MessageEditor {
1053    fn focus_handle(&self, cx: &App) -> gpui::FocusHandle {
1054        self.editor.focus_handle(cx)
1055    }
1056}
1057
1058impl Render for MessageEditor {
1059    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1060        let thread = self.thread.read(cx);
1061        let total_token_usage = thread.total_token_usage(cx);
1062        let token_usage_ratio = total_token_usage.ratio();
1063
1064        let action_log = self.thread.read(cx).action_log();
1065        let changed_buffers = action_log.read(cx).changed_buffers(cx);
1066
1067        let font_size = TextSize::Small.rems(cx);
1068        let line_height = font_size.to_pixels(window.rem_size()) * 1.5;
1069
1070        v_flex()
1071            .size_full()
1072            .when(self.waiting_for_summaries_to_send, |parent| {
1073                parent.child(
1074                    h_flex().py_3().w_full().justify_center().child(
1075                        h_flex()
1076                            .flex_none()
1077                            .px_2()
1078                            .py_2()
1079                            .bg(cx.theme().colors().editor_background)
1080                            .border_1()
1081                            .border_color(cx.theme().colors().border_variant)
1082                            .rounded_lg()
1083                            .shadow_md()
1084                            .gap_1()
1085                            .child(
1086                                Icon::new(IconName::ArrowCircle)
1087                                    .size(IconSize::XSmall)
1088                                    .color(Color::Muted)
1089                                    .with_animation(
1090                                        "arrow-circle",
1091                                        Animation::new(Duration::from_secs(2)).repeat(),
1092                                        |icon, delta| {
1093                                            icon.transform(gpui::Transformation::rotate(
1094                                                gpui::percentage(delta),
1095                                            ))
1096                                        },
1097                                    ),
1098                            )
1099                            .child(
1100                                Label::new("Summarizing context…")
1101                                    .size(LabelSize::XSmall)
1102                                    .color(Color::Muted),
1103                            ),
1104                    ),
1105                )
1106            })
1107            .when(changed_buffers.len() > 0, |parent| {
1108                parent.child(self.render_changed_buffers(&changed_buffers, window, cx))
1109            })
1110            .child(self.render_editor(font_size, line_height, window, cx))
1111            .when(token_usage_ratio != TokenUsageRatio::Normal, |parent| {
1112                parent.child(self.render_token_limit_callout(line_height, token_usage_ratio, cx))
1113            })
1114    }
1115}