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