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