agent_ui.rs

  1mod active_thread;
  2mod agent_configuration;
  3mod agent_diff;
  4mod agent_model_selector;
  5mod agent_panel;
  6mod buffer_codegen;
  7mod burn_mode_tooltip;
  8mod context_picker;
  9mod context_server_configuration;
 10mod context_strip;
 11mod debug;
 12mod inline_assistant;
 13mod inline_prompt_editor;
 14mod language_model_selector;
 15mod message_editor;
 16mod profile_selector;
 17mod slash_command;
 18mod slash_command_picker;
 19mod slash_command_settings;
 20mod terminal_codegen;
 21mod terminal_inline_assistant;
 22mod text_thread_editor;
 23mod thread_history;
 24mod tool_compatibility;
 25mod ui;
 26
 27use std::sync::Arc;
 28
 29use agent::{Thread, ThreadId};
 30use agent_settings::{AgentProfileId, AgentSettings, LanguageModelSelection};
 31use assistant_slash_command::SlashCommandRegistry;
 32use client::Client;
 33use feature_flags::FeatureFlagAppExt as _;
 34use fs::Fs;
 35use gpui::{Action, App, Entity, actions};
 36use language::LanguageRegistry;
 37use language_model::{
 38    ConfiguredModel, LanguageModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
 39};
 40use prompt_store::PromptBuilder;
 41use schemars::JsonSchema;
 42use serde::Deserialize;
 43use settings::{Settings as _, SettingsStore};
 44
 45pub use crate::active_thread::ActiveThread;
 46use crate::agent_configuration::{ConfigureContextServerModal, ManageProfilesModal};
 47pub use crate::agent_panel::{AgentPanel, ConcreteAssistantPanelDelegate};
 48pub use crate::inline_assistant::InlineAssistant;
 49use crate::slash_command_settings::SlashCommandSettings;
 50pub use agent_diff::{AgentDiffPane, AgentDiffToolbar};
 51pub use text_thread_editor::{AgentPanelDelegate, TextThreadEditor};
 52pub use ui::preview::{all_agent_previews, get_agent_preview};
 53
 54actions!(
 55    agent,
 56    [
 57        /// Creates a new text-based conversation thread.
 58        NewTextThread,
 59        /// Toggles the context picker interface for adding files, symbols, or other context.
 60        ToggleContextPicker,
 61        /// Toggles the navigation menu for switching between threads and views.
 62        ToggleNavigationMenu,
 63        /// Toggles the options menu for agent settings and preferences.
 64        ToggleOptionsMenu,
 65        /// Deletes the recently opened thread from history.
 66        DeleteRecentlyOpenThread,
 67        /// Toggles the profile selector for switching between agent profiles.
 68        ToggleProfileSelector,
 69        /// Removes all added context from the current conversation.
 70        RemoveAllContext,
 71        /// Expands the message editor to full size.
 72        ExpandMessageEditor,
 73        /// Opens the conversation history view.
 74        OpenHistory,
 75        /// Adds a context server to the configuration.
 76        AddContextServer,
 77        /// Removes the currently selected thread.
 78        RemoveSelectedThread,
 79        /// Starts a chat conversation with the agent.
 80        Chat,
 81        /// Starts a chat conversation with follow-up enabled.
 82        ChatWithFollow,
 83        /// Cycles to the next inline assist suggestion.
 84        CycleNextInlineAssist,
 85        /// Cycles to the previous inline assist suggestion.
 86        CyclePreviousInlineAssist,
 87        /// Moves focus up in the interface.
 88        FocusUp,
 89        /// Moves focus down in the interface.
 90        FocusDown,
 91        /// Moves focus left in the interface.
 92        FocusLeft,
 93        /// Moves focus right in the interface.
 94        FocusRight,
 95        /// Removes the currently focused context item.
 96        RemoveFocusedContext,
 97        /// Accepts the suggested context item.
 98        AcceptSuggestedContext,
 99        /// Opens the active thread as a markdown file.
100        OpenActiveThreadAsMarkdown,
101        /// Opens the agent diff view to review changes.
102        OpenAgentDiff,
103        /// Keeps the current suggestion or change.
104        Keep,
105        /// Rejects the current suggestion or change.
106        Reject,
107        /// Rejects all suggestions or changes.
108        RejectAll,
109        /// Keeps all suggestions or changes.
110        KeepAll,
111        /// Follows the agent's suggestions.
112        Follow,
113        /// Resets the trial upsell notification.
114        ResetTrialUpsell,
115        /// Resets the trial end upsell notification.
116        ResetTrialEndUpsell,
117        /// Continues the current thread.
118        ContinueThread,
119        /// Continues the thread with burn mode enabled.
120        ContinueWithBurnMode,
121        /// Toggles burn mode for faster responses.
122        ToggleBurnMode,
123    ]
124);
125
126/// Creates a new conversation thread, optionally based on an existing thread.
127#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
128#[action(namespace = agent)]
129#[serde(deny_unknown_fields)]
130pub struct NewThread {
131    #[serde(default)]
132    from_thread_id: Option<ThreadId>,
133}
134
135/// Opens the profile management interface for configuring agent tools and settings.
136#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
137#[action(namespace = agent)]
138#[serde(deny_unknown_fields)]
139pub struct ManageProfiles {
140    #[serde(default)]
141    pub customize_tools: Option<AgentProfileId>,
142}
143
144impl ManageProfiles {
145    pub fn customize_tools(profile_id: AgentProfileId) -> Self {
146        Self {
147            customize_tools: Some(profile_id),
148        }
149    }
150}
151
152#[derive(Clone)]
153pub(crate) enum ModelUsageContext {
154    Thread(Entity<Thread>),
155    InlineAssistant,
156}
157
158impl ModelUsageContext {
159    pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
160        match self {
161            Self::Thread(thread) => thread.read(cx).configured_model(),
162            Self::InlineAssistant => {
163                LanguageModelRegistry::read_global(cx).inline_assistant_model()
164            }
165        }
166    }
167
168    pub fn language_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
169        self.configured_model(cx)
170            .map(|configured_model| configured_model.model)
171    }
172}
173
174/// Initializes the `agent` crate.
175pub fn init(
176    fs: Arc<dyn Fs>,
177    client: Arc<Client>,
178    prompt_builder: Arc<PromptBuilder>,
179    language_registry: Arc<LanguageRegistry>,
180    is_eval: bool,
181    cx: &mut App,
182) {
183    AgentSettings::register(cx);
184    SlashCommandSettings::register(cx);
185
186    assistant_context::init(client.clone(), cx);
187    rules_library::init(cx);
188    if !is_eval {
189        // Initializing the language model from the user settings messes with the eval, so we only initialize them when
190        // we're not running inside of the eval.
191        init_language_model_settings(cx);
192    }
193    assistant_slash_command::init(cx);
194    agent::init(cx);
195    agent_panel::init(cx);
196    context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
197    TextThreadEditor::init(cx);
198
199    register_slash_commands(cx);
200    inline_assistant::init(
201        fs.clone(),
202        prompt_builder.clone(),
203        client.telemetry().clone(),
204        cx,
205    );
206    terminal_inline_assistant::init(
207        fs.clone(),
208        prompt_builder.clone(),
209        client.telemetry().clone(),
210        cx,
211    );
212    indexed_docs::init(cx);
213    cx.observe_new(move |workspace, window, cx| {
214        ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
215    })
216    .detach();
217    cx.observe_new(ManageProfilesModal::register).detach();
218}
219
220fn init_language_model_settings(cx: &mut App) {
221    update_active_language_model_from_settings(cx);
222
223    cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
224        .detach();
225    cx.subscribe(
226        &LanguageModelRegistry::global(cx),
227        |_, event: &language_model::Event, cx| match event {
228            language_model::Event::ProviderStateChanged
229            | language_model::Event::AddedProvider(_)
230            | language_model::Event::RemovedProvider(_) => {
231                update_active_language_model_from_settings(cx);
232            }
233            _ => {}
234        },
235    )
236    .detach();
237}
238
239fn update_active_language_model_from_settings(cx: &mut App) {
240    let settings = AgentSettings::get_global(cx);
241
242    fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
243        language_model::SelectedModel {
244            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
245            model: LanguageModelId::from(selection.model.clone()),
246        }
247    }
248
249    let default = settings.default_model.as_ref().map(to_selected_model);
250    let inline_assistant = settings
251        .inline_assistant_model
252        .as_ref()
253        .map(to_selected_model);
254    let commit_message = settings
255        .commit_message_model
256        .as_ref()
257        .map(to_selected_model);
258    let thread_summary = settings
259        .thread_summary_model
260        .as_ref()
261        .map(to_selected_model);
262    let inline_alternatives = settings
263        .inline_alternatives
264        .iter()
265        .map(to_selected_model)
266        .collect::<Vec<_>>();
267
268    LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
269        registry.select_default_model(default.as_ref(), cx);
270        registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
271        registry.select_commit_message_model(commit_message.as_ref(), cx);
272        registry.select_thread_summary_model(thread_summary.as_ref(), cx);
273        registry.select_inline_alternative_models(inline_alternatives, cx);
274    });
275}
276
277fn register_slash_commands(cx: &mut App) {
278    let slash_command_registry = SlashCommandRegistry::global(cx);
279
280    slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
281    slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
282    slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
283    slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
284    slash_command_registry
285        .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
286    slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
287    slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
288    slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
289    slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
290    slash_command_registry
291        .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
292    slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
293
294    cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
295        let slash_command_registry = slash_command_registry.clone();
296        move |is_enabled, _cx| {
297            if is_enabled {
298                slash_command_registry.register_command(
299                    assistant_slash_commands::StreamingExampleSlashCommand,
300                    false,
301                );
302            }
303        }
304    })
305    .detach();
306
307    update_slash_commands_from_settings(cx);
308    cx.observe_global::<SettingsStore>(update_slash_commands_from_settings)
309        .detach();
310}
311
312fn update_slash_commands_from_settings(cx: &mut App) {
313    let slash_command_registry = SlashCommandRegistry::global(cx);
314    let settings = SlashCommandSettings::get_global(cx);
315
316    if settings.docs.enabled {
317        slash_command_registry.register_command(assistant_slash_commands::DocsSlashCommand, true);
318    } else {
319        slash_command_registry.unregister_command(assistant_slash_commands::DocsSlashCommand);
320    }
321
322    if settings.cargo_workspace.enabled {
323        slash_command_registry
324            .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
325    } else {
326        slash_command_registry
327            .unregister_command(assistant_slash_commands::CargoWorkspaceSlashCommand);
328    }
329}