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