1mod agent_configuration;
2pub(crate) mod agent_connection_store;
3mod agent_diff;
4mod agent_model_selector;
5mod agent_panel;
6mod agent_registry_ui;
7mod buffer_codegen;
8mod completion_provider;
9mod config_options;
10mod context;
11mod context_server_configuration;
12pub(crate) mod conversation_view;
13mod diagnostics;
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 terminal_codegen;
27mod terminal_inline_assistant;
28#[cfg(any(test, feature = "test-support"))]
29pub mod test_support;
30mod thread_history;
31mod thread_history_view;
32mod thread_import;
33pub mod thread_metadata_store;
34pub mod thread_worktree_archive;
35
36pub mod threads_archive_view;
37mod ui;
38
39use std::rc::Rc;
40use std::sync::Arc;
41
42use ::ui::IconName;
43use agent_client_protocol as acp;
44use agent_settings::{AgentProfileId, AgentSettings};
45use command_palette_hooks::CommandPaletteFilter;
46use feature_flags::FeatureFlagAppExt as _;
47use fs::Fs;
48use gpui::{Action, App, Context, Entity, SharedString, UpdateGlobal as _, Window, actions};
49use language::{
50 LanguageRegistry,
51 language_settings::{AllLanguageSettings, EditPredictionProvider},
52};
53use language_model::{
54 ConfiguredModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
55};
56use project::{AgentId, DisableAiSettings};
57use prompt_store::PromptBuilder;
58use release_channel::ReleaseChannel;
59use schemars::JsonSchema;
60use serde::{Deserialize, Serialize};
61use settings::{DockPosition, DockSide, LanguageModelSelection, Settings as _, SettingsStore};
62use std::any::TypeId;
63use workspace::Workspace;
64
65use crate::agent_configuration::{ConfigureContextServerModal, ManageProfilesModal};
66pub use crate::agent_panel::{AgentPanel, AgentPanelEvent, MaxIdleRetainedThreads};
67use crate::agent_registry_ui::AgentRegistryPage;
68pub use crate::inline_assistant::InlineAssistant;
69pub use crate::thread_metadata_store::ThreadId;
70pub use agent_diff::{AgentDiffPane, AgentDiffToolbar};
71pub use conversation_view::ConversationView;
72pub use external_source_prompt::ExternalSourcePrompt;
73pub(crate) use mode_selector::ModeSelector;
74pub(crate) use model_selector::ModelSelector;
75pub(crate) use model_selector_popover::ModelSelectorPopover;
76pub(crate) use thread_history::ThreadHistory;
77pub(crate) use thread_history_view::*;
78pub use thread_import::{
79 AcpThreadImportOnboarding, CrossChannelImportOnboarding, ThreadImportModal,
80 channels_with_threads, import_threads_from_other_channels,
81};
82use zed_actions;
83pub use zed_actions::{CreateWorktree, NewWorktreeBranchTarget, SwitchWorktree};
84
85pub const DEFAULT_THREAD_TITLE: &str = "New Agent Thread";
86const PARALLEL_AGENT_LAYOUT_BACKFILL_KEY: &str = "parallel_agent_layout_backfilled";
87actions!(
88 agent,
89 [
90 /// Toggles the menu to create new agent threads.
91 ToggleNewThreadMenu,
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 /// Archives the currently selected thread.
111 ArchiveSelectedThread,
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 /// Scroll the output by one page up.
183 ScrollOutputPageUp,
184 /// Scroll the output by one page down.
185 ScrollOutputPageDown,
186 /// Scroll the output up by three lines.
187 ScrollOutputLineUp,
188 /// Scroll the output down by three lines.
189 ScrollOutputLineDown,
190 /// Scroll the output to the top.
191 ScrollOutputToTop,
192 /// Scroll the output to the bottom.
193 ScrollOutputToBottom,
194 /// Scroll the output to the previous user message.
195 ScrollOutputToPreviousMessage,
196 /// Scroll the output to the next user message.
197 ScrollOutputToNextMessage,
198 /// Import agent threads from other Zed release channels (e.g. Preview, Nightly).
199 ImportThreadsFromOtherChannels,
200 ]
201);
202
203actions!(
204 dev,
205 [
206 /// Shows metadata for the currently active thread.
207 ShowThreadMetadata,
208 /// Shows metadata for all threads in the sidebar.
209 ShowAllSidebarThreadMetadata,
210 ]
211);
212
213/// Action to authorize a tool call with a specific permission option.
214/// This is used by the permission granularity dropdown to authorize tool calls.
215#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
216#[action(namespace = agent)]
217#[serde(deny_unknown_fields)]
218pub struct AuthorizeToolCall {
219 /// The tool call ID to authorize.
220 pub tool_call_id: String,
221 /// The permission option ID to use.
222 pub option_id: String,
223 /// The kind of permission option (serialized as string).
224 pub option_kind: String,
225}
226
227/// Action to select a permission granularity option from the dropdown.
228/// This updates the selected granularity without triggering authorization.
229#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
230#[action(namespace = agent)]
231#[serde(deny_unknown_fields)]
232pub struct SelectPermissionGranularity {
233 /// The tool call ID for which to select the granularity.
234 pub tool_call_id: String,
235 /// The index of the selected granularity option.
236 pub index: usize,
237}
238
239/// Action to toggle a command pattern checkbox in the permission dropdown.
240#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
241#[action(namespace = agent)]
242#[serde(deny_unknown_fields)]
243pub struct ToggleCommandPattern {
244 /// The tool call ID for which to toggle the pattern.
245 pub tool_call_id: String,
246 /// The index of the command pattern to toggle.
247 pub pattern_index: usize,
248}
249
250/// Creates a new conversation thread, optionally based on an existing thread.
251#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
252#[action(namespace = agent)]
253#[serde(deny_unknown_fields)]
254pub struct NewThread;
255
256/// Creates a new external agent conversation thread.
257#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
258#[action(namespace = agent)]
259#[serde(deny_unknown_fields)]
260pub struct NewExternalAgentThread {
261 /// Which agent to use for the conversation.
262 agent: Option<Agent>,
263}
264
265#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
266#[action(namespace = agent)]
267#[serde(deny_unknown_fields)]
268pub struct NewNativeAgentThreadFromSummary {
269 from_session_id: agent_client_protocol::SessionId,
270}
271
272#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
273#[serde(rename_all = "snake_case")]
274#[non_exhaustive]
275pub enum Agent {
276 #[default]
277 #[serde(alias = "NativeAgent", alias = "TextThread")]
278 NativeAgent,
279 #[serde(alias = "Custom")]
280 Custom {
281 #[serde(rename = "name")]
282 id: AgentId,
283 },
284 #[cfg(any(test, feature = "test-support"))]
285 Stub,
286}
287
288impl From<AgentId> for Agent {
289 fn from(id: AgentId) -> Self {
290 if id.as_ref() == agent::ZED_AGENT_ID.as_ref() {
291 Self::NativeAgent
292 } else {
293 Self::Custom { id }
294 }
295 }
296}
297
298impl Agent {
299 pub fn id(&self) -> AgentId {
300 match self {
301 Self::NativeAgent => agent::ZED_AGENT_ID.clone(),
302 Self::Custom { id } => id.clone(),
303 #[cfg(any(test, feature = "test-support"))]
304 Self::Stub => "stub".into(),
305 }
306 }
307
308 pub fn is_native(&self) -> bool {
309 matches!(self, Self::NativeAgent)
310 }
311
312 pub fn label(&self) -> SharedString {
313 match self {
314 Self::NativeAgent => "Zed Agent".into(),
315 Self::Custom { id, .. } => id.0.clone(),
316 #[cfg(any(test, feature = "test-support"))]
317 Self::Stub => "Stub Agent".into(),
318 }
319 }
320
321 pub fn icon(&self) -> Option<IconName> {
322 match self {
323 Self::NativeAgent => None,
324 Self::Custom { .. } => Some(IconName::Sparkle),
325 #[cfg(any(test, feature = "test-support"))]
326 Self::Stub => None,
327 }
328 }
329
330 pub fn server(
331 &self,
332 fs: Arc<dyn fs::Fs>,
333 thread_store: Entity<agent::ThreadStore>,
334 ) -> Rc<dyn agent_servers::AgentServer> {
335 match self {
336 Self::NativeAgent => Rc::new(agent::NativeAgentServer::new(fs, thread_store)),
337 Self::Custom { id: name } => {
338 Rc::new(agent_servers::CustomAgentServer::new(name.clone()))
339 }
340 #[cfg(any(test, feature = "test-support"))]
341 Self::Stub => Rc::new(crate::test_support::StubAgentServer::default_response()),
342 }
343 }
344}
345
346/// Content to initialize new external agent with.
347pub enum AgentInitialContent {
348 ThreadSummary {
349 session_id: acp::SessionId,
350 title: Option<SharedString>,
351 },
352 ContentBlock {
353 blocks: Vec<agent_client_protocol::ContentBlock>,
354 auto_submit: bool,
355 },
356 FromExternalSource(ExternalSourcePrompt),
357}
358
359impl From<ExternalSourcePrompt> for AgentInitialContent {
360 fn from(prompt: ExternalSourcePrompt) -> Self {
361 Self::FromExternalSource(prompt)
362 }
363}
364
365/// Opens the profile management interface for configuring agent tools and settings.
366#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
367#[action(namespace = agent)]
368#[serde(deny_unknown_fields)]
369pub struct ManageProfiles {
370 #[serde(default)]
371 pub customize_tools: Option<AgentProfileId>,
372}
373
374impl ManageProfiles {
375 pub fn customize_tools(profile_id: AgentProfileId) -> Self {
376 Self {
377 customize_tools: Some(profile_id),
378 }
379 }
380}
381
382#[derive(Clone)]
383pub(crate) enum ModelUsageContext {
384 InlineAssistant,
385}
386
387impl ModelUsageContext {
388 pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
389 match self {
390 Self::InlineAssistant => {
391 LanguageModelRegistry::read_global(cx).inline_assistant_model()
392 }
393 }
394 }
395}
396
397pub(crate) fn humanize_token_count(count: u64) -> String {
398 match count {
399 0..=999 => count.to_string(),
400 1000..=9999 => {
401 let thousands = count / 1000;
402 let hundreds = (count % 1000 + 50) / 100;
403 if hundreds == 0 {
404 format!("{}k", thousands)
405 } else if hundreds == 10 {
406 format!("{}k", thousands + 1)
407 } else {
408 format!("{}.{}k", thousands, hundreds)
409 }
410 }
411 10_000..=999_999 => format!("{}k", (count + 500) / 1000),
412 1_000_000..=9_999_999 => {
413 let millions = count / 1_000_000;
414 let hundred_thousands = (count % 1_000_000 + 50_000) / 100_000;
415 if hundred_thousands == 0 {
416 format!("{}M", millions)
417 } else if hundred_thousands == 10 {
418 format!("{}M", millions + 1)
419 } else {
420 format!("{}.{}M", millions, hundred_thousands)
421 }
422 }
423 10_000_000.. => format!("{}M", (count + 500_000) / 1_000_000),
424 }
425}
426
427/// Initializes the `agent` crate.
428pub fn init(
429 fs: Arc<dyn Fs>,
430 prompt_builder: Arc<PromptBuilder>,
431 language_registry: Arc<LanguageRegistry>,
432 is_new_install: bool,
433 is_eval: bool,
434 cx: &mut App,
435) {
436 agent::ThreadStore::init_global(cx);
437 rules_library::init(cx);
438 if !is_eval {
439 // Initializing the language model from the user settings messes with the eval, so we only initialize them when
440 // we're not running inside of the eval.
441 init_language_model_settings(cx);
442 }
443 agent_panel::init(cx);
444 context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
445 thread_metadata_store::init(cx);
446
447 inline_assistant::init(fs.clone(), prompt_builder.clone(), cx);
448 terminal_inline_assistant::init(fs.clone(), prompt_builder, cx);
449 cx.observe_new(move |workspace, window, cx| {
450 ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
451 })
452 .detach();
453 cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
454 workspace.register_action(
455 move |workspace: &mut Workspace,
456 _: &zed_actions::AcpRegistry,
457 window: &mut Window,
458 cx: &mut Context<Workspace>| {
459 let existing = workspace
460 .active_pane()
461 .read(cx)
462 .items()
463 .find_map(|item| item.downcast::<AgentRegistryPage>());
464
465 if let Some(existing) = existing {
466 existing.update(cx, |_, cx| {
467 project::AgentRegistryStore::global(cx)
468 .update(cx, |store, cx| store.refresh(cx));
469 });
470 workspace.activate_item(&existing, true, true, window, cx);
471 } else {
472 let registry_page = AgentRegistryPage::new(workspace, window, cx);
473 workspace.add_item_to_active_pane(
474 Box::new(registry_page),
475 None,
476 true,
477 window,
478 cx,
479 );
480 }
481 },
482 );
483 })
484 .detach();
485 cx.observe_new(ManageProfilesModal::register).detach();
486 cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
487 workspace.register_action(
488 |workspace: &mut Workspace,
489 _: &ImportThreadsFromOtherChannels,
490 _window: &mut Window,
491 cx: &mut Context<Workspace>| {
492 import_threads_from_other_channels(workspace, cx);
493 },
494 );
495 })
496 .detach();
497
498 // Update command palette filter based on AI settings
499 update_command_palette_filter(cx);
500
501 // Watch for settings changes
502 cx.observe_global::<SettingsStore>(|app_cx| {
503 // When settings change, update the command palette filter
504 update_command_palette_filter(app_cx);
505 })
506 .detach();
507
508 cx.on_flags_ready(|_, cx| {
509 update_command_palette_filter(cx);
510 })
511 .detach();
512
513 let agent_v2_enabled = agent_v2_enabled(cx);
514 if agent_v2_enabled {
515 maybe_backfill_editor_layout(fs, is_new_install, cx);
516 }
517
518 SettingsStore::update_global(cx, |store, cx| {
519 store.update_default_settings(cx, |defaults| {
520 if agent_v2_enabled {
521 defaults.agent.get_or_insert_default().dock = Some(DockPosition::Left);
522 defaults.project_panel.get_or_insert_default().dock = Some(DockSide::Right);
523 defaults.outline_panel.get_or_insert_default().dock = Some(DockSide::Right);
524 defaults.collaboration_panel.get_or_insert_default().dock =
525 Some(DockPosition::Right);
526 defaults.git_panel.get_or_insert_default().dock = Some(DockPosition::Right);
527 } else {
528 defaults.agent.get_or_insert_default().dock = Some(DockPosition::Right);
529 defaults.project_panel.get_or_insert_default().dock = Some(DockSide::Left);
530 defaults.outline_panel.get_or_insert_default().dock = Some(DockSide::Left);
531 defaults.collaboration_panel.get_or_insert_default().dock =
532 Some(DockPosition::Left);
533 defaults.git_panel.get_or_insert_default().dock = Some(DockPosition::Left);
534 }
535 });
536 });
537}
538
539fn agent_v2_enabled(cx: &App) -> bool {
540 !matches!(ReleaseChannel::try_global(cx), Some(ReleaseChannel::Stable))
541}
542
543fn maybe_backfill_editor_layout(fs: Arc<dyn Fs>, is_new_install: bool, cx: &mut App) {
544 let kvp = db::kvp::KeyValueStore::global(cx);
545 let already_backfilled =
546 util::ResultExt::log_err(kvp.read_kvp(PARALLEL_AGENT_LAYOUT_BACKFILL_KEY))
547 .flatten()
548 .is_some();
549
550 if !already_backfilled {
551 if !is_new_install {
552 AgentSettings::backfill_editor_layout(fs, cx);
553 }
554
555 db::write_and_log(cx, move || async move {
556 kvp.write_kvp(
557 PARALLEL_AGENT_LAYOUT_BACKFILL_KEY.to_string(),
558 "1".to_string(),
559 )
560 .await
561 });
562 }
563}
564
565fn update_command_palette_filter(cx: &mut App) {
566 let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
567 let agent_enabled = AgentSettings::get_global(cx).enabled;
568 let agent_v2_enabled = agent_v2_enabled(cx);
569
570 let edit_prediction_provider = AllLanguageSettings::get_global(cx)
571 .edit_predictions
572 .provider;
573
574 CommandPaletteFilter::update_global(cx, |filter, _| {
575 use editor::actions::{
576 AcceptEditPrediction, AcceptNextLineEditPrediction, AcceptNextWordEditPrediction,
577 NextEditPrediction, PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
578 };
579 let edit_prediction_actions = [
580 TypeId::of::<AcceptEditPrediction>(),
581 TypeId::of::<AcceptNextWordEditPrediction>(),
582 TypeId::of::<AcceptNextLineEditPrediction>(),
583 TypeId::of::<AcceptEditPrediction>(),
584 TypeId::of::<ShowEditPrediction>(),
585 TypeId::of::<NextEditPrediction>(),
586 TypeId::of::<PreviousEditPrediction>(),
587 TypeId::of::<ToggleEditPrediction>(),
588 ];
589
590 if disable_ai {
591 filter.hide_namespace("agent");
592 filter.hide_namespace("agents");
593 filter.hide_namespace("assistant");
594 filter.hide_namespace("copilot");
595 filter.hide_namespace("zed_predict_onboarding");
596 filter.hide_namespace("edit_prediction");
597
598 filter.hide_action_types(&edit_prediction_actions);
599 filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
600 } else {
601 if agent_enabled {
602 filter.show_namespace("agent");
603 filter.show_namespace("agents");
604 filter.show_namespace("assistant");
605 } else {
606 filter.hide_namespace("agent");
607 filter.hide_namespace("agents");
608 filter.hide_namespace("assistant");
609 }
610
611 match edit_prediction_provider {
612 EditPredictionProvider::None => {
613 filter.hide_namespace("edit_prediction");
614 filter.hide_namespace("copilot");
615 filter.hide_action_types(&edit_prediction_actions);
616 }
617 EditPredictionProvider::Copilot => {
618 filter.show_namespace("edit_prediction");
619 filter.show_namespace("copilot");
620 filter.show_action_types(edit_prediction_actions.iter());
621 }
622 EditPredictionProvider::Zed
623 | EditPredictionProvider::Codestral
624 | EditPredictionProvider::Ollama
625 | EditPredictionProvider::OpenAiCompatibleApi
626 | EditPredictionProvider::Mercury
627 | EditPredictionProvider::Experimental(_) => {
628 filter.show_namespace("edit_prediction");
629 filter.hide_namespace("copilot");
630 filter.show_action_types(edit_prediction_actions.iter());
631 }
632 }
633
634 filter.show_namespace("zed_predict_onboarding");
635 filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
636 }
637
638 if agent_v2_enabled {
639 filter.show_namespace("multi_workspace");
640 } else {
641 filter.hide_namespace("multi_workspace");
642 }
643 });
644}
645
646fn init_language_model_settings(cx: &mut App) {
647 update_active_language_model_from_settings(cx);
648
649 cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
650 .detach();
651 cx.subscribe(
652 &LanguageModelRegistry::global(cx),
653 |_, event: &language_model::Event, cx| match event {
654 language_model::Event::ProviderStateChanged(_)
655 | language_model::Event::AddedProvider(_)
656 | language_model::Event::RemovedProvider(_)
657 | language_model::Event::ProvidersChanged => {
658 update_active_language_model_from_settings(cx);
659 }
660 _ => {}
661 },
662 )
663 .detach();
664}
665
666fn update_active_language_model_from_settings(cx: &mut App) {
667 let settings = AgentSettings::get_global(cx);
668
669 fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
670 language_model::SelectedModel {
671 provider: LanguageModelProviderId::from(selection.provider.0.clone()),
672 model: LanguageModelId::from(selection.model.clone()),
673 }
674 }
675
676 let default = settings.default_model.as_ref().map(to_selected_model);
677 let inline_assistant = settings
678 .inline_assistant_model
679 .as_ref()
680 .map(to_selected_model);
681 let commit_message = settings
682 .commit_message_model
683 .as_ref()
684 .map(to_selected_model);
685 let thread_summary = settings
686 .thread_summary_model
687 .as_ref()
688 .map(to_selected_model);
689 let inline_alternatives = settings
690 .inline_alternatives
691 .iter()
692 .map(to_selected_model)
693 .collect::<Vec<_>>();
694
695 LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
696 registry.select_default_model(default.as_ref(), cx);
697 registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
698 registry.select_commit_message_model(commit_message.as_ref(), cx);
699 registry.select_thread_summary_model(thread_summary.as_ref(), cx);
700 registry.select_inline_alternative_models(inline_alternatives, cx);
701 });
702}
703
704#[cfg(test)]
705mod tests {
706 use super::*;
707 use agent_settings::{AgentProfileId, AgentSettings};
708 use command_palette_hooks::CommandPaletteFilter;
709 use db::kvp::KeyValueStore;
710 use editor::actions::AcceptEditPrediction;
711 use gpui::{BorrowAppContext, TestAppContext, px};
712 use project::DisableAiSettings;
713 use settings::{
714 DockPosition, NotifyWhenAgentWaiting, PlaySoundWhenAgentDone, Settings, SettingsStore,
715 };
716
717 #[gpui::test]
718 fn test_agent_command_palette_visibility(cx: &mut TestAppContext) {
719 // Init settings
720 cx.update(|cx| {
721 let store = SettingsStore::test(cx);
722 cx.set_global(store);
723 command_palette_hooks::init(cx);
724 AgentSettings::register(cx);
725 DisableAiSettings::register(cx);
726 AllLanguageSettings::register(cx);
727 });
728
729 let agent_settings = AgentSettings {
730 enabled: true,
731 button: true,
732 dock: DockPosition::Right,
733 flexible: true,
734 default_width: px(300.),
735 default_height: px(600.),
736 max_content_width: Some(px(850.)),
737 default_model: None,
738 inline_assistant_model: None,
739 inline_assistant_use_streaming_tools: false,
740 commit_message_model: None,
741 thread_summary_model: None,
742 inline_alternatives: vec![],
743 favorite_models: vec![],
744 default_profile: AgentProfileId::default(),
745 profiles: Default::default(),
746 notify_when_agent_waiting: NotifyWhenAgentWaiting::default(),
747 play_sound_when_agent_done: PlaySoundWhenAgentDone::Never,
748 single_file_review: false,
749 model_parameters: vec![],
750 enable_feedback: false,
751 expand_edit_card: true,
752 expand_terminal_card: true,
753 cancel_generation_on_terminal_stop: true,
754 use_modifier_to_send: true,
755 message_editor_min_lines: 1,
756 tool_permissions: Default::default(),
757 show_turn_stats: false,
758 show_merge_conflict_indicator: true,
759 new_thread_location: Default::default(),
760 sidebar_side: Default::default(),
761 thinking_display: Default::default(),
762 };
763
764 cx.update(|cx| {
765 AgentSettings::override_global(agent_settings.clone(), cx);
766 DisableAiSettings::override_global(DisableAiSettings { disable_ai: false }, cx);
767
768 // Initial update
769 update_command_palette_filter(cx);
770 });
771
772 // Assert visible
773 cx.update(|cx| {
774 let filter = CommandPaletteFilter::try_global(cx).unwrap();
775 assert!(
776 !filter.is_hidden(&NewThread),
777 "NewThread should be visible by default"
778 );
779 });
780
781 // Disable agent
782 cx.update(|cx| {
783 let mut new_settings = agent_settings.clone();
784 new_settings.enabled = false;
785 AgentSettings::override_global(new_settings, cx);
786
787 // Trigger update
788 update_command_palette_filter(cx);
789 });
790
791 // Assert hidden
792 cx.update(|cx| {
793 let filter = CommandPaletteFilter::try_global(cx).unwrap();
794 assert!(
795 filter.is_hidden(&NewThread),
796 "NewThread should be hidden when agent is disabled"
797 );
798 });
799
800 // Test EditPredictionProvider
801 // Enable EditPredictionProvider::Copilot
802 cx.update(|cx| {
803 cx.update_global::<SettingsStore, _>(|store, cx| {
804 store.update_user_settings(cx, |s| {
805 s.project
806 .all_languages
807 .edit_predictions
808 .get_or_insert(Default::default())
809 .provider = Some(EditPredictionProvider::Copilot);
810 });
811 });
812 update_command_palette_filter(cx);
813 });
814
815 cx.update(|cx| {
816 let filter = CommandPaletteFilter::try_global(cx).unwrap();
817 assert!(
818 !filter.is_hidden(&AcceptEditPrediction),
819 "EditPrediction should be visible when provider is Copilot"
820 );
821 });
822
823 // Disable EditPredictionProvider (None)
824 cx.update(|cx| {
825 cx.update_global::<SettingsStore, _>(|store, cx| {
826 store.update_user_settings(cx, |s| {
827 s.project
828 .all_languages
829 .edit_predictions
830 .get_or_insert(Default::default())
831 .provider = Some(EditPredictionProvider::None);
832 });
833 });
834 update_command_palette_filter(cx);
835 });
836
837 cx.update(|cx| {
838 let filter = CommandPaletteFilter::try_global(cx).unwrap();
839 assert!(
840 filter.is_hidden(&AcceptEditPrediction),
841 "EditPrediction should be hidden when provider is None"
842 );
843 });
844 }
845
846 async fn setup_backfill_test(cx: &mut TestAppContext) -> Arc<dyn Fs> {
847 let fs = fs::FakeFs::new(cx.background_executor.clone());
848 fs.save(
849 paths::settings_file().as_path(),
850 &"{}".into(),
851 Default::default(),
852 )
853 .await
854 .unwrap();
855
856 cx.update(|cx| {
857 cx.set_global(db::AppDatabase::test_new());
858 let store = SettingsStore::test(cx);
859 cx.set_global(store);
860 AgentSettings::register(cx);
861 DisableAiSettings::register(cx);
862 cx.set_staff(true);
863 });
864
865 fs
866 }
867
868 #[gpui::test]
869 async fn test_backfill_sets_kvp_flag(cx: &mut TestAppContext) {
870 let fs = setup_backfill_test(cx).await;
871
872 cx.update(|cx| {
873 let kvp = KeyValueStore::global(cx);
874 assert!(
875 kvp.read_kvp(PARALLEL_AGENT_LAYOUT_BACKFILL_KEY)
876 .unwrap()
877 .is_none()
878 );
879
880 maybe_backfill_editor_layout(fs.clone(), false, cx);
881 });
882
883 cx.run_until_parked();
884
885 let kvp = cx.update(|cx| KeyValueStore::global(cx));
886 assert!(
887 kvp.read_kvp(PARALLEL_AGENT_LAYOUT_BACKFILL_KEY)
888 .unwrap()
889 .is_some(),
890 "flag should be set after backfill"
891 );
892 }
893
894 #[gpui::test]
895 async fn test_backfill_new_install_sets_flag_without_writing_settings(cx: &mut TestAppContext) {
896 let fs = setup_backfill_test(cx).await;
897
898 cx.update(|cx| {
899 maybe_backfill_editor_layout(fs.clone(), true, cx);
900 });
901
902 cx.run_until_parked();
903
904 let kvp = cx.update(|cx| KeyValueStore::global(cx));
905 assert!(
906 kvp.read_kvp(PARALLEL_AGENT_LAYOUT_BACKFILL_KEY)
907 .unwrap()
908 .is_some(),
909 "flag should be set even for new installs"
910 );
911
912 let written = fs.load(paths::settings_file().as_path()).await.unwrap();
913 assert_eq!(written.trim(), "{}", "settings file should be unchanged");
914 }
915
916 #[gpui::test]
917 async fn test_backfill_is_idempotent(cx: &mut TestAppContext) {
918 let fs = setup_backfill_test(cx).await;
919
920 cx.update(|cx| {
921 maybe_backfill_editor_layout(fs.clone(), false, cx);
922 });
923
924 cx.run_until_parked();
925
926 let after_first = fs.load(paths::settings_file().as_path()).await.unwrap();
927
928 cx.update(|cx| {
929 maybe_backfill_editor_layout(fs.clone(), false, cx);
930 });
931
932 cx.run_until_parked();
933
934 let after_second = fs.load(paths::settings_file().as_path()).await.unwrap();
935 assert_eq!(
936 after_first, after_second,
937 "second call should not change settings"
938 );
939 }
940
941 #[test]
942 fn test_deserialize_external_agent_variants() {
943 assert_eq!(
944 serde_json::from_str::<Agent>(r#""NativeAgent""#).unwrap(),
945 Agent::NativeAgent,
946 );
947 assert_eq!(
948 serde_json::from_str::<Agent>(r#"{"Custom":{"name":"my-agent"}}"#).unwrap(),
949 Agent::Custom {
950 id: "my-agent".into(),
951 },
952 );
953 }
954}