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 parse_built_in(server: &dyn agent_servers::AgentServer) -> Option<Self> {
164        match server.telemetry_id() {
165            "gemini-cli" => Some(Self::Gemini),
166            "claude-code" => Some(Self::ClaudeCode),
167            "codex" => Some(Self::Codex),
168            "zed" => Some(Self::NativeAgent),
169            _ => None,
170        }
171    }
172
173    pub fn server(
174        &self,
175        fs: Arc<dyn fs::Fs>,
176        history: Entity<agent::HistoryStore>,
177    ) -> Rc<dyn agent_servers::AgentServer> {
178        match self {
179            Self::Gemini => Rc::new(agent_servers::Gemini),
180            Self::ClaudeCode => Rc::new(agent_servers::ClaudeCode),
181            Self::Codex => Rc::new(agent_servers::Codex),
182            Self::NativeAgent => Rc::new(agent::NativeAgentServer::new(fs, history)),
183            Self::Custom { name } => Rc::new(agent_servers::CustomAgentServer::new(name.clone())),
184        }
185    }
186}
187
188/// Opens the profile management interface for configuring agent tools and settings.
189#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
190#[action(namespace = agent)]
191#[serde(deny_unknown_fields)]
192pub struct ManageProfiles {
193    #[serde(default)]
194    pub customize_tools: Option<AgentProfileId>,
195}
196
197impl ManageProfiles {
198    pub fn customize_tools(profile_id: AgentProfileId) -> Self {
199        Self {
200            customize_tools: Some(profile_id),
201        }
202    }
203}
204
205#[derive(Clone)]
206pub(crate) enum ModelUsageContext {
207    InlineAssistant,
208}
209
210impl ModelUsageContext {
211    pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
212        match self {
213            Self::InlineAssistant => {
214                LanguageModelRegistry::read_global(cx).inline_assistant_model()
215            }
216        }
217    }
218}
219
220/// Initializes the `agent` crate.
221pub fn init(
222    fs: Arc<dyn Fs>,
223    client: Arc<Client>,
224    prompt_builder: Arc<PromptBuilder>,
225    language_registry: Arc<LanguageRegistry>,
226    is_eval: bool,
227    cx: &mut App,
228) {
229    assistant_text_thread::init(client.clone(), cx);
230    rules_library::init(cx);
231    if !is_eval {
232        // Initializing the language model from the user settings messes with the eval, so we only initialize them when
233        // we're not running inside of the eval.
234        init_language_model_settings(cx);
235    }
236    assistant_slash_command::init(cx);
237    agent_panel::init(cx);
238    context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
239    TextThreadEditor::init(cx);
240
241    register_slash_commands(cx);
242    inline_assistant::init(
243        fs.clone(),
244        prompt_builder.clone(),
245        client.telemetry().clone(),
246        cx,
247    );
248    terminal_inline_assistant::init(fs.clone(), prompt_builder, client.telemetry().clone(), cx);
249    cx.observe_new(move |workspace, window, cx| {
250        ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
251    })
252    .detach();
253    cx.observe_new(ManageProfilesModal::register).detach();
254
255    // Update command palette filter based on AI settings
256    update_command_palette_filter(cx);
257
258    // Watch for settings changes
259    cx.observe_global::<SettingsStore>(|app_cx| {
260        // When settings change, update the command palette filter
261        update_command_palette_filter(app_cx);
262    })
263    .detach();
264}
265
266fn update_command_palette_filter(cx: &mut App) {
267    let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
268    let agent_enabled = AgentSettings::get_global(cx).enabled;
269    let edit_prediction_provider = AllLanguageSettings::get_global(cx)
270        .edit_predictions
271        .provider;
272
273    CommandPaletteFilter::update_global(cx, |filter, _| {
274        use editor::actions::{
275            AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
276            PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
277        };
278        let edit_prediction_actions = [
279            TypeId::of::<AcceptEditPrediction>(),
280            TypeId::of::<AcceptPartialEditPrediction>(),
281            TypeId::of::<ShowEditPrediction>(),
282            TypeId::of::<NextEditPrediction>(),
283            TypeId::of::<PreviousEditPrediction>(),
284            TypeId::of::<ToggleEditPrediction>(),
285        ];
286
287        if disable_ai {
288            filter.hide_namespace("agent");
289            filter.hide_namespace("assistant");
290            filter.hide_namespace("copilot");
291            filter.hide_namespace("supermaven");
292            filter.hide_namespace("zed_predict_onboarding");
293            filter.hide_namespace("edit_prediction");
294
295            filter.hide_action_types(&edit_prediction_actions);
296            filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
297        } else {
298            if agent_enabled {
299                filter.show_namespace("agent");
300            } else {
301                filter.hide_namespace("agent");
302            }
303
304            filter.show_namespace("assistant");
305
306            match edit_prediction_provider {
307                EditPredictionProvider::None => {
308                    filter.hide_namespace("edit_prediction");
309                    filter.hide_namespace("copilot");
310                    filter.hide_namespace("supermaven");
311                    filter.hide_action_types(&edit_prediction_actions);
312                }
313                EditPredictionProvider::Copilot => {
314                    filter.show_namespace("edit_prediction");
315                    filter.show_namespace("copilot");
316                    filter.hide_namespace("supermaven");
317                    filter.show_action_types(edit_prediction_actions.iter());
318                }
319                EditPredictionProvider::Supermaven => {
320                    filter.show_namespace("edit_prediction");
321                    filter.hide_namespace("copilot");
322                    filter.show_namespace("supermaven");
323                    filter.show_action_types(edit_prediction_actions.iter());
324                }
325                EditPredictionProvider::Zed
326                | EditPredictionProvider::Codestral
327                | EditPredictionProvider::Experimental(_) => {
328                    filter.show_namespace("edit_prediction");
329                    filter.hide_namespace("copilot");
330                    filter.hide_namespace("supermaven");
331                    filter.show_action_types(edit_prediction_actions.iter());
332                }
333            }
334
335            filter.show_namespace("zed_predict_onboarding");
336            filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
337        }
338    });
339}
340
341fn init_language_model_settings(cx: &mut App) {
342    update_active_language_model_from_settings(cx);
343
344    cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
345        .detach();
346    cx.subscribe(
347        &LanguageModelRegistry::global(cx),
348        |_, event: &language_model::Event, cx| match event {
349            language_model::Event::ProviderStateChanged(_) => {
350                update_active_language_model_from_settings(cx);
351            }
352            language_model::Event::AddedProvider(_) => {
353                update_active_language_model_from_settings(cx);
354            }
355            language_model::Event::RemovedProvider(_) => {
356                update_active_language_model_from_settings(cx);
357            }
358            _ => {}
359        },
360    )
361    .detach();
362}
363
364fn update_active_language_model_from_settings(cx: &mut App) {
365    let settings = AgentSettings::get_global(cx);
366
367    fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
368        language_model::SelectedModel {
369            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
370            model: LanguageModelId::from(selection.model.clone()),
371        }
372    }
373
374    // Filter out models from providers that are not authenticated
375    fn is_provider_authenticated(
376        selection: &LanguageModelSelection,
377        registry: &LanguageModelRegistry,
378        cx: &App,
379    ) -> bool {
380        let provider_id = LanguageModelProviderId::from(selection.provider.0.clone());
381        registry
382            .provider(&provider_id)
383            .map_or(false, |provider| provider.is_authenticated(cx))
384    }
385
386    let registry = LanguageModelRegistry::global(cx);
387    let registry_ref = registry.read(cx);
388
389    let default = settings
390        .default_model
391        .as_ref()
392        .filter(|s| is_provider_authenticated(s, registry_ref, cx))
393        .map(to_selected_model);
394    let inline_assistant = settings
395        .inline_assistant_model
396        .as_ref()
397        .filter(|s| is_provider_authenticated(s, registry_ref, cx))
398        .map(to_selected_model);
399    let commit_message = settings
400        .commit_message_model
401        .as_ref()
402        .filter(|s| is_provider_authenticated(s, registry_ref, cx))
403        .map(to_selected_model);
404    let thread_summary = settings
405        .thread_summary_model
406        .as_ref()
407        .filter(|s| is_provider_authenticated(s, registry_ref, cx))
408        .map(to_selected_model);
409    let inline_alternatives = settings
410        .inline_alternatives
411        .iter()
412        .filter(|s| is_provider_authenticated(s, registry_ref, cx))
413        .map(to_selected_model)
414        .collect::<Vec<_>>();
415
416    registry.update(cx, |registry, cx| {
417        registry.select_default_model(default.as_ref(), cx);
418        registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
419        registry.select_commit_message_model(commit_message.as_ref(), cx);
420        registry.select_thread_summary_model(thread_summary.as_ref(), cx);
421        registry.select_inline_alternative_models(inline_alternatives, cx);
422    });
423}
424
425fn register_slash_commands(cx: &mut App) {
426    let slash_command_registry = SlashCommandRegistry::global(cx);
427
428    slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
429    slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
430    slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
431    slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
432    slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
433    slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
434    slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
435    slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
436    slash_command_registry
437        .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
438    slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
439
440    cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
441        move |is_enabled, _cx| {
442            if is_enabled {
443                slash_command_registry.register_command(
444                    assistant_slash_commands::StreamingExampleSlashCommand,
445                    false,
446                );
447            }
448        }
449    })
450    .detach();
451}
452
453#[cfg(test)]
454mod tests {
455    use super::*;
456    use agent_settings::{AgentProfileId, AgentSettings, CompletionMode};
457    use command_palette_hooks::CommandPaletteFilter;
458    use editor::actions::AcceptEditPrediction;
459    use gpui::{BorrowAppContext, TestAppContext, px};
460    use project::DisableAiSettings;
461    use settings::{
462        DefaultAgentView, DockPosition, NotifyWhenAgentWaiting, Settings, SettingsStore,
463    };
464
465    #[gpui::test]
466    fn test_agent_command_palette_visibility(cx: &mut TestAppContext) {
467        // Init settings
468        cx.update(|cx| {
469            let store = SettingsStore::test(cx);
470            cx.set_global(store);
471            command_palette_hooks::init(cx);
472            AgentSettings::register(cx);
473            DisableAiSettings::register(cx);
474            AllLanguageSettings::register(cx);
475        });
476
477        let agent_settings = AgentSettings {
478            enabled: true,
479            button: true,
480            dock: DockPosition::Right,
481            default_width: px(300.),
482            default_height: px(600.),
483            default_model: None,
484            inline_assistant_model: None,
485            commit_message_model: None,
486            thread_summary_model: None,
487            inline_alternatives: vec![],
488            default_profile: AgentProfileId::default(),
489            default_view: DefaultAgentView::Thread,
490            profiles: Default::default(),
491            always_allow_tool_actions: false,
492            notify_when_agent_waiting: NotifyWhenAgentWaiting::default(),
493            play_sound_when_agent_done: false,
494            single_file_review: false,
495            model_parameters: vec![],
496            preferred_completion_mode: CompletionMode::Normal,
497            enable_feedback: false,
498            expand_edit_card: true,
499            expand_terminal_card: true,
500            use_modifier_to_send: true,
501            message_editor_min_lines: 1,
502        };
503
504        cx.update(|cx| {
505            AgentSettings::override_global(agent_settings.clone(), cx);
506            DisableAiSettings::override_global(DisableAiSettings { disable_ai: false }, cx);
507
508            // Initial update
509            update_command_palette_filter(cx);
510        });
511
512        // Assert visible
513        cx.update(|cx| {
514            let filter = CommandPaletteFilter::try_global(cx).unwrap();
515            assert!(
516                !filter.is_hidden(&NewThread),
517                "NewThread should be visible by default"
518            );
519        });
520
521        // Disable agent
522        cx.update(|cx| {
523            let mut new_settings = agent_settings.clone();
524            new_settings.enabled = false;
525            AgentSettings::override_global(new_settings, cx);
526
527            // Trigger update
528            update_command_palette_filter(cx);
529        });
530
531        // Assert hidden
532        cx.update(|cx| {
533            let filter = CommandPaletteFilter::try_global(cx).unwrap();
534            assert!(
535                filter.is_hidden(&NewThread),
536                "NewThread should be hidden when agent is disabled"
537            );
538        });
539
540        // Test EditPredictionProvider
541        // Enable EditPredictionProvider::Copilot
542        cx.update(|cx| {
543            cx.update_global::<SettingsStore, _>(|store, cx| {
544                store.update_user_settings(cx, |s| {
545                    s.project
546                        .all_languages
547                        .features
548                        .get_or_insert(Default::default())
549                        .edit_prediction_provider = Some(EditPredictionProvider::Copilot);
550                });
551            });
552            update_command_palette_filter(cx);
553        });
554
555        cx.update(|cx| {
556            let filter = CommandPaletteFilter::try_global(cx).unwrap();
557            assert!(
558                !filter.is_hidden(&AcceptEditPrediction),
559                "EditPrediction should be visible when provider is Copilot"
560            );
561        });
562
563        // Disable EditPredictionProvider (None)
564        cx.update(|cx| {
565            cx.update_global::<SettingsStore, _>(|store, cx| {
566                store.update_user_settings(cx, |s| {
567                    s.project
568                        .all_languages
569                        .features
570                        .get_or_insert(Default::default())
571                        .edit_prediction_provider = Some(EditPredictionProvider::None);
572                });
573            });
574            update_command_palette_filter(cx);
575        });
576
577        cx.update(|cx| {
578            let filter = CommandPaletteFilter::try_global(cx).unwrap();
579            assert!(
580                filter.is_hidden(&AcceptEditPrediction),
581                "EditPrediction should be hidden when provider is None"
582            );
583        });
584    }
585}