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