agent_ui.rs

  1mod agent_configuration;
  2pub(crate) mod agent_connection_store;
  3mod agent_diff;
  4mod agent_model_selector;
  5mod agent_panel;
  6mod agent_registry_ui;
  7mod branch_names;
  8mod buffer_codegen;
  9mod completion_provider;
 10mod config_options;
 11pub(crate) mod connection_view;
 12mod context;
 13mod context_server_configuration;
 14mod entry_view_state;
 15mod external_source_prompt;
 16mod favorite_models;
 17mod inline_assistant;
 18mod inline_prompt_editor;
 19mod language_model_selector;
 20mod mention_set;
 21mod message_editor;
 22mod mode_selector;
 23mod model_selector;
 24mod model_selector_popover;
 25mod profile_selector;
 26pub mod sidebar;
 27mod slash_command;
 28mod slash_command_picker;
 29mod terminal_codegen;
 30mod terminal_inline_assistant;
 31#[cfg(any(test, feature = "test-support"))]
 32pub mod test_support;
 33mod text_thread_editor;
 34mod text_thread_history;
 35mod thread_history;
 36mod ui;
 37
 38use std::rc::Rc;
 39use std::sync::Arc;
 40
 41use agent_client_protocol as acp;
 42use agent_settings::{AgentProfileId, AgentSettings};
 43use assistant_slash_command::SlashCommandRegistry;
 44use client::Client;
 45use command_palette_hooks::CommandPaletteFilter;
 46use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt as _};
 47use fs::Fs;
 48use gpui::{Action, App, Context, Entity, SharedString, Window, actions};
 49use language::{
 50    LanguageRegistry,
 51    language_settings::{AllLanguageSettings, EditPredictionProvider},
 52};
 53use language_model::{
 54    ConfiguredModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
 55};
 56use project::DisableAiSettings;
 57use prompt_store::PromptBuilder;
 58use schemars::JsonSchema;
 59use serde::{Deserialize, Serialize};
 60use settings::{LanguageModelSelection, Settings as _, SettingsStore};
 61use std::any::TypeId;
 62use workspace::Workspace;
 63
 64use crate::agent_configuration::{ConfigureContextServerModal, ManageProfilesModal};
 65pub use crate::agent_panel::{
 66    AgentPanel, AgentPanelEvent, ConcreteAssistantPanelDelegate, WorktreeCreationStatus,
 67};
 68use crate::agent_registry_ui::AgentRegistryPage;
 69pub use crate::inline_assistant::InlineAssistant;
 70pub use agent_diff::{AgentDiffPane, AgentDiffToolbar};
 71pub(crate) use connection_view::ConnectionView;
 72pub use external_source_prompt::ExternalSourcePrompt;
 73pub(crate) use mode_selector::ModeSelector;
 74pub(crate) use model_selector::ModelSelector;
 75pub(crate) use model_selector_popover::ModelSelectorPopover;
 76pub use text_thread_editor::{AgentPanelDelegate, TextThreadEditor};
 77pub(crate) use thread_history::*;
 78use zed_actions;
 79
 80actions!(
 81    agent,
 82    [
 83        /// Creates a new text-based conversation thread.
 84        NewTextThread,
 85        /// Toggles the menu to create new agent threads.
 86        ToggleNewThreadMenu,
 87        /// Toggles the selector for choosing where new threads start (current project or new worktree).
 88        ToggleStartThreadInSelector,
 89        /// Toggles the navigation menu for switching between threads and views.
 90        ToggleNavigationMenu,
 91        /// Toggles the options menu for agent settings and preferences.
 92        ToggleOptionsMenu,
 93        /// Toggles the profile or mode selector for switching between agent profiles.
 94        ToggleProfileSelector,
 95        /// Cycles through available session modes.
 96        CycleModeSelector,
 97        /// Cycles through favorited models in the ACP model selector.
 98        CycleFavoriteModels,
 99        /// Expands the message editor to full size.
100        ExpandMessageEditor,
101        /// Removes all thread history.
102        RemoveHistory,
103        /// Opens the conversation history view.
104        OpenHistory,
105        /// Adds a context server to the configuration.
106        AddContextServer,
107        /// Removes the currently selected thread.
108        RemoveSelectedThread,
109        /// Starts a chat conversation with follow-up enabled.
110        ChatWithFollow,
111        /// Cycles to the next inline assist suggestion.
112        CycleNextInlineAssist,
113        /// Cycles to the previous inline assist suggestion.
114        CyclePreviousInlineAssist,
115        /// Moves focus up in the interface.
116        FocusUp,
117        /// Moves focus down in the interface.
118        FocusDown,
119        /// Moves focus left in the interface.
120        FocusLeft,
121        /// Moves focus right in the interface.
122        FocusRight,
123        /// Opens the active thread as a markdown file.
124        OpenActiveThreadAsMarkdown,
125        /// Opens the agent diff view to review changes.
126        OpenAgentDiff,
127        /// Copies the current thread to the clipboard as JSON for debugging.
128        CopyThreadToClipboard,
129        /// Loads a thread from the clipboard JSON for debugging.
130        LoadThreadFromClipboard,
131        /// Keeps the current suggestion or change.
132        Keep,
133        /// Rejects the current suggestion or change.
134        Reject,
135        /// Rejects all suggestions or changes.
136        RejectAll,
137        /// Undoes the most recent reject operation, restoring the rejected changes.
138        UndoLastReject,
139        /// Keeps all suggestions or changes.
140        KeepAll,
141        /// Allow this operation only this time.
142        AllowOnce,
143        /// Allow this operation and remember the choice.
144        AllowAlways,
145        /// Reject this operation only this time.
146        RejectOnce,
147        /// Follows the agent's suggestions.
148        Follow,
149        /// Resets the trial upsell notification.
150        ResetTrialUpsell,
151        /// Resets the trial end upsell notification.
152        ResetTrialEndUpsell,
153        /// Opens the "Add Context" menu in the message editor.
154        OpenAddContextMenu,
155        /// Continues the current thread.
156        ContinueThread,
157        /// Interrupts the current generation and sends the message immediately.
158        SendImmediately,
159        /// Sends the next queued message immediately.
160        SendNextQueuedMessage,
161        /// Removes the first message from the queue (the next one to be sent).
162        RemoveFirstQueuedMessage,
163        /// Edits the first message in the queue (the next one to be sent).
164        EditFirstQueuedMessage,
165        /// Clears all messages from the queue.
166        ClearMessageQueue,
167        /// Opens the permission granularity dropdown for the current tool call.
168        OpenPermissionDropdown,
169        /// Toggles thinking mode for models that support extended thinking.
170        ToggleThinkingMode,
171        /// Cycles through available thinking effort levels for the current model.
172        CycleThinkingEffort,
173        /// Toggles the thinking effort selector menu open or closed.
174        ToggleThinkingEffortMenu,
175        /// Toggles fast mode for models that support it.
176        ToggleFastMode,
177    ]
178);
179
180/// Action to authorize a tool call with a specific permission option.
181/// This is used by the permission granularity dropdown to authorize tool calls.
182#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
183#[action(namespace = agent)]
184#[serde(deny_unknown_fields)]
185pub struct AuthorizeToolCall {
186    /// The tool call ID to authorize.
187    pub tool_call_id: String,
188    /// The permission option ID to use.
189    pub option_id: String,
190    /// The kind of permission option (serialized as string).
191    pub option_kind: String,
192}
193
194/// Creates a new conversation thread, optionally based on an existing thread.
195#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
196#[action(namespace = agent)]
197#[serde(deny_unknown_fields)]
198pub struct NewThread;
199
200/// Creates a new external agent conversation thread.
201#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
202#[action(namespace = agent)]
203#[serde(deny_unknown_fields)]
204pub struct NewExternalAgentThread {
205    /// Which agent to use for the conversation.
206    agent: Option<ExternalAgent>,
207}
208
209#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
210#[action(namespace = agent)]
211#[serde(deny_unknown_fields)]
212pub struct NewNativeAgentThreadFromSummary {
213    from_session_id: agent_client_protocol::SessionId,
214}
215
216// TODO unify this with AgentType
217#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, JsonSchema)]
218#[serde(rename_all = "snake_case")]
219pub enum ExternalAgent {
220    NativeAgent,
221    Custom { name: SharedString },
222}
223
224// Custom impl handles legacy variant names from before the built-in agents were moved to
225// the registry: "claude_code" -> Custom { name: "claude-acp" }, "codex" -> Custom { name:
226// "codex-acp" }, "gemini" -> Custom { name: "gemini" }.
227// Can be removed at some point in the future and go back to #[derive(Deserialize)].
228impl<'de> serde::Deserialize<'de> for ExternalAgent {
229    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
230    where
231        D: serde::Deserializer<'de>,
232    {
233        use project::agent_server_store::{CLAUDE_AGENT_NAME, CODEX_NAME, GEMINI_NAME};
234
235        let value = serde_json::Value::deserialize(deserializer)?;
236
237        if let Some(s) = value.as_str() {
238            return match s {
239                "native_agent" => Ok(Self::NativeAgent),
240                "claude_code" | "claude_agent" => Ok(Self::Custom {
241                    name: CLAUDE_AGENT_NAME.into(),
242                }),
243                "codex" => Ok(Self::Custom {
244                    name: CODEX_NAME.into(),
245                }),
246                "gemini" => Ok(Self::Custom {
247                    name: GEMINI_NAME.into(),
248                }),
249                other => Err(serde::de::Error::unknown_variant(
250                    other,
251                    &[
252                        "native_agent",
253                        "custom",
254                        "claude_agent",
255                        "claude_code",
256                        "codex",
257                        "gemini",
258                    ],
259                )),
260            };
261        }
262
263        if let Some(obj) = value.as_object() {
264            if let Some(inner) = obj.get("custom") {
265                #[derive(serde::Deserialize)]
266                struct CustomFields {
267                    name: SharedString,
268                }
269                let fields: CustomFields =
270                    serde_json::from_value(inner.clone()).map_err(serde::de::Error::custom)?;
271                return Ok(Self::Custom { name: fields.name });
272            }
273        }
274
275        Err(serde::de::Error::custom(
276            "expected a string variant or {\"custom\": {\"name\": ...}}",
277        ))
278    }
279}
280
281impl ExternalAgent {
282    pub fn server(
283        &self,
284        fs: Arc<dyn fs::Fs>,
285        thread_store: Entity<agent::ThreadStore>,
286    ) -> Rc<dyn agent_servers::AgentServer> {
287        match self {
288            Self::NativeAgent => Rc::new(agent::NativeAgentServer::new(fs, thread_store)),
289            Self::Custom { name } => Rc::new(agent_servers::CustomAgentServer::new(name.clone())),
290        }
291    }
292}
293
294/// Sets where new threads will run.
295#[derive(
296    Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Action,
297)]
298#[action(namespace = agent)]
299#[serde(rename_all = "snake_case", tag = "kind")]
300pub enum StartThreadIn {
301    #[default]
302    LocalProject,
303    NewWorktree,
304}
305
306/// Content to initialize new external agent with.
307pub enum AgentInitialContent {
308    ThreadSummary {
309        session_id: acp::SessionId,
310        title: Option<SharedString>,
311    },
312    ContentBlock {
313        blocks: Vec<agent_client_protocol::ContentBlock>,
314        auto_submit: bool,
315    },
316    FromExternalSource(ExternalSourcePrompt),
317}
318
319impl From<ExternalSourcePrompt> for AgentInitialContent {
320    fn from(prompt: ExternalSourcePrompt) -> Self {
321        Self::FromExternalSource(prompt)
322    }
323}
324
325/// Opens the profile management interface for configuring agent tools and settings.
326#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
327#[action(namespace = agent)]
328#[serde(deny_unknown_fields)]
329pub struct ManageProfiles {
330    #[serde(default)]
331    pub customize_tools: Option<AgentProfileId>,
332}
333
334impl ManageProfiles {
335    pub fn customize_tools(profile_id: AgentProfileId) -> Self {
336        Self {
337            customize_tools: Some(profile_id),
338        }
339    }
340}
341
342#[derive(Clone)]
343pub(crate) enum ModelUsageContext {
344    InlineAssistant,
345}
346
347impl ModelUsageContext {
348    pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
349        match self {
350            Self::InlineAssistant => {
351                LanguageModelRegistry::read_global(cx).inline_assistant_model()
352            }
353        }
354    }
355}
356
357/// Initializes the `agent` crate.
358pub fn init(
359    fs: Arc<dyn Fs>,
360    client: Arc<Client>,
361    prompt_builder: Arc<PromptBuilder>,
362    language_registry: Arc<LanguageRegistry>,
363    is_eval: bool,
364    cx: &mut App,
365) {
366    agent::ThreadStore::init_global(cx);
367    assistant_text_thread::init(client, cx);
368    rules_library::init(cx);
369    if !is_eval {
370        // Initializing the language model from the user settings messes with the eval, so we only initialize them when
371        // we're not running inside of the eval.
372        init_language_model_settings(cx);
373    }
374    assistant_slash_command::init(cx);
375    agent_panel::init(cx);
376    context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
377    TextThreadEditor::init(cx);
378
379    register_slash_commands(cx);
380    inline_assistant::init(fs.clone(), prompt_builder.clone(), cx);
381    terminal_inline_assistant::init(fs.clone(), prompt_builder, cx);
382    cx.observe_new(move |workspace, window, cx| {
383        ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
384    })
385    .detach();
386    cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
387        workspace.register_action(
388            move |workspace: &mut Workspace,
389                  _: &zed_actions::AcpRegistry,
390                  window: &mut Window,
391                  cx: &mut Context<Workspace>| {
392                let existing = workspace
393                    .active_pane()
394                    .read(cx)
395                    .items()
396                    .find_map(|item| item.downcast::<AgentRegistryPage>());
397
398                if let Some(existing) = existing {
399                    existing.update(cx, |_, cx| {
400                        project::AgentRegistryStore::global(cx)
401                            .update(cx, |store, cx| store.refresh(cx));
402                    });
403                    workspace.activate_item(&existing, true, true, window, cx);
404                } else {
405                    let registry_page = AgentRegistryPage::new(workspace, window, cx);
406                    workspace.add_item_to_active_pane(
407                        Box::new(registry_page),
408                        None,
409                        true,
410                        window,
411                        cx,
412                    );
413                }
414            },
415        );
416    })
417    .detach();
418    cx.observe_new(ManageProfilesModal::register).detach();
419
420    // Update command palette filter based on AI settings
421    update_command_palette_filter(cx);
422
423    // Watch for settings changes
424    cx.observe_global::<SettingsStore>(|app_cx| {
425        // When settings change, update the command palette filter
426        update_command_palette_filter(app_cx);
427    })
428    .detach();
429
430    cx.on_flags_ready(|_, cx| {
431        update_command_palette_filter(cx);
432    })
433    .detach();
434}
435
436fn update_command_palette_filter(cx: &mut App) {
437    let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
438    let agent_enabled = AgentSettings::get_global(cx).enabled;
439    let agent_v2_enabled = cx.has_flag::<AgentV2FeatureFlag>();
440    let edit_prediction_provider = AllLanguageSettings::get_global(cx)
441        .edit_predictions
442        .provider;
443
444    CommandPaletteFilter::update_global(cx, |filter, _| {
445        use editor::actions::{
446            AcceptEditPrediction, AcceptNextLineEditPrediction, AcceptNextWordEditPrediction,
447            NextEditPrediction, PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
448        };
449        let edit_prediction_actions = [
450            TypeId::of::<AcceptEditPrediction>(),
451            TypeId::of::<AcceptNextWordEditPrediction>(),
452            TypeId::of::<AcceptNextLineEditPrediction>(),
453            TypeId::of::<AcceptEditPrediction>(),
454            TypeId::of::<ShowEditPrediction>(),
455            TypeId::of::<NextEditPrediction>(),
456            TypeId::of::<PreviousEditPrediction>(),
457            TypeId::of::<ToggleEditPrediction>(),
458        ];
459
460        if disable_ai {
461            filter.hide_namespace("agent");
462            filter.hide_namespace("agents");
463            filter.hide_namespace("assistant");
464            filter.hide_namespace("copilot");
465            filter.hide_namespace("zed_predict_onboarding");
466            filter.hide_namespace("edit_prediction");
467
468            filter.hide_action_types(&edit_prediction_actions);
469            filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
470        } else {
471            if agent_enabled {
472                filter.show_namespace("agent");
473                filter.show_namespace("agents");
474                filter.show_namespace("assistant");
475            } else {
476                filter.hide_namespace("agent");
477                filter.hide_namespace("agents");
478                filter.hide_namespace("assistant");
479            }
480
481            match edit_prediction_provider {
482                EditPredictionProvider::None => {
483                    filter.hide_namespace("edit_prediction");
484                    filter.hide_namespace("copilot");
485                    filter.hide_action_types(&edit_prediction_actions);
486                }
487                EditPredictionProvider::Copilot => {
488                    filter.show_namespace("edit_prediction");
489                    filter.show_namespace("copilot");
490                    filter.show_action_types(edit_prediction_actions.iter());
491                }
492                EditPredictionProvider::Zed
493                | EditPredictionProvider::Codestral
494                | EditPredictionProvider::Ollama
495                | EditPredictionProvider::OpenAiCompatibleApi
496                | EditPredictionProvider::Sweep
497                | EditPredictionProvider::Mercury
498                | EditPredictionProvider::Experimental(_) => {
499                    filter.show_namespace("edit_prediction");
500                    filter.hide_namespace("copilot");
501                    filter.show_action_types(edit_prediction_actions.iter());
502                }
503            }
504
505            filter.show_namespace("zed_predict_onboarding");
506            filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
507        }
508
509        if agent_v2_enabled {
510            filter.show_namespace("multi_workspace");
511        } else {
512            filter.hide_namespace("multi_workspace");
513        }
514    });
515}
516
517fn init_language_model_settings(cx: &mut App) {
518    update_active_language_model_from_settings(cx);
519
520    cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
521        .detach();
522    cx.subscribe(
523        &LanguageModelRegistry::global(cx),
524        |_, event: &language_model::Event, cx| match event {
525            language_model::Event::ProviderStateChanged(_)
526            | language_model::Event::AddedProvider(_)
527            | language_model::Event::RemovedProvider(_)
528            | language_model::Event::ProvidersChanged => {
529                update_active_language_model_from_settings(cx);
530            }
531            _ => {}
532        },
533    )
534    .detach();
535}
536
537fn update_active_language_model_from_settings(cx: &mut App) {
538    let settings = AgentSettings::get_global(cx);
539
540    fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
541        language_model::SelectedModel {
542            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
543            model: LanguageModelId::from(selection.model.clone()),
544        }
545    }
546
547    let default = settings.default_model.as_ref().map(to_selected_model);
548    let inline_assistant = settings
549        .inline_assistant_model
550        .as_ref()
551        .map(to_selected_model);
552    let commit_message = settings
553        .commit_message_model
554        .as_ref()
555        .map(to_selected_model);
556    let thread_summary = settings
557        .thread_summary_model
558        .as_ref()
559        .map(to_selected_model);
560    let inline_alternatives = settings
561        .inline_alternatives
562        .iter()
563        .map(to_selected_model)
564        .collect::<Vec<_>>();
565
566    LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
567        registry.select_default_model(default.as_ref(), cx);
568        registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
569        registry.select_commit_message_model(commit_message.as_ref(), cx);
570        registry.select_thread_summary_model(thread_summary.as_ref(), cx);
571        registry.select_inline_alternative_models(inline_alternatives, cx);
572    });
573}
574
575fn register_slash_commands(cx: &mut App) {
576    let slash_command_registry = SlashCommandRegistry::global(cx);
577
578    slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
579    slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
580    slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
581    slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
582    slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
583    slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
584    slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
585    slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
586    slash_command_registry
587        .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
588    slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
589
590    cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
591        move |is_enabled, _cx| {
592            if is_enabled {
593                slash_command_registry.register_command(
594                    assistant_slash_commands::StreamingExampleSlashCommand,
595                    false,
596                );
597            }
598        }
599    })
600    .detach();
601}
602
603#[cfg(test)]
604mod tests {
605    use super::*;
606    use agent_settings::{AgentProfileId, AgentSettings};
607    use command_palette_hooks::CommandPaletteFilter;
608    use editor::actions::AcceptEditPrediction;
609    use gpui::{BorrowAppContext, TestAppContext, px};
610    use project::DisableAiSettings;
611    use settings::{
612        DefaultAgentView, DockPosition, NotifyWhenAgentWaiting, Settings, SettingsStore,
613    };
614
615    #[gpui::test]
616    fn test_agent_command_palette_visibility(cx: &mut TestAppContext) {
617        // Init settings
618        cx.update(|cx| {
619            let store = SettingsStore::test(cx);
620            cx.set_global(store);
621            command_palette_hooks::init(cx);
622            AgentSettings::register(cx);
623            DisableAiSettings::register(cx);
624            AllLanguageSettings::register(cx);
625        });
626
627        let agent_settings = AgentSettings {
628            enabled: true,
629            button: true,
630            dock: DockPosition::Right,
631            default_width: px(300.),
632            default_height: px(600.),
633            default_model: None,
634            inline_assistant_model: None,
635            inline_assistant_use_streaming_tools: false,
636            commit_message_model: None,
637            thread_summary_model: None,
638            inline_alternatives: vec![],
639            favorite_models: vec![],
640            default_profile: AgentProfileId::default(),
641            default_view: DefaultAgentView::Thread,
642            profiles: Default::default(),
643
644            notify_when_agent_waiting: NotifyWhenAgentWaiting::default(),
645            play_sound_when_agent_done: false,
646            single_file_review: false,
647            model_parameters: vec![],
648            enable_feedback: false,
649            expand_edit_card: true,
650            expand_terminal_card: true,
651            cancel_generation_on_terminal_stop: true,
652            use_modifier_to_send: true,
653            message_editor_min_lines: 1,
654            tool_permissions: Default::default(),
655            show_turn_stats: false,
656        };
657
658        cx.update(|cx| {
659            AgentSettings::override_global(agent_settings.clone(), cx);
660            DisableAiSettings::override_global(DisableAiSettings { disable_ai: false }, cx);
661
662            // Initial update
663            update_command_palette_filter(cx);
664        });
665
666        // Assert visible
667        cx.update(|cx| {
668            let filter = CommandPaletteFilter::try_global(cx).unwrap();
669            assert!(
670                !filter.is_hidden(&NewThread),
671                "NewThread should be visible by default"
672            );
673            assert!(
674                !filter.is_hidden(&text_thread_editor::CopyCode),
675                "CopyCode should be visible when agent is enabled"
676            );
677        });
678
679        // Disable agent
680        cx.update(|cx| {
681            let mut new_settings = agent_settings.clone();
682            new_settings.enabled = false;
683            AgentSettings::override_global(new_settings, cx);
684
685            // Trigger update
686            update_command_palette_filter(cx);
687        });
688
689        // Assert hidden
690        cx.update(|cx| {
691            let filter = CommandPaletteFilter::try_global(cx).unwrap();
692            assert!(
693                filter.is_hidden(&NewThread),
694                "NewThread should be hidden when agent is disabled"
695            );
696            assert!(
697                filter.is_hidden(&text_thread_editor::CopyCode),
698                "CopyCode should be hidden when agent is disabled"
699            );
700        });
701
702        // Test EditPredictionProvider
703        // Enable EditPredictionProvider::Copilot
704        cx.update(|cx| {
705            cx.update_global::<SettingsStore, _>(|store, cx| {
706                store.update_user_settings(cx, |s| {
707                    s.project
708                        .all_languages
709                        .edit_predictions
710                        .get_or_insert(Default::default())
711                        .provider = Some(EditPredictionProvider::Copilot);
712                });
713            });
714            update_command_palette_filter(cx);
715        });
716
717        cx.update(|cx| {
718            let filter = CommandPaletteFilter::try_global(cx).unwrap();
719            assert!(
720                !filter.is_hidden(&AcceptEditPrediction),
721                "EditPrediction should be visible when provider is Copilot"
722            );
723        });
724
725        // Disable EditPredictionProvider (None)
726        cx.update(|cx| {
727            cx.update_global::<SettingsStore, _>(|store, cx| {
728                store.update_user_settings(cx, |s| {
729                    s.project
730                        .all_languages
731                        .edit_predictions
732                        .get_or_insert(Default::default())
733                        .provider = Some(EditPredictionProvider::None);
734                });
735            });
736            update_command_palette_filter(cx);
737        });
738
739        cx.update(|cx| {
740            let filter = CommandPaletteFilter::try_global(cx).unwrap();
741            assert!(
742                filter.is_hidden(&AcceptEditPrediction),
743                "EditPrediction should be hidden when provider is None"
744            );
745        });
746    }
747
748    #[test]
749    fn test_deserialize_legacy_external_agent_variants() {
750        use project::agent_server_store::{CLAUDE_AGENT_NAME, CODEX_NAME, GEMINI_NAME};
751
752        assert_eq!(
753            serde_json::from_str::<ExternalAgent>(r#""claude_code""#).unwrap(),
754            ExternalAgent::Custom {
755                name: CLAUDE_AGENT_NAME.into(),
756            },
757        );
758        assert_eq!(
759            serde_json::from_str::<ExternalAgent>(r#""codex""#).unwrap(),
760            ExternalAgent::Custom {
761                name: CODEX_NAME.into(),
762            },
763        );
764        assert_eq!(
765            serde_json::from_str::<ExternalAgent>(r#""gemini""#).unwrap(),
766            ExternalAgent::Custom {
767                name: GEMINI_NAME.into(),
768            },
769        );
770    }
771
772    #[test]
773    fn test_deserialize_current_external_agent_variants() {
774        assert_eq!(
775            serde_json::from_str::<ExternalAgent>(r#""native_agent""#).unwrap(),
776            ExternalAgent::NativeAgent,
777        );
778        assert_eq!(
779            serde_json::from_str::<ExternalAgent>(r#"{"custom":{"name":"my-agent"}}"#).unwrap(),
780            ExternalAgent::Custom {
781                name: "my-agent".into(),
782            },
783        );
784    }
785}