1mod agent_configuration;
2pub(crate) mod agent_connection_store;
3mod agent_diff;
4mod agent_model_selector;
5mod agent_panel;
6mod agent_registry_ui;
7mod branch_names;
8mod buffer_codegen;
9mod completion_provider;
10mod config_options;
11mod context;
12mod context_server_configuration;
13pub(crate) mod conversation_view;
14mod entry_view_state;
15mod external_source_prompt;
16mod favorite_models;
17mod inline_assistant;
18mod inline_prompt_editor;
19mod language_model_selector;
20mod mention_set;
21mod message_editor;
22mod mode_selector;
23mod model_selector;
24mod model_selector_popover;
25mod profile_selector;
26mod slash_command;
27mod slash_command_picker;
28mod terminal_codegen;
29mod terminal_inline_assistant;
30#[cfg(any(test, feature = "test-support"))]
31pub mod test_support;
32mod text_thread_editor;
33mod text_thread_history;
34mod thread_history;
35mod thread_history_view;
36pub mod thread_metadata_store;
37pub mod 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, UpdateGlobal, Window, actions};
51use language::{
52 LanguageRegistry,
53 language_settings::{AllLanguageSettings, EditPredictionProvider},
54};
55use language_model::{
56 ConfiguredModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
57};
58use project::{AgentId, DisableAiSettings};
59use prompt_store::PromptBuilder;
60use schemars::JsonSchema;
61use serde::{Deserialize, Serialize};
62use settings::{DockPosition, DockSide, 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 conversation_view::ConversationView;
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
83pub const DEFAULT_THREAD_TITLE: &str = "New Thread";
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/// Action to select a permission granularity option from the dropdown.
200/// This updates the selected granularity without triggering authorization.
201#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
202#[action(namespace = agent)]
203#[serde(deny_unknown_fields)]
204pub struct SelectPermissionGranularity {
205 /// The tool call ID for which to select the granularity.
206 pub tool_call_id: String,
207 /// The index of the selected granularity option.
208 pub index: usize,
209}
210
211/// Action to toggle a command pattern checkbox in the permission dropdown.
212#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
213#[action(namespace = agent)]
214#[serde(deny_unknown_fields)]
215pub struct ToggleCommandPattern {
216 /// The tool call ID for which to toggle the pattern.
217 pub tool_call_id: String,
218 /// The index of the command pattern to toggle.
219 pub pattern_index: usize,
220}
221
222/// Creates a new conversation thread, optionally based on an existing thread.
223#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
224#[action(namespace = agent)]
225#[serde(deny_unknown_fields)]
226pub struct NewThread;
227
228/// Creates a new external agent conversation thread.
229#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
230#[action(namespace = agent)]
231#[serde(deny_unknown_fields)]
232pub struct NewExternalAgentThread {
233 /// Which agent to use for the conversation.
234 agent: Option<Agent>,
235}
236
237#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
238#[action(namespace = agent)]
239#[serde(deny_unknown_fields)]
240pub struct NewNativeAgentThreadFromSummary {
241 from_session_id: agent_client_protocol::SessionId,
242}
243
244// TODO unify this with AgentType
245#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
246#[serde(rename_all = "snake_case")]
247pub enum Agent {
248 NativeAgent,
249 Custom {
250 #[serde(rename = "name")]
251 id: AgentId,
252 },
253}
254
255impl Agent {
256 pub fn id(&self) -> AgentId {
257 match self {
258 Self::NativeAgent => agent::ZED_AGENT_ID.clone(),
259 Self::Custom { id } => id.clone(),
260 }
261 }
262
263 pub fn server(
264 &self,
265 fs: Arc<dyn fs::Fs>,
266 thread_store: Entity<agent::ThreadStore>,
267 ) -> Rc<dyn agent_servers::AgentServer> {
268 match self {
269 Self::NativeAgent => Rc::new(agent::NativeAgentServer::new(fs, thread_store)),
270 Self::Custom { id: name } => {
271 Rc::new(agent_servers::CustomAgentServer::new(name.clone()))
272 }
273 }
274 }
275}
276
277/// Sets where new threads will run.
278#[derive(
279 Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Action,
280)]
281#[action(namespace = agent)]
282#[serde(rename_all = "snake_case", tag = "kind")]
283pub enum StartThreadIn {
284 #[default]
285 LocalProject,
286 NewWorktree,
287}
288
289/// Content to initialize new external agent with.
290pub enum AgentInitialContent {
291 ThreadSummary {
292 session_id: acp::SessionId,
293 title: Option<SharedString>,
294 },
295 ContentBlock {
296 blocks: Vec<agent_client_protocol::ContentBlock>,
297 auto_submit: bool,
298 },
299 FromExternalSource(ExternalSourcePrompt),
300}
301
302impl From<ExternalSourcePrompt> for AgentInitialContent {
303 fn from(prompt: ExternalSourcePrompt) -> Self {
304 Self::FromExternalSource(prompt)
305 }
306}
307
308/// Opens the profile management interface for configuring agent tools and settings.
309#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
310#[action(namespace = agent)]
311#[serde(deny_unknown_fields)]
312pub struct ManageProfiles {
313 #[serde(default)]
314 pub customize_tools: Option<AgentProfileId>,
315}
316
317impl ManageProfiles {
318 pub fn customize_tools(profile_id: AgentProfileId) -> Self {
319 Self {
320 customize_tools: Some(profile_id),
321 }
322 }
323}
324
325#[derive(Clone)]
326pub(crate) enum ModelUsageContext {
327 InlineAssistant,
328}
329
330impl ModelUsageContext {
331 pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
332 match self {
333 Self::InlineAssistant => {
334 LanguageModelRegistry::read_global(cx).inline_assistant_model()
335 }
336 }
337 }
338}
339
340/// Initializes the `agent` crate.
341pub fn init(
342 fs: Arc<dyn Fs>,
343 client: Arc<Client>,
344 prompt_builder: Arc<PromptBuilder>,
345 language_registry: Arc<LanguageRegistry>,
346 is_eval: bool,
347 cx: &mut App,
348) {
349 agent::ThreadStore::init_global(cx);
350 assistant_text_thread::init(client, cx);
351 rules_library::init(cx);
352 if !is_eval {
353 // Initializing the language model from the user settings messes with the eval, so we only initialize them when
354 // we're not running inside of the eval.
355 init_language_model_settings(cx);
356 }
357 assistant_slash_command::init(cx);
358 agent_panel::init(cx);
359 context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
360 TextThreadEditor::init(cx);
361 thread_metadata_store::init(cx);
362
363 register_slash_commands(cx);
364 inline_assistant::init(fs.clone(), prompt_builder.clone(), cx);
365 terminal_inline_assistant::init(fs.clone(), prompt_builder, cx);
366 cx.observe_new(move |workspace, window, cx| {
367 ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
368 })
369 .detach();
370 cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
371 workspace.register_action(
372 move |workspace: &mut Workspace,
373 _: &zed_actions::AcpRegistry,
374 window: &mut Window,
375 cx: &mut Context<Workspace>| {
376 let existing = workspace
377 .active_pane()
378 .read(cx)
379 .items()
380 .find_map(|item| item.downcast::<AgentRegistryPage>());
381
382 if let Some(existing) = existing {
383 existing.update(cx, |_, cx| {
384 project::AgentRegistryStore::global(cx)
385 .update(cx, |store, cx| store.refresh(cx));
386 });
387 workspace.activate_item(&existing, true, true, window, cx);
388 } else {
389 let registry_page = AgentRegistryPage::new(workspace, window, cx);
390 workspace.add_item_to_active_pane(
391 Box::new(registry_page),
392 None,
393 true,
394 window,
395 cx,
396 );
397 }
398 },
399 );
400 })
401 .detach();
402 cx.observe_new(ManageProfilesModal::register).detach();
403
404 // Update command palette filter based on AI settings
405 update_command_palette_filter(cx);
406
407 // Watch for settings changes
408 cx.observe_global::<SettingsStore>(|app_cx| {
409 // When settings change, update the command palette filter
410 update_command_palette_filter(app_cx);
411 })
412 .detach();
413
414 cx.on_flags_ready(|_, cx| {
415 update_command_palette_filter(cx);
416 })
417 .detach();
418
419 cx.observe_flag::<AgentV2FeatureFlag, _>(|is_enabled, cx| {
420 SettingsStore::update_global(cx, |store, cx| {
421 store.update_default_settings(cx, |defaults| {
422 if is_enabled {
423 defaults.agent.get_or_insert_default().dock = Some(DockPosition::Left);
424 defaults.project_panel.get_or_insert_default().dock = Some(DockSide::Right);
425 defaults.outline_panel.get_or_insert_default().dock = Some(DockSide::Right);
426 defaults.collaboration_panel.get_or_insert_default().dock =
427 Some(DockPosition::Right);
428 defaults.git_panel.get_or_insert_default().dock = Some(DockPosition::Right);
429 defaults.notification_panel.get_or_insert_default().button = Some(false);
430 } else {
431 defaults.agent.get_or_insert_default().dock = Some(DockPosition::Right);
432 defaults.project_panel.get_or_insert_default().dock = Some(DockSide::Left);
433 defaults.outline_panel.get_or_insert_default().dock = Some(DockSide::Left);
434 defaults.collaboration_panel.get_or_insert_default().dock =
435 Some(DockPosition::Left);
436 defaults.git_panel.get_or_insert_default().dock = Some(DockPosition::Left);
437 defaults.notification_panel.get_or_insert_default().button = Some(true);
438 }
439 });
440 });
441 })
442 .detach();
443}
444
445fn update_command_palette_filter(cx: &mut App) {
446 let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
447 let agent_enabled = AgentSettings::get_global(cx).enabled;
448 let agent_v2_enabled = cx.has_flag::<AgentV2FeatureFlag>();
449 let edit_prediction_provider = AllLanguageSettings::get_global(cx)
450 .edit_predictions
451 .provider;
452
453 CommandPaletteFilter::update_global(cx, |filter, _| {
454 use editor::actions::{
455 AcceptEditPrediction, AcceptNextLineEditPrediction, AcceptNextWordEditPrediction,
456 NextEditPrediction, PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
457 };
458 let edit_prediction_actions = [
459 TypeId::of::<AcceptEditPrediction>(),
460 TypeId::of::<AcceptNextWordEditPrediction>(),
461 TypeId::of::<AcceptNextLineEditPrediction>(),
462 TypeId::of::<AcceptEditPrediction>(),
463 TypeId::of::<ShowEditPrediction>(),
464 TypeId::of::<NextEditPrediction>(),
465 TypeId::of::<PreviousEditPrediction>(),
466 TypeId::of::<ToggleEditPrediction>(),
467 ];
468
469 if disable_ai {
470 filter.hide_namespace("agent");
471 filter.hide_namespace("agents");
472 filter.hide_namespace("assistant");
473 filter.hide_namespace("copilot");
474 filter.hide_namespace("zed_predict_onboarding");
475 filter.hide_namespace("edit_prediction");
476
477 filter.hide_action_types(&edit_prediction_actions);
478 filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
479 } else {
480 if agent_enabled {
481 filter.show_namespace("agent");
482 filter.show_namespace("agents");
483 filter.show_namespace("assistant");
484 } else {
485 filter.hide_namespace("agent");
486 filter.hide_namespace("agents");
487 filter.hide_namespace("assistant");
488 }
489
490 match edit_prediction_provider {
491 EditPredictionProvider::None => {
492 filter.hide_namespace("edit_prediction");
493 filter.hide_namespace("copilot");
494 filter.hide_action_types(&edit_prediction_actions);
495 }
496 EditPredictionProvider::Copilot => {
497 filter.show_namespace("edit_prediction");
498 filter.show_namespace("copilot");
499 filter.show_action_types(edit_prediction_actions.iter());
500 }
501 EditPredictionProvider::Zed
502 | EditPredictionProvider::Codestral
503 | EditPredictionProvider::Ollama
504 | EditPredictionProvider::OpenAiCompatibleApi
505 | EditPredictionProvider::Mercury
506 | EditPredictionProvider::Experimental(_) => {
507 filter.show_namespace("edit_prediction");
508 filter.hide_namespace("copilot");
509 filter.show_action_types(edit_prediction_actions.iter());
510 }
511 }
512
513 filter.show_namespace("zed_predict_onboarding");
514 filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
515 }
516
517 if agent_v2_enabled {
518 filter.show_namespace("multi_workspace");
519 } else {
520 filter.hide_namespace("multi_workspace");
521 }
522 });
523}
524
525fn init_language_model_settings(cx: &mut App) {
526 update_active_language_model_from_settings(cx);
527
528 cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
529 .detach();
530 cx.subscribe(
531 &LanguageModelRegistry::global(cx),
532 |_, event: &language_model::Event, cx| match event {
533 language_model::Event::ProviderStateChanged(_)
534 | language_model::Event::AddedProvider(_)
535 | language_model::Event::RemovedProvider(_)
536 | language_model::Event::ProvidersChanged => {
537 update_active_language_model_from_settings(cx);
538 }
539 _ => {}
540 },
541 )
542 .detach();
543}
544
545fn update_active_language_model_from_settings(cx: &mut App) {
546 let settings = AgentSettings::get_global(cx);
547
548 fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
549 language_model::SelectedModel {
550 provider: LanguageModelProviderId::from(selection.provider.0.clone()),
551 model: LanguageModelId::from(selection.model.clone()),
552 }
553 }
554
555 let default = settings.default_model.as_ref().map(to_selected_model);
556 let inline_assistant = settings
557 .inline_assistant_model
558 .as_ref()
559 .map(to_selected_model);
560 let commit_message = settings
561 .commit_message_model
562 .as_ref()
563 .map(to_selected_model);
564 let thread_summary = settings
565 .thread_summary_model
566 .as_ref()
567 .map(to_selected_model);
568 let inline_alternatives = settings
569 .inline_alternatives
570 .iter()
571 .map(to_selected_model)
572 .collect::<Vec<_>>();
573
574 LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
575 registry.select_default_model(default.as_ref(), cx);
576 registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
577 registry.select_commit_message_model(commit_message.as_ref(), cx);
578 registry.select_thread_summary_model(thread_summary.as_ref(), cx);
579 registry.select_inline_alternative_models(inline_alternatives, cx);
580 });
581}
582
583fn register_slash_commands(cx: &mut App) {
584 let slash_command_registry = SlashCommandRegistry::global(cx);
585
586 slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
587 slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
588 slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
589 slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
590 slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
591 slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
592 slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
593 slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
594 slash_command_registry
595 .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
596 slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
597
598 cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
599 move |is_enabled, _cx| {
600 if is_enabled {
601 slash_command_registry.register_command(
602 assistant_slash_commands::StreamingExampleSlashCommand,
603 false,
604 );
605 }
606 }
607 })
608 .detach();
609}
610
611#[cfg(test)]
612mod tests {
613 use super::*;
614 use agent_settings::{AgentProfileId, AgentSettings};
615 use command_palette_hooks::CommandPaletteFilter;
616 use editor::actions::AcceptEditPrediction;
617 use gpui::{BorrowAppContext, TestAppContext, px};
618 use project::DisableAiSettings;
619 use settings::{
620 DefaultAgentView, DockPosition, NotifyWhenAgentWaiting, Settings, SettingsStore,
621 };
622
623 #[gpui::test]
624 fn test_agent_command_palette_visibility(cx: &mut TestAppContext) {
625 // Init settings
626 cx.update(|cx| {
627 let store = SettingsStore::test(cx);
628 cx.set_global(store);
629 command_palette_hooks::init(cx);
630 AgentSettings::register(cx);
631 DisableAiSettings::register(cx);
632 AllLanguageSettings::register(cx);
633 });
634
635 let agent_settings = AgentSettings {
636 enabled: true,
637 button: true,
638 dock: DockPosition::Right,
639 flexible: true,
640 default_width: px(300.),
641 default_height: px(600.),
642 default_model: None,
643 inline_assistant_model: None,
644 inline_assistant_use_streaming_tools: false,
645 commit_message_model: None,
646 thread_summary_model: None,
647 inline_alternatives: vec![],
648 favorite_models: vec![],
649 default_profile: AgentProfileId::default(),
650 default_view: DefaultAgentView::Thread,
651 profiles: Default::default(),
652
653 notify_when_agent_waiting: NotifyWhenAgentWaiting::default(),
654 play_sound_when_agent_done: false,
655 single_file_review: false,
656 model_parameters: vec![],
657 enable_feedback: false,
658 expand_edit_card: true,
659 expand_terminal_card: true,
660 cancel_generation_on_terminal_stop: true,
661 use_modifier_to_send: true,
662 message_editor_min_lines: 1,
663 tool_permissions: Default::default(),
664 show_turn_stats: false,
665 new_thread_location: Default::default(),
666 };
667
668 cx.update(|cx| {
669 AgentSettings::override_global(agent_settings.clone(), cx);
670 DisableAiSettings::override_global(DisableAiSettings { disable_ai: false }, cx);
671
672 // Initial update
673 update_command_palette_filter(cx);
674 });
675
676 // Assert visible
677 cx.update(|cx| {
678 let filter = CommandPaletteFilter::try_global(cx).unwrap();
679 assert!(
680 !filter.is_hidden(&NewThread),
681 "NewThread should be visible by default"
682 );
683 assert!(
684 !filter.is_hidden(&text_thread_editor::CopyCode),
685 "CopyCode should be visible when agent is enabled"
686 );
687 });
688
689 // Disable agent
690 cx.update(|cx| {
691 let mut new_settings = agent_settings.clone();
692 new_settings.enabled = false;
693 AgentSettings::override_global(new_settings, cx);
694
695 // Trigger update
696 update_command_palette_filter(cx);
697 });
698
699 // Assert hidden
700 cx.update(|cx| {
701 let filter = CommandPaletteFilter::try_global(cx).unwrap();
702 assert!(
703 filter.is_hidden(&NewThread),
704 "NewThread should be hidden when agent is disabled"
705 );
706 assert!(
707 filter.is_hidden(&text_thread_editor::CopyCode),
708 "CopyCode should be hidden when agent is disabled"
709 );
710 });
711
712 // Test EditPredictionProvider
713 // Enable EditPredictionProvider::Copilot
714 cx.update(|cx| {
715 cx.update_global::<SettingsStore, _>(|store, cx| {
716 store.update_user_settings(cx, |s| {
717 s.project
718 .all_languages
719 .edit_predictions
720 .get_or_insert(Default::default())
721 .provider = Some(EditPredictionProvider::Copilot);
722 });
723 });
724 update_command_palette_filter(cx);
725 });
726
727 cx.update(|cx| {
728 let filter = CommandPaletteFilter::try_global(cx).unwrap();
729 assert!(
730 !filter.is_hidden(&AcceptEditPrediction),
731 "EditPrediction should be visible when provider is Copilot"
732 );
733 });
734
735 // Disable EditPredictionProvider (None)
736 cx.update(|cx| {
737 cx.update_global::<SettingsStore, _>(|store, cx| {
738 store.update_user_settings(cx, |s| {
739 s.project
740 .all_languages
741 .edit_predictions
742 .get_or_insert(Default::default())
743 .provider = Some(EditPredictionProvider::None);
744 });
745 });
746 update_command_palette_filter(cx);
747 });
748
749 cx.update(|cx| {
750 let filter = CommandPaletteFilter::try_global(cx).unwrap();
751 assert!(
752 filter.is_hidden(&AcceptEditPrediction),
753 "EditPrediction should be hidden when provider is None"
754 );
755 });
756 }
757
758 #[test]
759 fn test_deserialize_external_agent_variants() {
760 assert_eq!(
761 serde_json::from_str::<Agent>(r#""native_agent""#).unwrap(),
762 Agent::NativeAgent,
763 );
764 assert_eq!(
765 serde_json::from_str::<Agent>(r#"{"custom":{"name":"my-agent"}}"#).unwrap(),
766 Agent::Custom {
767 id: "my-agent".into(),
768 },
769 );
770 }
771}