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