agent_ui.rs

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