message_editor.rs

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