agent_ui.rs

  1mod acp;
  2mod active_thread;
  3mod agent_configuration;
  4mod agent_diff;
  5mod agent_model_selector;
  6mod agent_panel;
  7mod buffer_codegen;
  8mod burn_mode_tooltip;
  9mod context_picker;
 10mod context_server_configuration;
 11mod context_strip;
 12mod debug;
 13mod inline_assistant;
 14mod inline_prompt_editor;
 15mod language_model_selector;
 16mod message_editor;
 17mod profile_selector;
 18mod slash_command;
 19mod slash_command_picker;
 20mod slash_command_settings;
 21mod terminal_codegen;
 22mod terminal_inline_assistant;
 23mod text_thread_editor;
 24mod thread_history;
 25mod tool_compatibility;
 26mod ui;
 27
 28use std::rc::Rc;
 29use std::sync::Arc;
 30
 31use agent::{Thread, ThreadId};
 32use agent_settings::{AgentProfileId, AgentSettings, LanguageModelSelection};
 33use assistant_slash_command::SlashCommandRegistry;
 34use client::Client;
 35use feature_flags::FeatureFlagAppExt as _;
 36use fs::Fs;
 37use gpui::{Action, App, Entity, actions};
 38use language::LanguageRegistry;
 39use language_model::{
 40    ConfiguredModel, LanguageModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
 41};
 42use prompt_store::PromptBuilder;
 43use schemars::JsonSchema;
 44use serde::{Deserialize, Serialize};
 45use settings::{Settings as _, SettingsStore};
 46
 47pub use crate::active_thread::ActiveThread;
 48use crate::agent_configuration::{ConfigureContextServerModal, ManageProfilesModal};
 49pub use crate::agent_panel::{AgentPanel, ConcreteAssistantPanelDelegate};
 50pub use crate::inline_assistant::InlineAssistant;
 51use crate::slash_command_settings::SlashCommandSettings;
 52pub use agent_diff::{AgentDiffPane, AgentDiffToolbar};
 53pub use text_thread_editor::{AgentPanelDelegate, TextThreadEditor};
 54pub use ui::preview::{all_agent_previews, get_agent_preview};
 55
 56actions!(
 57    agent,
 58    [
 59        /// Creates a new text-based conversation thread.
 60        NewTextThread,
 61        /// Toggles the context picker interface for adding files, symbols, or other context.
 62        ToggleContextPicker,
 63        /// Toggles the navigation menu for switching between threads and views.
 64        ToggleNavigationMenu,
 65        /// Toggles the options menu for agent settings and preferences.
 66        ToggleOptionsMenu,
 67        /// Deletes the recently opened thread from history.
 68        DeleteRecentlyOpenThread,
 69        /// Toggles the profile selector for switching between agent profiles.
 70        ToggleProfileSelector,
 71        /// Removes all added context from the current conversation.
 72        RemoveAllContext,
 73        /// Expands the message editor to full size.
 74        ExpandMessageEditor,
 75        /// Opens the conversation history view.
 76        OpenHistory,
 77        /// Adds a context server to the configuration.
 78        AddContextServer,
 79        /// Removes the currently selected thread.
 80        RemoveSelectedThread,
 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/// Creates a new external agent conversation thread.
136#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
137#[action(namespace = agent)]
138#[serde(deny_unknown_fields)]
139pub struct NewExternalAgentThread {
140    /// Which agent to use for the conversation.
141    agent: Option<ExternalAgent>,
142}
143
144#[derive(Default, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
145#[serde(rename_all = "snake_case")]
146enum ExternalAgent {
147    #[default]
148    Gemini,
149    ClaudeCode,
150    Codex,
151}
152
153impl ExternalAgent {
154    pub fn server(&self) -> Rc<dyn agent_servers::AgentServer> {
155        match self {
156            ExternalAgent::Gemini => Rc::new(agent_servers::Gemini),
157            ExternalAgent::ClaudeCode => Rc::new(agent_servers::ClaudeCode),
158            ExternalAgent::Codex => Rc::new(agent_servers::Codex),
159        }
160    }
161}
162
163/// Opens the profile management interface for configuring agent tools and settings.
164#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
165#[action(namespace = agent)]
166#[serde(deny_unknown_fields)]
167pub struct ManageProfiles {
168    #[serde(default)]
169    pub customize_tools: Option<AgentProfileId>,
170}
171
172impl ManageProfiles {
173    pub fn customize_tools(profile_id: AgentProfileId) -> Self {
174        Self {
175            customize_tools: Some(profile_id),
176        }
177    }
178}
179
180#[derive(Clone)]
181pub(crate) enum ModelUsageContext {
182    Thread(Entity<Thread>),
183    InlineAssistant,
184}
185
186impl ModelUsageContext {
187    pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
188        match self {
189            Self::Thread(thread) => thread.read(cx).configured_model(),
190            Self::InlineAssistant => {
191                LanguageModelRegistry::read_global(cx).inline_assistant_model()
192            }
193        }
194    }
195
196    pub fn language_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
197        self.configured_model(cx)
198            .map(|configured_model| configured_model.model)
199    }
200}
201
202/// Initializes the `agent` crate.
203pub fn init(
204    fs: Arc<dyn Fs>,
205    client: Arc<Client>,
206    prompt_builder: Arc<PromptBuilder>,
207    language_registry: Arc<LanguageRegistry>,
208    is_eval: bool,
209    cx: &mut App,
210) {
211    AgentSettings::register(cx);
212    SlashCommandSettings::register(cx);
213
214    assistant_context::init(client.clone(), cx);
215    rules_library::init(cx);
216    if !is_eval {
217        // Initializing the language model from the user settings messes with the eval, so we only initialize them when
218        // we're not running inside of the eval.
219        init_language_model_settings(cx);
220    }
221    assistant_slash_command::init(cx);
222    agent::init(cx);
223    agent_panel::init(cx);
224    context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
225    TextThreadEditor::init(cx);
226
227    register_slash_commands(cx);
228    inline_assistant::init(
229        fs.clone(),
230        prompt_builder.clone(),
231        client.telemetry().clone(),
232        cx,
233    );
234    terminal_inline_assistant::init(
235        fs.clone(),
236        prompt_builder.clone(),
237        client.telemetry().clone(),
238        cx,
239    );
240    indexed_docs::init(cx);
241    cx.observe_new(move |workspace, window, cx| {
242        ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
243    })
244    .detach();
245    cx.observe_new(ManageProfilesModal::register).detach();
246}
247
248fn init_language_model_settings(cx: &mut App) {
249    update_active_language_model_from_settings(cx);
250
251    cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
252        .detach();
253    cx.subscribe(
254        &LanguageModelRegistry::global(cx),
255        |_, event: &language_model::Event, cx| match event {
256            language_model::Event::ProviderStateChanged
257            | language_model::Event::AddedProvider(_)
258            | language_model::Event::RemovedProvider(_) => {
259                update_active_language_model_from_settings(cx);
260            }
261            _ => {}
262        },
263    )
264    .detach();
265}
266
267fn update_active_language_model_from_settings(cx: &mut App) {
268    let settings = AgentSettings::get_global(cx);
269
270    fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
271        language_model::SelectedModel {
272            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
273            model: LanguageModelId::from(selection.model.clone()),
274        }
275    }
276
277    let default = settings.default_model.as_ref().map(to_selected_model);
278    let inline_assistant = settings
279        .inline_assistant_model
280        .as_ref()
281        .map(to_selected_model);
282    let commit_message = settings
283        .commit_message_model
284        .as_ref()
285        .map(to_selected_model);
286    let thread_summary = settings
287        .thread_summary_model
288        .as_ref()
289        .map(to_selected_model);
290    let inline_alternatives = settings
291        .inline_alternatives
292        .iter()
293        .map(to_selected_model)
294        .collect::<Vec<_>>();
295
296    LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
297        registry.select_default_model(default.as_ref(), cx);
298        registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
299        registry.select_commit_message_model(commit_message.as_ref(), cx);
300        registry.select_thread_summary_model(thread_summary.as_ref(), cx);
301        registry.select_inline_alternative_models(inline_alternatives, cx);
302    });
303}
304
305fn register_slash_commands(cx: &mut App) {
306    let slash_command_registry = SlashCommandRegistry::global(cx);
307
308    slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
309    slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
310    slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
311    slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
312    slash_command_registry
313        .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
314    slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
315    slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
316    slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
317    slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
318    slash_command_registry
319        .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
320    slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
321
322    cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
323        let slash_command_registry = slash_command_registry.clone();
324        move |is_enabled, _cx| {
325            if is_enabled {
326                slash_command_registry.register_command(
327                    assistant_slash_commands::StreamingExampleSlashCommand,
328                    false,
329                );
330            }
331        }
332    })
333    .detach();
334
335    update_slash_commands_from_settings(cx);
336    cx.observe_global::<SettingsStore>(update_slash_commands_from_settings)
337        .detach();
338}
339
340fn update_slash_commands_from_settings(cx: &mut App) {
341    let slash_command_registry = SlashCommandRegistry::global(cx);
342    let settings = SlashCommandSettings::get_global(cx);
343
344    if settings.docs.enabled {
345        slash_command_registry.register_command(assistant_slash_commands::DocsSlashCommand, true);
346    } else {
347        slash_command_registry.unregister_command(assistant_slash_commands::DocsSlashCommand);
348    }
349
350    if settings.cargo_workspace.enabled {
351        slash_command_registry
352            .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
353    } else {
354        slash_command_registry
355            .unregister_command(assistant_slash_commands::CargoWorkspaceSlashCommand);
356    }
357}