profile_selector.rs

  1use std::sync::Arc;
  2
  3use assistant_settings::{
  4    AgentProfile, AgentProfileId, AssistantDockPosition, AssistantSettings, GroupedAgentProfiles,
  5    builtin_profiles,
  6};
  7use fs::Fs;
  8use gpui::{Action, Entity, FocusHandle, Subscription, WeakEntity, prelude::*};
  9use language_model::LanguageModelRegistry;
 10use settings::{Settings as _, SettingsStore, update_settings_file};
 11use ui::{
 12    ContextMenu, ContextMenuEntry, DocumentationSide, PopoverMenu, PopoverMenuHandle, Tooltip,
 13    prelude::*,
 14};
 15use util::ResultExt as _;
 16
 17use crate::{ManageProfiles, Thread, ThreadStore, ToggleProfileSelector};
 18
 19pub struct ProfileSelector {
 20    profiles: GroupedAgentProfiles,
 21    fs: Arc<dyn Fs>,
 22    thread: Entity<Thread>,
 23    thread_store: WeakEntity<ThreadStore>,
 24    menu_handle: PopoverMenuHandle<ContextMenu>,
 25    focus_handle: FocusHandle,
 26    _subscriptions: Vec<Subscription>,
 27}
 28
 29impl ProfileSelector {
 30    pub fn new(
 31        fs: Arc<dyn Fs>,
 32        thread: Entity<Thread>,
 33        thread_store: WeakEntity<ThreadStore>,
 34        focus_handle: FocusHandle,
 35        cx: &mut Context<Self>,
 36    ) -> Self {
 37        let settings_subscription = cx.observe_global::<SettingsStore>(move |this, cx| {
 38            this.refresh_profiles(cx);
 39        });
 40
 41        Self {
 42            profiles: GroupedAgentProfiles::from_settings(AssistantSettings::get_global(cx)),
 43            fs,
 44            thread,
 45            thread_store,
 46            menu_handle: PopoverMenuHandle::default(),
 47            focus_handle,
 48            _subscriptions: vec![settings_subscription],
 49        }
 50    }
 51
 52    pub fn menu_handle(&self) -> PopoverMenuHandle<ContextMenu> {
 53        self.menu_handle.clone()
 54    }
 55
 56    fn refresh_profiles(&mut self, cx: &mut Context<Self>) {
 57        self.profiles = GroupedAgentProfiles::from_settings(AssistantSettings::get_global(cx));
 58    }
 59
 60    fn build_context_menu(
 61        &self,
 62        window: &mut Window,
 63        cx: &mut Context<Self>,
 64    ) -> Entity<ContextMenu> {
 65        ContextMenu::build(window, cx, |mut menu, _window, cx| {
 66            let settings = AssistantSettings::get_global(cx);
 67            for (profile_id, profile) in self.profiles.builtin.iter() {
 68                menu = menu.item(self.menu_entry_for_profile(
 69                    profile_id.clone(),
 70                    profile,
 71                    settings,
 72                    cx,
 73                ));
 74            }
 75
 76            if !self.profiles.custom.is_empty() {
 77                menu = menu.separator().header("Custom Profiles");
 78                for (profile_id, profile) in self.profiles.custom.iter() {
 79                    menu = menu.item(self.menu_entry_for_profile(
 80                        profile_id.clone(),
 81                        profile,
 82                        settings,
 83                        cx,
 84                    ));
 85                }
 86            }
 87
 88            menu = menu.separator();
 89            menu = menu.item(ContextMenuEntry::new("Configure Profiles…").handler(
 90                move |window, cx| {
 91                    window.dispatch_action(ManageProfiles::default().boxed_clone(), cx);
 92                },
 93            ));
 94
 95            menu
 96        })
 97    }
 98
 99    fn menu_entry_for_profile(
100        &self,
101        profile_id: AgentProfileId,
102        profile: &AgentProfile,
103        settings: &AssistantSettings,
104        _cx: &App,
105    ) -> ContextMenuEntry {
106        let documentation = match profile.name.to_lowercase().as_str() {
107            builtin_profiles::WRITE => Some("Get help to write anything."),
108            builtin_profiles::ASK => Some("Chat about your codebase."),
109            builtin_profiles::MINIMAL => Some("Chat about anything with no tools."),
110            _ => None,
111        };
112
113        let entry = ContextMenuEntry::new(profile.name.clone())
114            .toggleable(IconPosition::End, profile_id == settings.default_profile);
115
116        let entry = if let Some(doc_text) = documentation {
117            entry.documentation_aside(documentation_side(settings.dock), move |_| {
118                Label::new(doc_text).into_any_element()
119            })
120        } else {
121            entry
122        };
123
124        entry.handler({
125            let fs = self.fs.clone();
126            let thread_store = self.thread_store.clone();
127            let profile_id = profile_id.clone();
128            move |_window, cx| {
129                update_settings_file::<AssistantSettings>(fs.clone(), cx, {
130                    let profile_id = profile_id.clone();
131                    move |settings, _cx| {
132                        settings.set_profile(profile_id.clone());
133                    }
134                });
135
136                thread_store
137                    .update(cx, |this, cx| {
138                        this.load_profile_by_id(profile_id.clone(), cx);
139                    })
140                    .log_err();
141            }
142        })
143    }
144}
145
146impl Render for ProfileSelector {
147    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
148        let settings = AssistantSettings::get_global(cx);
149        let profile_id = &settings.default_profile;
150        let profile = settings.profiles.get(profile_id);
151
152        let selected_profile = profile
153            .map(|profile| profile.name.clone())
154            .unwrap_or_else(|| "Unknown".into());
155
156        let configured_model = self
157            .thread
158            .read_with(cx, |thread, _cx| thread.configured_model())
159            .or_else(|| {
160                let model_registry = LanguageModelRegistry::read_global(cx);
161                model_registry.default_model()
162            });
163        let supports_tools =
164            configured_model.map_or(false, |default| default.model.supports_tools());
165
166        if supports_tools {
167            let this = cx.entity().clone();
168            let focus_handle = self.focus_handle.clone();
169            let trigger_button = Button::new("profile-selector-model", selected_profile)
170                .label_size(LabelSize::Small)
171                .color(Color::Muted)
172                .icon(IconName::ChevronDown)
173                .icon_size(IconSize::XSmall)
174                .icon_position(IconPosition::End)
175                .icon_color(Color::Muted);
176
177            PopoverMenu::new("profile-selector")
178                .trigger_with_tooltip(trigger_button, {
179                    let focus_handle = focus_handle.clone();
180                    move |window, cx| {
181                        Tooltip::for_action_in(
182                            "Toggle Profile Menu",
183                            &ToggleProfileSelector,
184                            &focus_handle,
185                            window,
186                            cx,
187                        )
188                    }
189                })
190                .anchor(
191                    if documentation_side(settings.dock) == DocumentationSide::Left {
192                        gpui::Corner::BottomRight
193                    } else {
194                        gpui::Corner::BottomLeft
195                    },
196                )
197                .with_handle(self.menu_handle.clone())
198                .menu(move |window, cx| {
199                    Some(this.update(cx, |this, cx| this.build_context_menu(window, cx)))
200                })
201                .into_any_element()
202        } else {
203            Button::new("tools-not-supported-button", "Tools Unsupported")
204                .disabled(true)
205                .label_size(LabelSize::Small)
206                .color(Color::Muted)
207                .tooltip(Tooltip::text("This model does not support tools."))
208                .into_any_element()
209        }
210    }
211}
212
213fn documentation_side(position: AssistantDockPosition) -> DocumentationSide {
214    match position {
215        AssistantDockPosition::Left => DocumentationSide::Right,
216        AssistantDockPosition::Bottom => DocumentationSide::Left,
217        AssistantDockPosition::Right => DocumentationSide::Left,
218    }
219}