agent_ui.rs

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