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