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