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