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