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