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