agent_ui.rs

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