agent_ui.rs

  1mod acp;
  2mod agent_configuration;
  3mod agent_diff;
  4mod agent_model_selector;
  5mod agent_panel;
  6mod buffer_codegen;
  7mod completion_provider;
  8mod context;
  9mod context_server_configuration;
 10#[cfg(test)]
 11mod evals;
 12mod inline_assistant;
 13mod inline_prompt_editor;
 14mod language_model_selector;
 15mod mention_set;
 16mod profile_selector;
 17mod slash_command;
 18mod slash_command_picker;
 19mod terminal_codegen;
 20mod terminal_inline_assistant;
 21mod text_thread_editor;
 22mod ui;
 23
 24use std::rc::Rc;
 25use std::sync::Arc;
 26
 27use agent_settings::{AgentProfileId, AgentSettings};
 28use assistant_slash_command::SlashCommandRegistry;
 29use client::Client;
 30use command_palette_hooks::CommandPaletteFilter;
 31use feature_flags::FeatureFlagAppExt as _;
 32use fs::Fs;
 33use gpui::{Action, App, Entity, SharedString, actions};
 34use language::{
 35    LanguageRegistry,
 36    language_settings::{AllLanguageSettings, EditPredictionProvider},
 37};
 38use language_model::{
 39    ConfiguredModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
 40};
 41use project::DisableAiSettings;
 42use prompt_store::PromptBuilder;
 43use schemars::JsonSchema;
 44use serde::{Deserialize, Serialize};
 45use settings::{LanguageModelSelection, Settings as _, SettingsStore};
 46use std::any::TypeId;
 47
 48use crate::agent_configuration::{ConfigureContextServerModal, ManageProfilesModal};
 49pub use crate::agent_panel::{AgentPanel, ConcreteAssistantPanelDelegate};
 50pub use crate::inline_assistant::InlineAssistant;
 51pub use agent_diff::{AgentDiffPane, AgentDiffToolbar};
 52pub use text_thread_editor::{AgentPanelDelegate, TextThreadEditor};
 53use zed_actions;
 54
 55actions!(
 56    agent,
 57    [
 58        /// Creates a new text-based conversation thread.
 59        NewTextThread,
 60        /// Toggles the menu to create new agent threads.
 61        ToggleNewThreadMenu,
 62        /// Toggles the navigation menu for switching between threads and views.
 63        ToggleNavigationMenu,
 64        /// Toggles the options menu for agent settings and preferences.
 65        ToggleOptionsMenu,
 66        /// Deletes the recently opened thread from history.
 67        DeleteRecentlyOpenThread,
 68        /// Toggles the profile or mode selector for switching between agent profiles.
 69        ToggleProfileSelector,
 70        /// Cycles through available session modes.
 71        CycleModeSelector,
 72        /// Expands the message editor to full size.
 73        ExpandMessageEditor,
 74        /// Removes all thread history.
 75        RemoveHistory,
 76        /// Opens the conversation history view.
 77        OpenHistory,
 78        /// Adds a context server to the configuration.
 79        AddContextServer,
 80        /// Removes the currently selected thread.
 81        RemoveSelectedThread,
 82        /// Starts a chat conversation with follow-up enabled.
 83        ChatWithFollow,
 84        /// Cycles to the next inline assist suggestion.
 85        CycleNextInlineAssist,
 86        /// Cycles to the previous inline assist suggestion.
 87        CyclePreviousInlineAssist,
 88        /// Moves focus up in the interface.
 89        FocusUp,
 90        /// Moves focus down in the interface.
 91        FocusDown,
 92        /// Moves focus left in the interface.
 93        FocusLeft,
 94        /// Moves focus right in the interface.
 95        FocusRight,
 96        /// Opens the active thread as a markdown file.
 97        OpenActiveThreadAsMarkdown,
 98        /// Opens the agent diff view to review changes.
 99        OpenAgentDiff,
100        /// Keeps the current suggestion or change.
101        Keep,
102        /// Rejects the current suggestion or change.
103        Reject,
104        /// Rejects all suggestions or changes.
105        RejectAll,
106        /// Keeps all suggestions or changes.
107        KeepAll,
108        /// Allow this operation only this time.
109        AllowOnce,
110        /// Allow this operation and remember the choice.
111        AllowAlways,
112        /// Reject this operation only this time.
113        RejectOnce,
114        /// Follows the agent's suggestions.
115        Follow,
116        /// Resets the trial upsell notification.
117        ResetTrialUpsell,
118        /// Resets the trial end upsell notification.
119        ResetTrialEndUpsell,
120        /// Continues the current thread.
121        ContinueThread,
122        /// Continues the thread with burn mode enabled.
123        ContinueWithBurnMode,
124        /// Toggles burn mode for faster responses.
125        ToggleBurnMode,
126    ]
127);
128
129/// Creates a new conversation thread, optionally based on an existing thread.
130#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
131#[action(namespace = agent)]
132#[serde(deny_unknown_fields)]
133pub struct NewThread;
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(Clone, PartialEq, Deserialize, JsonSchema, Action)]
145#[action(namespace = agent)]
146#[serde(deny_unknown_fields)]
147pub struct NewNativeAgentThreadFromSummary {
148    from_session_id: agent_client_protocol::SessionId,
149}
150
151// TODO unify this with AgentType
152#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
153#[serde(rename_all = "snake_case")]
154pub enum ExternalAgent {
155    Gemini,
156    ClaudeCode,
157    Codex,
158    NativeAgent,
159    Custom { name: SharedString },
160}
161
162impl ExternalAgent {
163    pub fn server(
164        &self,
165        fs: Arc<dyn fs::Fs>,
166        history: Entity<agent::HistoryStore>,
167    ) -> Rc<dyn agent_servers::AgentServer> {
168        match self {
169            Self::Gemini => Rc::new(agent_servers::Gemini),
170            Self::ClaudeCode => Rc::new(agent_servers::ClaudeCode),
171            Self::Codex => Rc::new(agent_servers::Codex),
172            Self::NativeAgent => Rc::new(agent::NativeAgentServer::new(fs, history)),
173            Self::Custom { name } => Rc::new(agent_servers::CustomAgentServer::new(name.clone())),
174        }
175    }
176}
177
178/// Opens the profile management interface for configuring agent tools and settings.
179#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
180#[action(namespace = agent)]
181#[serde(deny_unknown_fields)]
182pub struct ManageProfiles {
183    #[serde(default)]
184    pub customize_tools: Option<AgentProfileId>,
185}
186
187impl ManageProfiles {
188    pub fn customize_tools(profile_id: AgentProfileId) -> Self {
189        Self {
190            customize_tools: Some(profile_id),
191        }
192    }
193}
194
195#[derive(Clone)]
196pub(crate) enum ModelUsageContext {
197    InlineAssistant,
198}
199
200impl ModelUsageContext {
201    pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
202        match self {
203            Self::InlineAssistant => {
204                LanguageModelRegistry::read_global(cx).inline_assistant_model()
205            }
206        }
207    }
208}
209
210/// Initializes the `agent` crate.
211pub fn init(
212    fs: Arc<dyn Fs>,
213    client: Arc<Client>,
214    prompt_builder: Arc<PromptBuilder>,
215    language_registry: Arc<LanguageRegistry>,
216    is_eval: bool,
217    cx: &mut App,
218) {
219    assistant_text_thread::init(client.clone(), cx);
220    rules_library::init(cx);
221    if !is_eval {
222        // Initializing the language model from the user settings messes with the eval, so we only initialize them when
223        // we're not running inside of the eval.
224        init_language_model_settings(cx);
225    }
226    assistant_slash_command::init(cx);
227    agent_panel::init(cx);
228    context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
229    TextThreadEditor::init(cx);
230
231    register_slash_commands(cx);
232    inline_assistant::init(
233        fs.clone(),
234        prompt_builder.clone(),
235        client.telemetry().clone(),
236        cx,
237    );
238    terminal_inline_assistant::init(fs.clone(), prompt_builder, client.telemetry().clone(), cx);
239    cx.observe_new(move |workspace, window, cx| {
240        ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
241    })
242    .detach();
243    cx.observe_new(ManageProfilesModal::register).detach();
244
245    // Update command palette filter based on AI settings
246    update_command_palette_filter(cx);
247
248    // Watch for settings changes
249    cx.observe_global::<SettingsStore>(|app_cx| {
250        // When settings change, update the command palette filter
251        update_command_palette_filter(app_cx);
252    })
253    .detach();
254}
255
256fn update_command_palette_filter(cx: &mut App) {
257    let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
258    let agent_enabled = AgentSettings::get_global(cx).enabled;
259    let edit_prediction_provider = AllLanguageSettings::get_global(cx)
260        .edit_predictions
261        .provider;
262
263    CommandPaletteFilter::update_global(cx, |filter, _| {
264        use editor::actions::{
265            AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
266            PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
267        };
268        let edit_prediction_actions = [
269            TypeId::of::<AcceptEditPrediction>(),
270            TypeId::of::<AcceptPartialEditPrediction>(),
271            TypeId::of::<ShowEditPrediction>(),
272            TypeId::of::<NextEditPrediction>(),
273            TypeId::of::<PreviousEditPrediction>(),
274            TypeId::of::<ToggleEditPrediction>(),
275        ];
276
277        if disable_ai {
278            filter.hide_namespace("agent");
279            filter.hide_namespace("assistant");
280            filter.hide_namespace("copilot");
281            filter.hide_namespace("supermaven");
282            filter.hide_namespace("zed_predict_onboarding");
283            filter.hide_namespace("edit_prediction");
284
285            filter.hide_action_types(&edit_prediction_actions);
286            filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
287        } else {
288            if agent_enabled {
289                filter.show_namespace("agent");
290            } else {
291                filter.hide_namespace("agent");
292            }
293
294            filter.show_namespace("assistant");
295
296            match edit_prediction_provider {
297                EditPredictionProvider::None => {
298                    filter.hide_namespace("edit_prediction");
299                    filter.hide_namespace("copilot");
300                    filter.hide_namespace("supermaven");
301                    filter.hide_action_types(&edit_prediction_actions);
302                }
303                EditPredictionProvider::Copilot => {
304                    filter.show_namespace("edit_prediction");
305                    filter.show_namespace("copilot");
306                    filter.hide_namespace("supermaven");
307                    filter.show_action_types(edit_prediction_actions.iter());
308                }
309                EditPredictionProvider::Supermaven => {
310                    filter.show_namespace("edit_prediction");
311                    filter.hide_namespace("copilot");
312                    filter.show_namespace("supermaven");
313                    filter.show_action_types(edit_prediction_actions.iter());
314                }
315                EditPredictionProvider::Zed
316                | EditPredictionProvider::Codestral
317                | EditPredictionProvider::Experimental(_) => {
318                    filter.show_namespace("edit_prediction");
319                    filter.hide_namespace("copilot");
320                    filter.hide_namespace("supermaven");
321                    filter.show_action_types(edit_prediction_actions.iter());
322                }
323            }
324
325            filter.show_namespace("zed_predict_onboarding");
326            filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
327        }
328    });
329}
330
331fn init_language_model_settings(cx: &mut App) {
332    update_active_language_model_from_settings(cx);
333
334    cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
335        .detach();
336    cx.subscribe(
337        &LanguageModelRegistry::global(cx),
338        |_, event: &language_model::Event, cx| match event {
339            language_model::Event::ProviderStateChanged(_)
340            | language_model::Event::AddedProvider(_)
341            | language_model::Event::RemovedProvider(_) => {
342                update_active_language_model_from_settings(cx);
343            }
344            _ => {}
345        },
346    )
347    .detach();
348}
349
350fn update_active_language_model_from_settings(cx: &mut App) {
351    let settings = AgentSettings::get_global(cx);
352
353    fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
354        language_model::SelectedModel {
355            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
356            model: LanguageModelId::from(selection.model.clone()),
357        }
358    }
359
360    let default = settings.default_model.as_ref().map(to_selected_model);
361    let inline_assistant = settings
362        .inline_assistant_model
363        .as_ref()
364        .map(to_selected_model);
365    let commit_message = settings
366        .commit_message_model
367        .as_ref()
368        .map(to_selected_model);
369    let thread_summary = settings
370        .thread_summary_model
371        .as_ref()
372        .map(to_selected_model);
373    let inline_alternatives = settings
374        .inline_alternatives
375        .iter()
376        .map(to_selected_model)
377        .collect::<Vec<_>>();
378
379    LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
380        registry.select_default_model(default.as_ref(), cx);
381        registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
382        registry.select_commit_message_model(commit_message.as_ref(), cx);
383        registry.select_thread_summary_model(thread_summary.as_ref(), cx);
384        registry.select_inline_alternative_models(inline_alternatives, cx);
385    });
386}
387
388fn register_slash_commands(cx: &mut App) {
389    let slash_command_registry = SlashCommandRegistry::global(cx);
390
391    slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
392    slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
393    slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
394    slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
395    slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
396    slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
397    slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
398    slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
399    slash_command_registry
400        .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
401    slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
402
403    cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
404        move |is_enabled, _cx| {
405            if is_enabled {
406                slash_command_registry.register_command(
407                    assistant_slash_commands::StreamingExampleSlashCommand,
408                    false,
409                );
410            }
411        }
412    })
413    .detach();
414}
415
416#[cfg(test)]
417mod tests {
418    use super::*;
419    use agent_settings::{AgentProfileId, AgentSettings, CompletionMode};
420    use command_palette_hooks::CommandPaletteFilter;
421    use editor::actions::AcceptEditPrediction;
422    use gpui::{BorrowAppContext, TestAppContext, px};
423    use project::DisableAiSettings;
424    use settings::{
425        DefaultAgentView, DockPosition, NotifyWhenAgentWaiting, Settings, SettingsStore,
426    };
427
428    #[gpui::test]
429    fn test_agent_command_palette_visibility(cx: &mut TestAppContext) {
430        // Init settings
431        cx.update(|cx| {
432            let store = SettingsStore::test(cx);
433            cx.set_global(store);
434            command_palette_hooks::init(cx);
435            AgentSettings::register(cx);
436            DisableAiSettings::register(cx);
437            AllLanguageSettings::register(cx);
438        });
439
440        let agent_settings = AgentSettings {
441            enabled: true,
442            button: true,
443            dock: DockPosition::Right,
444            default_width: px(300.),
445            default_height: px(600.),
446            default_model: None,
447            inline_assistant_model: None,
448            inline_assistant_use_streaming_tools: false,
449            commit_message_model: None,
450            thread_summary_model: None,
451            inline_alternatives: vec![],
452            default_profile: AgentProfileId::default(),
453            default_view: DefaultAgentView::Thread,
454            profiles: Default::default(),
455            always_allow_tool_actions: false,
456            notify_when_agent_waiting: NotifyWhenAgentWaiting::default(),
457            play_sound_when_agent_done: false,
458            single_file_review: false,
459            model_parameters: vec![],
460            preferred_completion_mode: CompletionMode::Normal,
461            enable_feedback: false,
462            expand_edit_card: true,
463            expand_terminal_card: true,
464            use_modifier_to_send: true,
465            message_editor_min_lines: 1,
466        };
467
468        cx.update(|cx| {
469            AgentSettings::override_global(agent_settings.clone(), cx);
470            DisableAiSettings::override_global(DisableAiSettings { disable_ai: false }, cx);
471
472            // Initial update
473            update_command_palette_filter(cx);
474        });
475
476        // Assert visible
477        cx.update(|cx| {
478            let filter = CommandPaletteFilter::try_global(cx).unwrap();
479            assert!(
480                !filter.is_hidden(&NewThread),
481                "NewThread should be visible by default"
482            );
483        });
484
485        // Disable agent
486        cx.update(|cx| {
487            let mut new_settings = agent_settings.clone();
488            new_settings.enabled = false;
489            AgentSettings::override_global(new_settings, cx);
490
491            // Trigger update
492            update_command_palette_filter(cx);
493        });
494
495        // Assert hidden
496        cx.update(|cx| {
497            let filter = CommandPaletteFilter::try_global(cx).unwrap();
498            assert!(
499                filter.is_hidden(&NewThread),
500                "NewThread should be hidden when agent is disabled"
501            );
502        });
503
504        // Test EditPredictionProvider
505        // Enable EditPredictionProvider::Copilot
506        cx.update(|cx| {
507            cx.update_global::<SettingsStore, _>(|store, cx| {
508                store.update_user_settings(cx, |s| {
509                    s.project
510                        .all_languages
511                        .features
512                        .get_or_insert(Default::default())
513                        .edit_prediction_provider = Some(EditPredictionProvider::Copilot);
514                });
515            });
516            update_command_palette_filter(cx);
517        });
518
519        cx.update(|cx| {
520            let filter = CommandPaletteFilter::try_global(cx).unwrap();
521            assert!(
522                !filter.is_hidden(&AcceptEditPrediction),
523                "EditPrediction should be visible when provider is Copilot"
524            );
525        });
526
527        // Disable EditPredictionProvider (None)
528        cx.update(|cx| {
529            cx.update_global::<SettingsStore, _>(|store, cx| {
530                store.update_user_settings(cx, |s| {
531                    s.project
532                        .all_languages
533                        .features
534                        .get_or_insert(Default::default())
535                        .edit_prediction_provider = Some(EditPredictionProvider::None);
536                });
537            });
538            update_command_palette_filter(cx);
539        });
540
541        cx.update(|cx| {
542            let filter = CommandPaletteFilter::try_global(cx).unwrap();
543            assert!(
544                filter.is_hidden(&AcceptEditPrediction),
545                "EditPrediction should be hidden when provider is None"
546            );
547        });
548    }
549}