agent_ui.rs

  1pub mod 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;
 10mod favorite_models;
 11mod inline_assistant;
 12mod inline_prompt_editor;
 13mod language_model_selector;
 14mod mention_set;
 15mod profile_selector;
 16mod slash_command;
 17mod slash_command_picker;
 18mod terminal_codegen;
 19mod terminal_inline_assistant;
 20mod text_thread_editor;
 21mod text_thread_history;
 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::{AgentV2FeatureFlag, 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        /// Toggles the profile or mode selector for switching between agent profiles.
 67        ToggleProfileSelector,
 68        /// Cycles through available session modes.
 69        CycleModeSelector,
 70        /// Cycles through favorited models in the ACP model selector.
 71        CycleFavoriteModels,
 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        /// Interrupts the current generation and sends the message immediately.
127        SendImmediately,
128        /// Sends the next queued message immediately.
129        SendNextQueuedMessage,
130        /// Clears all messages from the queue.
131        ClearMessageQueue,
132        /// Opens the permission granularity dropdown for the current tool call.
133        OpenPermissionDropdown,
134    ]
135);
136
137/// Action to authorize a tool call with a specific permission option.
138/// This is used by the permission granularity dropdown to authorize tool calls.
139#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
140#[action(namespace = agent)]
141#[serde(deny_unknown_fields)]
142pub struct AuthorizeToolCall {
143    /// The tool call ID to authorize.
144    pub tool_call_id: String,
145    /// The permission option ID to use.
146    pub option_id: String,
147    /// The kind of permission option (serialized as string).
148    pub option_kind: String,
149}
150
151/// Action to select a permission granularity option from the dropdown.
152/// This updates the selected granularity without triggering authorization.
153#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
154#[action(namespace = agent)]
155#[serde(deny_unknown_fields)]
156pub struct SelectPermissionGranularity {
157    /// The tool call ID for which to select the granularity.
158    pub tool_call_id: String,
159    /// The index of the selected granularity option.
160    pub index: usize,
161}
162
163/// Creates a new conversation thread, optionally based on an existing thread.
164#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
165#[action(namespace = agent)]
166#[serde(deny_unknown_fields)]
167pub struct NewThread;
168
169/// Creates a new external agent conversation thread.
170#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
171#[action(namespace = agent)]
172#[serde(deny_unknown_fields)]
173pub struct NewExternalAgentThread {
174    /// Which agent to use for the conversation.
175    agent: Option<ExternalAgent>,
176}
177
178#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
179#[action(namespace = agent)]
180#[serde(deny_unknown_fields)]
181pub struct NewNativeAgentThreadFromSummary {
182    from_session_id: agent_client_protocol::SessionId,
183}
184
185// TODO unify this with AgentType
186#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
187#[serde(rename_all = "snake_case")]
188pub enum ExternalAgent {
189    Gemini,
190    ClaudeCode,
191    Codex,
192    NativeAgent,
193    Custom { name: SharedString },
194}
195
196impl ExternalAgent {
197    pub fn server(
198        &self,
199        fs: Arc<dyn fs::Fs>,
200        thread_store: Entity<agent::ThreadStore>,
201    ) -> Rc<dyn agent_servers::AgentServer> {
202        match self {
203            Self::Gemini => Rc::new(agent_servers::Gemini),
204            Self::ClaudeCode => Rc::new(agent_servers::ClaudeCode),
205            Self::Codex => Rc::new(agent_servers::Codex),
206            Self::NativeAgent => Rc::new(agent::NativeAgentServer::new(fs, thread_store)),
207            Self::Custom { name } => Rc::new(agent_servers::CustomAgentServer::new(name.clone())),
208        }
209    }
210}
211
212/// Opens the profile management interface for configuring agent tools and settings.
213#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
214#[action(namespace = agent)]
215#[serde(deny_unknown_fields)]
216pub struct ManageProfiles {
217    #[serde(default)]
218    pub customize_tools: Option<AgentProfileId>,
219}
220
221impl ManageProfiles {
222    pub fn customize_tools(profile_id: AgentProfileId) -> Self {
223        Self {
224            customize_tools: Some(profile_id),
225        }
226    }
227}
228
229#[derive(Clone)]
230pub(crate) enum ModelUsageContext {
231    InlineAssistant,
232}
233
234impl ModelUsageContext {
235    pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
236        match self {
237            Self::InlineAssistant => {
238                LanguageModelRegistry::read_global(cx).inline_assistant_model()
239            }
240        }
241    }
242}
243
244/// Initializes the `agent` crate.
245pub fn init(
246    fs: Arc<dyn Fs>,
247    client: Arc<Client>,
248    prompt_builder: Arc<PromptBuilder>,
249    language_registry: Arc<LanguageRegistry>,
250    is_eval: bool,
251    cx: &mut App,
252) {
253    assistant_text_thread::init(client, cx);
254    rules_library::init(cx);
255    if !is_eval {
256        // Initializing the language model from the user settings messes with the eval, so we only initialize them when
257        // we're not running inside of the eval.
258        init_language_model_settings(cx);
259    }
260    assistant_slash_command::init(cx);
261    agent_panel::init(cx);
262    context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
263    TextThreadEditor::init(cx);
264
265    register_slash_commands(cx);
266    inline_assistant::init(fs.clone(), prompt_builder.clone(), cx);
267    terminal_inline_assistant::init(fs.clone(), prompt_builder, cx);
268    cx.observe_new(move |workspace, window, cx| {
269        ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
270    })
271    .detach();
272    cx.observe_new(ManageProfilesModal::register).detach();
273
274    // Update command palette filter based on AI settings
275    update_command_palette_filter(cx);
276
277    // Watch for settings changes
278    cx.observe_global::<SettingsStore>(|app_cx| {
279        // When settings change, update the command palette filter
280        update_command_palette_filter(app_cx);
281    })
282    .detach();
283
284    cx.on_flags_ready(|_, cx| {
285        update_command_palette_filter(cx);
286    })
287    .detach();
288}
289
290fn update_command_palette_filter(cx: &mut App) {
291    let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
292    let agent_enabled = AgentSettings::get_global(cx).enabled;
293    let agent_v2_enabled = cx.has_flag::<AgentV2FeatureFlag>();
294    let edit_prediction_provider = AllLanguageSettings::get_global(cx)
295        .edit_predictions
296        .provider;
297
298    CommandPaletteFilter::update_global(cx, |filter, _| {
299        use editor::actions::{
300            AcceptEditPrediction, AcceptNextLineEditPrediction, AcceptNextWordEditPrediction,
301            NextEditPrediction, PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
302        };
303        let edit_prediction_actions = [
304            TypeId::of::<AcceptEditPrediction>(),
305            TypeId::of::<AcceptNextWordEditPrediction>(),
306            TypeId::of::<AcceptNextLineEditPrediction>(),
307            TypeId::of::<AcceptEditPrediction>(),
308            TypeId::of::<ShowEditPrediction>(),
309            TypeId::of::<NextEditPrediction>(),
310            TypeId::of::<PreviousEditPrediction>(),
311            TypeId::of::<ToggleEditPrediction>(),
312        ];
313
314        if disable_ai {
315            filter.hide_namespace("agent");
316            filter.hide_namespace("agents");
317            filter.hide_namespace("assistant");
318            filter.hide_namespace("copilot");
319            filter.hide_namespace("supermaven");
320            filter.hide_namespace("zed_predict_onboarding");
321            filter.hide_namespace("edit_prediction");
322
323            filter.hide_action_types(&edit_prediction_actions);
324            filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
325        } else {
326            if agent_enabled {
327                filter.show_namespace("agent");
328                filter.show_namespace("agents");
329            } else {
330                filter.hide_namespace("agent");
331                filter.hide_namespace("agents");
332            }
333
334            filter.show_namespace("assistant");
335
336            match edit_prediction_provider {
337                EditPredictionProvider::None => {
338                    filter.hide_namespace("edit_prediction");
339                    filter.hide_namespace("copilot");
340                    filter.hide_namespace("supermaven");
341                    filter.hide_action_types(&edit_prediction_actions);
342                }
343                EditPredictionProvider::Copilot => {
344                    filter.show_namespace("edit_prediction");
345                    filter.show_namespace("copilot");
346                    filter.hide_namespace("supermaven");
347                    filter.show_action_types(edit_prediction_actions.iter());
348                }
349                EditPredictionProvider::Supermaven => {
350                    filter.show_namespace("edit_prediction");
351                    filter.hide_namespace("copilot");
352                    filter.show_namespace("supermaven");
353                    filter.show_action_types(edit_prediction_actions.iter());
354                }
355                EditPredictionProvider::Zed
356                | EditPredictionProvider::Codestral
357                | EditPredictionProvider::Experimental(_) => {
358                    filter.show_namespace("edit_prediction");
359                    filter.hide_namespace("copilot");
360                    filter.hide_namespace("supermaven");
361                    filter.show_action_types(edit_prediction_actions.iter());
362                }
363            }
364
365            filter.show_namespace("zed_predict_onboarding");
366            filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
367            if !agent_v2_enabled {
368                filter.hide_action_types(&[TypeId::of::<zed_actions::agent::ToggleAgentPane>()]);
369            }
370        }
371    });
372}
373
374fn init_language_model_settings(cx: &mut App) {
375    update_active_language_model_from_settings(cx);
376
377    cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
378        .detach();
379    cx.subscribe(
380        &LanguageModelRegistry::global(cx),
381        |_, event: &language_model::Event, cx| match event {
382            language_model::Event::ProviderStateChanged(_)
383            | language_model::Event::AddedProvider(_)
384            | language_model::Event::RemovedProvider(_)
385            | language_model::Event::ProvidersChanged => {
386                update_active_language_model_from_settings(cx);
387            }
388            _ => {}
389        },
390    )
391    .detach();
392}
393
394fn update_active_language_model_from_settings(cx: &mut App) {
395    let settings = AgentSettings::get_global(cx);
396
397    fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
398        language_model::SelectedModel {
399            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
400            model: LanguageModelId::from(selection.model.clone()),
401        }
402    }
403
404    let default = settings.default_model.as_ref().map(to_selected_model);
405    let inline_assistant = settings
406        .inline_assistant_model
407        .as_ref()
408        .map(to_selected_model);
409    let commit_message = settings
410        .commit_message_model
411        .as_ref()
412        .map(to_selected_model);
413    let thread_summary = settings
414        .thread_summary_model
415        .as_ref()
416        .map(to_selected_model);
417    let inline_alternatives = settings
418        .inline_alternatives
419        .iter()
420        .map(to_selected_model)
421        .collect::<Vec<_>>();
422
423    LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
424        registry.select_default_model(default.as_ref(), cx);
425        registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
426        registry.select_commit_message_model(commit_message.as_ref(), cx);
427        registry.select_thread_summary_model(thread_summary.as_ref(), cx);
428        registry.select_inline_alternative_models(inline_alternatives, cx);
429    });
430}
431
432fn register_slash_commands(cx: &mut App) {
433    let slash_command_registry = SlashCommandRegistry::global(cx);
434
435    slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
436    slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
437    slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
438    slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
439    slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
440    slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
441    slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
442    slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
443    slash_command_registry
444        .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
445    slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
446
447    cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
448        move |is_enabled, _cx| {
449            if is_enabled {
450                slash_command_registry.register_command(
451                    assistant_slash_commands::StreamingExampleSlashCommand,
452                    false,
453                );
454            }
455        }
456    })
457    .detach();
458}
459
460#[cfg(test)]
461mod tests {
462    use super::*;
463    use agent_settings::{AgentProfileId, AgentSettings, CompletionMode};
464    use command_palette_hooks::CommandPaletteFilter;
465    use editor::actions::AcceptEditPrediction;
466    use gpui::{BorrowAppContext, TestAppContext, px};
467    use project::DisableAiSettings;
468    use settings::{
469        DefaultAgentView, DockPosition, DockSide, NotifyWhenAgentWaiting, Settings, SettingsStore,
470    };
471
472    #[gpui::test]
473    fn test_agent_command_palette_visibility(cx: &mut TestAppContext) {
474        // Init settings
475        cx.update(|cx| {
476            let store = SettingsStore::test(cx);
477            cx.set_global(store);
478            command_palette_hooks::init(cx);
479            AgentSettings::register(cx);
480            DisableAiSettings::register(cx);
481            AllLanguageSettings::register(cx);
482        });
483
484        let agent_settings = AgentSettings {
485            enabled: true,
486            button: true,
487            dock: DockPosition::Right,
488            agents_panel_dock: DockSide::Left,
489            default_width: px(300.),
490            default_height: px(600.),
491            default_model: None,
492            inline_assistant_model: None,
493            inline_assistant_use_streaming_tools: false,
494            commit_message_model: None,
495            thread_summary_model: None,
496            inline_alternatives: vec![],
497            favorite_models: vec![],
498            default_profile: AgentProfileId::default(),
499            default_view: DefaultAgentView::Thread,
500            profiles: Default::default(),
501            always_allow_tool_actions: false,
502            notify_when_agent_waiting: NotifyWhenAgentWaiting::default(),
503            play_sound_when_agent_done: false,
504            single_file_review: false,
505            model_parameters: vec![],
506            preferred_completion_mode: CompletionMode::Normal,
507            enable_feedback: false,
508            expand_edit_card: true,
509            expand_terminal_card: true,
510            use_modifier_to_send: true,
511            message_editor_min_lines: 1,
512            tool_permissions: Default::default(),
513            show_turn_stats: false,
514        };
515
516        cx.update(|cx| {
517            AgentSettings::override_global(agent_settings.clone(), cx);
518            DisableAiSettings::override_global(DisableAiSettings { disable_ai: false }, cx);
519
520            // Initial update
521            update_command_palette_filter(cx);
522        });
523
524        // Assert visible
525        cx.update(|cx| {
526            let filter = CommandPaletteFilter::try_global(cx).unwrap();
527            assert!(
528                !filter.is_hidden(&NewThread),
529                "NewThread should be visible by default"
530            );
531        });
532
533        // Disable agent
534        cx.update(|cx| {
535            let mut new_settings = agent_settings.clone();
536            new_settings.enabled = false;
537            AgentSettings::override_global(new_settings, cx);
538
539            // Trigger update
540            update_command_palette_filter(cx);
541        });
542
543        // Assert hidden
544        cx.update(|cx| {
545            let filter = CommandPaletteFilter::try_global(cx).unwrap();
546            assert!(
547                filter.is_hidden(&NewThread),
548                "NewThread should be hidden when agent is disabled"
549            );
550        });
551
552        // Test EditPredictionProvider
553        // Enable EditPredictionProvider::Copilot
554        cx.update(|cx| {
555            cx.update_global::<SettingsStore, _>(|store, cx| {
556                store.update_user_settings(cx, |s| {
557                    s.project
558                        .all_languages
559                        .features
560                        .get_or_insert(Default::default())
561                        .edit_prediction_provider = Some(EditPredictionProvider::Copilot);
562                });
563            });
564            update_command_palette_filter(cx);
565        });
566
567        cx.update(|cx| {
568            let filter = CommandPaletteFilter::try_global(cx).unwrap();
569            assert!(
570                !filter.is_hidden(&AcceptEditPrediction),
571                "EditPrediction should be visible when provider is Copilot"
572            );
573        });
574
575        // Disable EditPredictionProvider (None)
576        cx.update(|cx| {
577            cx.update_global::<SettingsStore, _>(|store, cx| {
578                store.update_user_settings(cx, |s| {
579                    s.project
580                        .all_languages
581                        .features
582                        .get_or_insert(Default::default())
583                        .edit_prediction_provider = Some(EditPredictionProvider::None);
584                });
585            });
586            update_command_palette_filter(cx);
587        });
588
589        cx.update(|cx| {
590            let filter = CommandPaletteFilter::try_global(cx).unwrap();
591            assert!(
592                filter.is_hidden(&AcceptEditPrediction),
593                "EditPrediction should be hidden when provider is None"
594            );
595        });
596    }
597}