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, UpdateGlobal, 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::{DockPosition, DockSide, 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        /// Scroll the output by one page up.
183        ScrollOutputPageUp,
184        /// Scroll the output by one page down.
185        ScrollOutputPageDown,
186    ]
187);
188
189/// Action to authorize a tool call with a specific permission option.
190/// This is used by the permission granularity dropdown to authorize tool calls.
191#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
192#[action(namespace = agent)]
193#[serde(deny_unknown_fields)]
194pub struct AuthorizeToolCall {
195    /// The tool call ID to authorize.
196    pub tool_call_id: String,
197    /// The permission option ID to use.
198    pub option_id: String,
199    /// The kind of permission option (serialized as string).
200    pub option_kind: String,
201}
202
203/// Action to select a permission granularity option from the dropdown.
204/// This updates the selected granularity without triggering authorization.
205#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
206#[action(namespace = agent)]
207#[serde(deny_unknown_fields)]
208pub struct SelectPermissionGranularity {
209    /// The tool call ID for which to select the granularity.
210    pub tool_call_id: String,
211    /// The index of the selected granularity option.
212    pub index: usize,
213}
214
215/// Action to toggle a command pattern checkbox in the permission dropdown.
216#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
217#[action(namespace = agent)]
218#[serde(deny_unknown_fields)]
219pub struct ToggleCommandPattern {
220    /// The tool call ID for which to toggle the pattern.
221    pub tool_call_id: String,
222    /// The index of the command pattern to toggle.
223    pub pattern_index: usize,
224}
225
226/// Creates a new conversation thread, optionally based on an existing thread.
227#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
228#[action(namespace = agent)]
229#[serde(deny_unknown_fields)]
230pub struct NewThread;
231
232/// Creates a new external agent conversation thread.
233#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
234#[action(namespace = agent)]
235#[serde(deny_unknown_fields)]
236pub struct NewExternalAgentThread {
237    /// Which agent to use for the conversation.
238    agent: Option<Agent>,
239}
240
241#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
242#[action(namespace = agent)]
243#[serde(deny_unknown_fields)]
244pub struct NewNativeAgentThreadFromSummary {
245    from_session_id: agent_client_protocol::SessionId,
246}
247
248// TODO unify this with AgentType
249#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
250#[serde(rename_all = "snake_case")]
251pub enum Agent {
252    NativeAgent,
253    Custom {
254        #[serde(rename = "name")]
255        id: AgentId,
256    },
257}
258
259impl Agent {
260    pub fn id(&self) -> AgentId {
261        match self {
262            Self::NativeAgent => agent::ZED_AGENT_ID.clone(),
263            Self::Custom { id } => id.clone(),
264        }
265    }
266
267    pub fn server(
268        &self,
269        fs: Arc<dyn fs::Fs>,
270        thread_store: Entity<agent::ThreadStore>,
271    ) -> Rc<dyn agent_servers::AgentServer> {
272        match self {
273            Self::NativeAgent => Rc::new(agent::NativeAgentServer::new(fs, thread_store)),
274            Self::Custom { id: name } => {
275                Rc::new(agent_servers::CustomAgentServer::new(name.clone()))
276            }
277        }
278    }
279}
280
281/// Sets where new threads will run.
282#[derive(
283    Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Action,
284)]
285#[action(namespace = agent)]
286#[serde(rename_all = "snake_case", tag = "kind")]
287pub enum StartThreadIn {
288    #[default]
289    LocalProject,
290    NewWorktree,
291}
292
293/// Content to initialize new external agent with.
294pub enum AgentInitialContent {
295    ThreadSummary {
296        session_id: acp::SessionId,
297        title: Option<SharedString>,
298    },
299    ContentBlock {
300        blocks: Vec<agent_client_protocol::ContentBlock>,
301        auto_submit: bool,
302    },
303    FromExternalSource(ExternalSourcePrompt),
304}
305
306impl From<ExternalSourcePrompt> for AgentInitialContent {
307    fn from(prompt: ExternalSourcePrompt) -> Self {
308        Self::FromExternalSource(prompt)
309    }
310}
311
312/// Opens the profile management interface for configuring agent tools and settings.
313#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
314#[action(namespace = agent)]
315#[serde(deny_unknown_fields)]
316pub struct ManageProfiles {
317    #[serde(default)]
318    pub customize_tools: Option<AgentProfileId>,
319}
320
321impl ManageProfiles {
322    pub fn customize_tools(profile_id: AgentProfileId) -> Self {
323        Self {
324            customize_tools: Some(profile_id),
325        }
326    }
327}
328
329#[derive(Clone)]
330pub(crate) enum ModelUsageContext {
331    InlineAssistant,
332}
333
334impl ModelUsageContext {
335    pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
336        match self {
337            Self::InlineAssistant => {
338                LanguageModelRegistry::read_global(cx).inline_assistant_model()
339            }
340        }
341    }
342}
343
344/// Initializes the `agent` crate.
345pub fn init(
346    fs: Arc<dyn Fs>,
347    client: Arc<Client>,
348    prompt_builder: Arc<PromptBuilder>,
349    language_registry: Arc<LanguageRegistry>,
350    is_eval: bool,
351    cx: &mut App,
352) {
353    agent::ThreadStore::init_global(cx);
354    assistant_text_thread::init(client, cx);
355    rules_library::init(cx);
356    if !is_eval {
357        // Initializing the language model from the user settings messes with the eval, so we only initialize them when
358        // we're not running inside of the eval.
359        init_language_model_settings(cx);
360    }
361    assistant_slash_command::init(cx);
362    agent_panel::init(cx);
363    context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
364    TextThreadEditor::init(cx);
365    thread_metadata_store::init(cx);
366
367    register_slash_commands(cx);
368    inline_assistant::init(fs.clone(), prompt_builder.clone(), cx);
369    terminal_inline_assistant::init(fs.clone(), prompt_builder, cx);
370    cx.observe_new(move |workspace, window, cx| {
371        ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
372    })
373    .detach();
374    cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
375        workspace.register_action(
376            move |workspace: &mut Workspace,
377                  _: &zed_actions::AcpRegistry,
378                  window: &mut Window,
379                  cx: &mut Context<Workspace>| {
380                let existing = workspace
381                    .active_pane()
382                    .read(cx)
383                    .items()
384                    .find_map(|item| item.downcast::<AgentRegistryPage>());
385
386                if let Some(existing) = existing {
387                    existing.update(cx, |_, cx| {
388                        project::AgentRegistryStore::global(cx)
389                            .update(cx, |store, cx| store.refresh(cx));
390                    });
391                    workspace.activate_item(&existing, true, true, window, cx);
392                } else {
393                    let registry_page = AgentRegistryPage::new(workspace, window, cx);
394                    workspace.add_item_to_active_pane(
395                        Box::new(registry_page),
396                        None,
397                        true,
398                        window,
399                        cx,
400                    );
401                }
402            },
403        );
404    })
405    .detach();
406    cx.observe_new(ManageProfilesModal::register).detach();
407
408    // Update command palette filter based on AI settings
409    update_command_palette_filter(cx);
410
411    // Watch for settings changes
412    cx.observe_global::<SettingsStore>(|app_cx| {
413        // When settings change, update the command palette filter
414        update_command_palette_filter(app_cx);
415    })
416    .detach();
417
418    cx.on_flags_ready(|_, cx| {
419        update_command_palette_filter(cx);
420    })
421    .detach();
422
423    cx.observe_flag::<AgentV2FeatureFlag, _>(|is_enabled, cx| {
424        SettingsStore::update_global(cx, |store, cx| {
425            store.update_default_settings(cx, |defaults| {
426                if is_enabled {
427                    defaults.agent.get_or_insert_default().dock = Some(DockPosition::Left);
428                    defaults.project_panel.get_or_insert_default().dock = Some(DockSide::Right);
429                    defaults.outline_panel.get_or_insert_default().dock = Some(DockSide::Right);
430                    defaults.collaboration_panel.get_or_insert_default().dock =
431                        Some(DockPosition::Right);
432                    defaults.git_panel.get_or_insert_default().dock = Some(DockPosition::Right);
433                    defaults.notification_panel.get_or_insert_default().button = Some(false);
434                } else {
435                    defaults.agent.get_or_insert_default().dock = Some(DockPosition::Right);
436                    defaults.project_panel.get_or_insert_default().dock = Some(DockSide::Left);
437                    defaults.outline_panel.get_or_insert_default().dock = Some(DockSide::Left);
438                    defaults.collaboration_panel.get_or_insert_default().dock =
439                        Some(DockPosition::Left);
440                    defaults.git_panel.get_or_insert_default().dock = Some(DockPosition::Left);
441                    defaults.notification_panel.get_or_insert_default().button = Some(true);
442                }
443            });
444        });
445    })
446    .detach();
447}
448
449fn update_command_palette_filter(cx: &mut App) {
450    let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
451    let agent_enabled = AgentSettings::get_global(cx).enabled;
452    let agent_v2_enabled = cx.has_flag::<AgentV2FeatureFlag>();
453    let edit_prediction_provider = AllLanguageSettings::get_global(cx)
454        .edit_predictions
455        .provider;
456
457    CommandPaletteFilter::update_global(cx, |filter, _| {
458        use editor::actions::{
459            AcceptEditPrediction, AcceptNextLineEditPrediction, AcceptNextWordEditPrediction,
460            NextEditPrediction, PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
461        };
462        let edit_prediction_actions = [
463            TypeId::of::<AcceptEditPrediction>(),
464            TypeId::of::<AcceptNextWordEditPrediction>(),
465            TypeId::of::<AcceptNextLineEditPrediction>(),
466            TypeId::of::<AcceptEditPrediction>(),
467            TypeId::of::<ShowEditPrediction>(),
468            TypeId::of::<NextEditPrediction>(),
469            TypeId::of::<PreviousEditPrediction>(),
470            TypeId::of::<ToggleEditPrediction>(),
471        ];
472
473        if disable_ai {
474            filter.hide_namespace("agent");
475            filter.hide_namespace("agents");
476            filter.hide_namespace("assistant");
477            filter.hide_namespace("copilot");
478            filter.hide_namespace("zed_predict_onboarding");
479            filter.hide_namespace("edit_prediction");
480
481            filter.hide_action_types(&edit_prediction_actions);
482            filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
483        } else {
484            if agent_enabled {
485                filter.show_namespace("agent");
486                filter.show_namespace("agents");
487                filter.show_namespace("assistant");
488            } else {
489                filter.hide_namespace("agent");
490                filter.hide_namespace("agents");
491                filter.hide_namespace("assistant");
492            }
493
494            match edit_prediction_provider {
495                EditPredictionProvider::None => {
496                    filter.hide_namespace("edit_prediction");
497                    filter.hide_namespace("copilot");
498                    filter.hide_action_types(&edit_prediction_actions);
499                }
500                EditPredictionProvider::Copilot => {
501                    filter.show_namespace("edit_prediction");
502                    filter.show_namespace("copilot");
503                    filter.show_action_types(edit_prediction_actions.iter());
504                }
505                EditPredictionProvider::Zed
506                | EditPredictionProvider::Codestral
507                | EditPredictionProvider::Ollama
508                | EditPredictionProvider::OpenAiCompatibleApi
509                | EditPredictionProvider::Mercury
510                | EditPredictionProvider::Experimental(_) => {
511                    filter.show_namespace("edit_prediction");
512                    filter.hide_namespace("copilot");
513                    filter.show_action_types(edit_prediction_actions.iter());
514                }
515            }
516
517            filter.show_namespace("zed_predict_onboarding");
518            filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
519        }
520
521        if agent_v2_enabled {
522            filter.show_namespace("multi_workspace");
523        } else {
524            filter.hide_namespace("multi_workspace");
525        }
526    });
527}
528
529fn init_language_model_settings(cx: &mut App) {
530    update_active_language_model_from_settings(cx);
531
532    cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
533        .detach();
534    cx.subscribe(
535        &LanguageModelRegistry::global(cx),
536        |_, event: &language_model::Event, cx| match event {
537            language_model::Event::ProviderStateChanged(_)
538            | language_model::Event::AddedProvider(_)
539            | language_model::Event::RemovedProvider(_)
540            | language_model::Event::ProvidersChanged => {
541                update_active_language_model_from_settings(cx);
542            }
543            _ => {}
544        },
545    )
546    .detach();
547}
548
549fn update_active_language_model_from_settings(cx: &mut App) {
550    let settings = AgentSettings::get_global(cx);
551
552    fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
553        language_model::SelectedModel {
554            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
555            model: LanguageModelId::from(selection.model.clone()),
556        }
557    }
558
559    let default = settings.default_model.as_ref().map(to_selected_model);
560    let inline_assistant = settings
561        .inline_assistant_model
562        .as_ref()
563        .map(to_selected_model);
564    let commit_message = settings
565        .commit_message_model
566        .as_ref()
567        .map(to_selected_model);
568    let thread_summary = settings
569        .thread_summary_model
570        .as_ref()
571        .map(to_selected_model);
572    let inline_alternatives = settings
573        .inline_alternatives
574        .iter()
575        .map(to_selected_model)
576        .collect::<Vec<_>>();
577
578    LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
579        registry.select_default_model(default.as_ref(), cx);
580        registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
581        registry.select_commit_message_model(commit_message.as_ref(), cx);
582        registry.select_thread_summary_model(thread_summary.as_ref(), cx);
583        registry.select_inline_alternative_models(inline_alternatives, cx);
584    });
585}
586
587fn register_slash_commands(cx: &mut App) {
588    let slash_command_registry = SlashCommandRegistry::global(cx);
589
590    slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
591    slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
592    slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
593    slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
594    slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
595    slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
596    slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
597    slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
598    slash_command_registry
599        .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
600    slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
601
602    cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
603        move |is_enabled, _cx| {
604            if is_enabled {
605                slash_command_registry.register_command(
606                    assistant_slash_commands::StreamingExampleSlashCommand,
607                    false,
608                );
609            }
610        }
611    })
612    .detach();
613}
614
615#[cfg(test)]
616mod tests {
617    use super::*;
618    use agent_settings::{AgentProfileId, AgentSettings};
619    use command_palette_hooks::CommandPaletteFilter;
620    use editor::actions::AcceptEditPrediction;
621    use gpui::{BorrowAppContext, TestAppContext, px};
622    use project::DisableAiSettings;
623    use settings::{
624        DefaultAgentView, DockPosition, NotifyWhenAgentWaiting, Settings, SettingsStore,
625    };
626
627    #[gpui::test]
628    fn test_agent_command_palette_visibility(cx: &mut TestAppContext) {
629        // Init settings
630        cx.update(|cx| {
631            let store = SettingsStore::test(cx);
632            cx.set_global(store);
633            command_palette_hooks::init(cx);
634            AgentSettings::register(cx);
635            DisableAiSettings::register(cx);
636            AllLanguageSettings::register(cx);
637        });
638
639        let agent_settings = AgentSettings {
640            enabled: true,
641            button: true,
642            dock: DockPosition::Right,
643            default_width: px(300.),
644            default_height: px(600.),
645            default_model: None,
646            inline_assistant_model: None,
647            inline_assistant_use_streaming_tools: false,
648            commit_message_model: None,
649            thread_summary_model: None,
650            inline_alternatives: vec![],
651            favorite_models: vec![],
652            default_profile: AgentProfileId::default(),
653            default_view: DefaultAgentView::Thread,
654            profiles: Default::default(),
655            notify_when_agent_waiting: NotifyWhenAgentWaiting::default(),
656            play_sound_when_agent_done: false,
657            single_file_review: false,
658            model_parameters: vec![],
659            enable_feedback: false,
660            expand_edit_card: true,
661            expand_terminal_card: true,
662            cancel_generation_on_terminal_stop: true,
663            use_modifier_to_send: true,
664            message_editor_min_lines: 1,
665            tool_permissions: Default::default(),
666            show_turn_stats: false,
667            new_thread_location: Default::default(),
668            sidebar_side: Default::default(),
669        };
670
671        cx.update(|cx| {
672            AgentSettings::override_global(agent_settings.clone(), cx);
673            DisableAiSettings::override_global(DisableAiSettings { disable_ai: false }, cx);
674
675            // Initial update
676            update_command_palette_filter(cx);
677        });
678
679        // Assert visible
680        cx.update(|cx| {
681            let filter = CommandPaletteFilter::try_global(cx).unwrap();
682            assert!(
683                !filter.is_hidden(&NewThread),
684                "NewThread should be visible by default"
685            );
686            assert!(
687                !filter.is_hidden(&text_thread_editor::CopyCode),
688                "CopyCode should be visible when agent is enabled"
689            );
690        });
691
692        // Disable agent
693        cx.update(|cx| {
694            let mut new_settings = agent_settings.clone();
695            new_settings.enabled = false;
696            AgentSettings::override_global(new_settings, cx);
697
698            // Trigger update
699            update_command_palette_filter(cx);
700        });
701
702        // Assert hidden
703        cx.update(|cx| {
704            let filter = CommandPaletteFilter::try_global(cx).unwrap();
705            assert!(
706                filter.is_hidden(&NewThread),
707                "NewThread should be hidden when agent is disabled"
708            );
709            assert!(
710                filter.is_hidden(&text_thread_editor::CopyCode),
711                "CopyCode should be hidden when agent is disabled"
712            );
713        });
714
715        // Test EditPredictionProvider
716        // Enable EditPredictionProvider::Copilot
717        cx.update(|cx| {
718            cx.update_global::<SettingsStore, _>(|store, cx| {
719                store.update_user_settings(cx, |s| {
720                    s.project
721                        .all_languages
722                        .edit_predictions
723                        .get_or_insert(Default::default())
724                        .provider = Some(EditPredictionProvider::Copilot);
725                });
726            });
727            update_command_palette_filter(cx);
728        });
729
730        cx.update(|cx| {
731            let filter = CommandPaletteFilter::try_global(cx).unwrap();
732            assert!(
733                !filter.is_hidden(&AcceptEditPrediction),
734                "EditPrediction should be visible when provider is Copilot"
735            );
736        });
737
738        // Disable EditPredictionProvider (None)
739        cx.update(|cx| {
740            cx.update_global::<SettingsStore, _>(|store, cx| {
741                store.update_user_settings(cx, |s| {
742                    s.project
743                        .all_languages
744                        .edit_predictions
745                        .get_or_insert(Default::default())
746                        .provider = Some(EditPredictionProvider::None);
747                });
748            });
749            update_command_palette_filter(cx);
750        });
751
752        cx.update(|cx| {
753            let filter = CommandPaletteFilter::try_global(cx).unwrap();
754            assert!(
755                filter.is_hidden(&AcceptEditPrediction),
756                "EditPrediction should be hidden when provider is None"
757            );
758        });
759    }
760
761    #[test]
762    fn test_deserialize_external_agent_variants() {
763        assert_eq!(
764            serde_json::from_str::<Agent>(r#""native_agent""#).unwrap(),
765            Agent::NativeAgent,
766        );
767        assert_eq!(
768            serde_json::from_str::<Agent>(r#"{"custom":{"name":"my-agent"}}"#).unwrap(),
769            Agent::Custom {
770                id: "my-agent".into(),
771            },
772        );
773    }
774}