agent_ui.rs

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