agent_ui.rs

  1mod agent_configuration;
  2pub(crate) mod agent_connection_store;
  3mod agent_diff;
  4mod agent_model_selector;
  5mod agent_panel;
  6mod agent_registry_ui;
  7mod branch_names;
  8mod buffer_codegen;
  9mod completion_provider;
 10mod config_options;
 11mod context;
 12mod context_server_configuration;
 13pub(crate) mod conversation_view;
 14mod diagnostics;
 15mod entry_view_state;
 16mod external_source_prompt;
 17mod favorite_models;
 18mod inline_assistant;
 19mod inline_prompt_editor;
 20mod language_model_selector;
 21mod mention_set;
 22mod message_editor;
 23mod mode_selector;
 24mod model_selector;
 25mod model_selector_popover;
 26mod profile_selector;
 27mod terminal_codegen;
 28mod terminal_inline_assistant;
 29#[cfg(any(test, feature = "test-support"))]
 30pub mod test_support;
 31mod thread_branch_picker;
 32mod thread_history;
 33mod thread_history_view;
 34mod thread_import;
 35pub mod thread_metadata_store;
 36mod thread_worktree_picker;
 37pub mod threads_archive_view;
 38mod ui;
 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::{AgentV2FeatureFlag, 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 schemars::JsonSchema;
 61use serde::{Deserialize, Serialize};
 62use settings::{DockPosition, DockSide, LanguageModelSelection, Settings as _, SettingsStore};
 63use std::any::TypeId;
 64use workspace::Workspace;
 65
 66use crate::agent_configuration::{ConfigureContextServerModal, ManageProfilesModal};
 67pub use crate::agent_panel::{AgentPanel, AgentPanelEvent, WorktreeCreationStatus};
 68use crate::agent_registry_ui::AgentRegistryPage;
 69pub use crate::inline_assistant::InlineAssistant;
 70pub use agent_diff::{AgentDiffPane, AgentDiffToolbar};
 71pub(crate) 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::{AcpThreadImportOnboarding, ThreadImportModal};
 79use zed_actions;
 80
 81pub const DEFAULT_THREAD_TITLE: &str = "New Thread";
 82const PARALLEL_AGENT_LAYOUT_BACKFILL_KEY: &str = "parallel_agent_layout_backfilled";
 83
 84actions!(
 85    agent,
 86    [
 87        /// Toggles the menu to create new agent threads.
 88        ToggleNewThreadMenu,
 89        /// Cycles through the options for where new threads start (current project or new worktree).
 90        CycleStartThreadIn,
 91        /// Toggles the navigation menu for switching between threads and views.
 92        ToggleNavigationMenu,
 93        /// Toggles the options menu for agent settings and preferences.
 94        ToggleOptionsMenu,
 95        /// Toggles the profile or mode selector for switching between agent profiles.
 96        ToggleProfileSelector,
 97        /// Cycles through available session modes.
 98        CycleModeSelector,
 99        /// Cycles through favorited models in the ACP model selector.
100        CycleFavoriteModels,
101        /// Expands the message editor to full size.
102        ExpandMessageEditor,
103        /// Removes all thread history.
104        RemoveHistory,
105        /// Opens the conversation history view.
106        OpenHistory,
107        /// Adds a context server to the configuration.
108        AddContextServer,
109        /// Removes the currently selected thread.
110        RemoveSelectedThread,
111        /// Starts a chat conversation with follow-up enabled.
112        ChatWithFollow,
113        /// Cycles to the next inline assist suggestion.
114        CycleNextInlineAssist,
115        /// Cycles to the previous inline assist suggestion.
116        CyclePreviousInlineAssist,
117        /// Moves focus up in the interface.
118        FocusUp,
119        /// Moves focus down in the interface.
120        FocusDown,
121        /// Moves focus left in the interface.
122        FocusLeft,
123        /// Moves focus right in the interface.
124        FocusRight,
125        /// Opens the active thread as a markdown file.
126        OpenActiveThreadAsMarkdown,
127        /// Opens the agent diff view to review changes.
128        OpenAgentDiff,
129        /// Copies the current thread to the clipboard as JSON for debugging.
130        CopyThreadToClipboard,
131        /// Loads a thread from the clipboard JSON for debugging.
132        LoadThreadFromClipboard,
133        /// Keeps the current suggestion or change.
134        Keep,
135        /// Rejects the current suggestion or change.
136        Reject,
137        /// Rejects all suggestions or changes.
138        RejectAll,
139        /// Undoes the most recent reject operation, restoring the rejected changes.
140        UndoLastReject,
141        /// Keeps all suggestions or changes.
142        KeepAll,
143        /// Allow this operation only this time.
144        AllowOnce,
145        /// Allow this operation and remember the choice.
146        AllowAlways,
147        /// Reject this operation only this time.
148        RejectOnce,
149        /// Follows the agent's suggestions.
150        Follow,
151        /// Resets the trial upsell notification.
152        ResetTrialUpsell,
153        /// Resets the trial end upsell notification.
154        ResetTrialEndUpsell,
155        /// Opens the "Add Context" menu in the message editor.
156        OpenAddContextMenu,
157        /// Continues the current thread.
158        ContinueThread,
159        /// Interrupts the current generation and sends the message immediately.
160        SendImmediately,
161        /// Sends the next queued message immediately.
162        SendNextQueuedMessage,
163        /// Removes the first message from the queue (the next one to be sent).
164        RemoveFirstQueuedMessage,
165        /// Edits the first message in the queue (the next one to be sent).
166        EditFirstQueuedMessage,
167        /// Clears all messages from the queue.
168        ClearMessageQueue,
169        /// Opens the permission granularity dropdown for the current tool call.
170        OpenPermissionDropdown,
171        /// Toggles thinking mode for models that support extended thinking.
172        ToggleThinkingMode,
173        /// Cycles through available thinking effort levels for the current model.
174        CycleThinkingEffort,
175        /// Toggles the thinking effort selector menu open or closed.
176        ToggleThinkingEffortMenu,
177        /// Toggles fast mode for models that support it.
178        ToggleFastMode,
179        /// Scroll the output by one page up.
180        ScrollOutputPageUp,
181        /// Scroll the output by one page down.
182        ScrollOutputPageDown,
183        /// Scroll the output up by three lines.
184        ScrollOutputLineUp,
185        /// Scroll the output down by three lines.
186        ScrollOutputLineDown,
187        /// Scroll the output to the top.
188        ScrollOutputToTop,
189        /// Scroll the output to the bottom.
190        ScrollOutputToBottom,
191        /// Scroll the output to the previous user message.
192        ScrollOutputToPreviousMessage,
193        /// Scroll the output to the next user message.
194        ScrollOutputToNextMessage,
195    ]
196);
197
198/// Action to authorize a tool call with a specific permission option.
199/// This is used by the permission granularity dropdown to authorize tool calls.
200#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
201#[action(namespace = agent)]
202#[serde(deny_unknown_fields)]
203pub struct AuthorizeToolCall {
204    /// The tool call ID to authorize.
205    pub tool_call_id: String,
206    /// The permission option ID to use.
207    pub option_id: String,
208    /// The kind of permission option (serialized as string).
209    pub option_kind: String,
210}
211
212/// Action to select a permission granularity option from the dropdown.
213/// This updates the selected granularity without triggering authorization.
214#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
215#[action(namespace = agent)]
216#[serde(deny_unknown_fields)]
217pub struct SelectPermissionGranularity {
218    /// The tool call ID for which to select the granularity.
219    pub tool_call_id: String,
220    /// The index of the selected granularity option.
221    pub index: usize,
222}
223
224/// Action to toggle a command pattern checkbox in the permission dropdown.
225#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
226#[action(namespace = agent)]
227#[serde(deny_unknown_fields)]
228pub struct ToggleCommandPattern {
229    /// The tool call ID for which to toggle the pattern.
230    pub tool_call_id: String,
231    /// The index of the command pattern to toggle.
232    pub pattern_index: usize,
233}
234
235/// Creates a new conversation thread, optionally based on an existing thread.
236#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
237#[action(namespace = agent)]
238#[serde(deny_unknown_fields)]
239pub struct NewThread;
240
241/// Creates a new external agent conversation thread.
242#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
243#[action(namespace = agent)]
244#[serde(deny_unknown_fields)]
245pub struct NewExternalAgentThread {
246    /// Which agent to use for the conversation.
247    agent: Option<Agent>,
248}
249
250#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
251#[action(namespace = agent)]
252#[serde(deny_unknown_fields)]
253pub struct NewNativeAgentThreadFromSummary {
254    from_session_id: agent_client_protocol::SessionId,
255}
256
257#[derive(Debug, Default, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)]
258#[serde(rename_all = "snake_case")]
259pub enum Agent {
260    #[default]
261    #[serde(alias = "NativeAgent", alias = "TextThread")]
262    NativeAgent,
263    #[serde(alias = "Custom")]
264    Custom {
265        #[serde(rename = "name")]
266        id: AgentId,
267    },
268}
269
270impl From<AgentId> for Agent {
271    fn from(id: AgentId) -> Self {
272        if id.as_ref() == agent::ZED_AGENT_ID.as_ref() {
273            Self::NativeAgent
274        } else {
275            Self::Custom { id }
276        }
277    }
278}
279
280impl Agent {
281    pub fn id(&self) -> AgentId {
282        match self {
283            Self::NativeAgent => agent::ZED_AGENT_ID.clone(),
284            Self::Custom { id } => id.clone(),
285        }
286    }
287
288    pub fn is_native(&self) -> bool {
289        matches!(self, Self::NativeAgent)
290    }
291
292    pub fn label(&self) -> SharedString {
293        match self {
294            Self::NativeAgent => "Zed Agent".into(),
295            Self::Custom { id, .. } => id.0.clone(),
296        }
297    }
298
299    pub fn icon(&self) -> Option<IconName> {
300        match self {
301            Self::NativeAgent => None,
302            Self::Custom { .. } => Some(IconName::Sparkle),
303        }
304    }
305
306    pub fn server(
307        &self,
308        fs: Arc<dyn fs::Fs>,
309        thread_store: Entity<agent::ThreadStore>,
310    ) -> Rc<dyn agent_servers::AgentServer> {
311        match self {
312            Self::NativeAgent => Rc::new(agent::NativeAgentServer::new(fs, thread_store)),
313            Self::Custom { id: name } => {
314                Rc::new(agent_servers::CustomAgentServer::new(name.clone()))
315            }
316        }
317    }
318}
319
320/// Describes which branch to use when creating a new git worktree.
321#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
322#[serde(rename_all = "snake_case", tag = "kind")]
323pub enum NewWorktreeBranchTarget {
324    /// Create a new randomly named branch from the current HEAD.
325    /// Will match worktree name if the newly created worktree was also randomly named.
326    #[default]
327    CurrentBranch,
328    /// Check out an existing branch, or create a new branch from it if it's
329    /// already occupied by another worktree.
330    ExistingBranch { name: String },
331    /// Create a new branch with an explicit name, optionally from a specific ref.
332    CreateBranch {
333        name: String,
334        #[serde(default)]
335        from_ref: Option<String>,
336    },
337}
338
339/// Sets where new threads will run.
340#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema, Action)]
341#[action(namespace = agent)]
342#[serde(rename_all = "snake_case", tag = "kind")]
343pub enum StartThreadIn {
344    #[default]
345    LocalProject,
346    NewWorktree {
347        /// When this is None, Zed will randomly generate a worktree name
348        /// otherwise, the provided name will be used.
349        #[serde(default)]
350        worktree_name: Option<String>,
351        #[serde(default)]
352        branch_target: NewWorktreeBranchTarget,
353    },
354    /// A linked worktree that already exists on disk.
355    LinkedWorktree { path: PathBuf, display_name: String },
356}
357
358/// Content to initialize new external agent with.
359pub enum AgentInitialContent {
360    ThreadSummary {
361        session_id: acp::SessionId,
362        title: Option<SharedString>,
363    },
364    ContentBlock {
365        blocks: Vec<agent_client_protocol::ContentBlock>,
366        auto_submit: bool,
367    },
368    FromExternalSource(ExternalSourcePrompt),
369}
370
371impl From<ExternalSourcePrompt> for AgentInitialContent {
372    fn from(prompt: ExternalSourcePrompt) -> Self {
373        Self::FromExternalSource(prompt)
374    }
375}
376
377/// Opens the profile management interface for configuring agent tools and settings.
378#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
379#[action(namespace = agent)]
380#[serde(deny_unknown_fields)]
381pub struct ManageProfiles {
382    #[serde(default)]
383    pub customize_tools: Option<AgentProfileId>,
384}
385
386impl ManageProfiles {
387    pub fn customize_tools(profile_id: AgentProfileId) -> Self {
388        Self {
389            customize_tools: Some(profile_id),
390        }
391    }
392}
393
394#[derive(Clone)]
395pub(crate) enum ModelUsageContext {
396    InlineAssistant,
397}
398
399impl ModelUsageContext {
400    pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
401        match self {
402            Self::InlineAssistant => {
403                LanguageModelRegistry::read_global(cx).inline_assistant_model()
404            }
405        }
406    }
407}
408
409pub(crate) fn humanize_token_count(count: u64) -> String {
410    match count {
411        0..=999 => count.to_string(),
412        1000..=9999 => {
413            let thousands = count / 1000;
414            let hundreds = (count % 1000 + 50) / 100;
415            if hundreds == 0 {
416                format!("{}k", thousands)
417            } else if hundreds == 10 {
418                format!("{}k", thousands + 1)
419            } else {
420                format!("{}.{}k", thousands, hundreds)
421            }
422        }
423        10_000..=999_999 => format!("{}k", (count + 500) / 1000),
424        1_000_000..=9_999_999 => {
425            let millions = count / 1_000_000;
426            let hundred_thousands = (count % 1_000_000 + 50_000) / 100_000;
427            if hundred_thousands == 0 {
428                format!("{}M", millions)
429            } else if hundred_thousands == 10 {
430                format!("{}M", millions + 1)
431            } else {
432                format!("{}.{}M", millions, hundred_thousands)
433            }
434        }
435        10_000_000.. => format!("{}M", (count + 500_000) / 1_000_000),
436    }
437}
438
439/// Initializes the `agent` crate.
440pub fn init(
441    fs: Arc<dyn Fs>,
442    prompt_builder: Arc<PromptBuilder>,
443    language_registry: Arc<LanguageRegistry>,
444    is_new_install: bool,
445    is_eval: bool,
446    cx: &mut App,
447) {
448    agent::ThreadStore::init_global(cx);
449    rules_library::init(cx);
450    if !is_eval {
451        // Initializing the language model from the user settings messes with the eval, so we only initialize them when
452        // we're not running inside of the eval.
453        init_language_model_settings(cx);
454    }
455    agent_panel::init(cx);
456    context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
457    thread_metadata_store::init(cx);
458
459    inline_assistant::init(fs.clone(), prompt_builder.clone(), cx);
460    terminal_inline_assistant::init(fs.clone(), prompt_builder, cx);
461    cx.observe_new(move |workspace, window, cx| {
462        ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
463    })
464    .detach();
465    cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
466        workspace.register_action(
467            move |workspace: &mut Workspace,
468                  _: &zed_actions::AcpRegistry,
469                  window: &mut Window,
470                  cx: &mut Context<Workspace>| {
471                let existing = workspace
472                    .active_pane()
473                    .read(cx)
474                    .items()
475                    .find_map(|item| item.downcast::<AgentRegistryPage>());
476
477                if let Some(existing) = existing {
478                    existing.update(cx, |_, cx| {
479                        project::AgentRegistryStore::global(cx)
480                            .update(cx, |store, cx| store.refresh(cx));
481                    });
482                    workspace.activate_item(&existing, true, true, window, cx);
483                } else {
484                    let registry_page = AgentRegistryPage::new(workspace, window, cx);
485                    workspace.add_item_to_active_pane(
486                        Box::new(registry_page),
487                        None,
488                        true,
489                        window,
490                        cx,
491                    );
492                }
493            },
494        );
495    })
496    .detach();
497    cx.observe_new(ManageProfilesModal::register).detach();
498
499    // Update command palette filter based on AI settings
500    update_command_palette_filter(cx);
501
502    // Watch for settings changes
503    cx.observe_global::<SettingsStore>(|app_cx| {
504        // When settings change, update the command palette filter
505        update_command_palette_filter(app_cx);
506    })
507    .detach();
508
509    cx.on_flags_ready(|_, cx| {
510        update_command_palette_filter(cx);
511    })
512    .detach();
513
514    // TODO: remove this field when we're ready remove the feature flag
515    maybe_backfill_editor_layout(fs, is_new_install, false, cx);
516
517    cx.observe_flag::<AgentV2FeatureFlag, _>(|is_enabled, cx| {
518        SettingsStore::update_global(cx, |store, cx| {
519            store.update_default_settings(cx, |defaults| {
520                if is_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    .detach();
539}
540
541fn maybe_backfill_editor_layout(
542    fs: Arc<dyn Fs>,
543    is_new_install: bool,
544    should_run: bool,
545    cx: &mut App,
546) {
547    if !should_run {
548        return;
549    }
550
551    let kvp = db::kvp::KeyValueStore::global(cx);
552    let already_backfilled =
553        util::ResultExt::log_err(kvp.read_kvp(PARALLEL_AGENT_LAYOUT_BACKFILL_KEY))
554            .flatten()
555            .is_some();
556
557    if !already_backfilled {
558        if !is_new_install {
559            AgentSettings::backfill_editor_layout(fs, cx);
560        }
561
562        db::write_and_log(cx, move || async move {
563            kvp.write_kvp(
564                PARALLEL_AGENT_LAYOUT_BACKFILL_KEY.to_string(),
565                "1".to_string(),
566            )
567            .await
568        });
569    }
570}
571
572fn update_command_palette_filter(cx: &mut App) {
573    let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
574    let agent_enabled = AgentSettings::get_global(cx).enabled;
575    let agent_v2_enabled = cx.has_flag::<AgentV2FeatureFlag>();
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 feature_flags::FeatureFlagAppExt;
718    use gpui::{BorrowAppContext, TestAppContext, px};
719    use project::DisableAiSettings;
720    use settings::{
721        DockPosition, NotifyWhenAgentWaiting, PlaySoundWhenAgentDone, Settings, SettingsStore,
722    };
723
724    #[gpui::test]
725    fn test_agent_command_palette_visibility(cx: &mut TestAppContext) {
726        // Init settings
727        cx.update(|cx| {
728            let store = SettingsStore::test(cx);
729            cx.set_global(store);
730            command_palette_hooks::init(cx);
731            AgentSettings::register(cx);
732            DisableAiSettings::register(cx);
733            AllLanguageSettings::register(cx);
734        });
735
736        let agent_settings = AgentSettings {
737            enabled: true,
738            button: true,
739            dock: DockPosition::Right,
740            flexible: true,
741            default_width: px(300.),
742            default_height: px(600.),
743            max_content_width: px(850.),
744            default_model: None,
745            inline_assistant_model: None,
746            inline_assistant_use_streaming_tools: false,
747            commit_message_model: None,
748            thread_summary_model: None,
749            inline_alternatives: vec![],
750            favorite_models: vec![],
751            default_profile: AgentProfileId::default(),
752            profiles: Default::default(),
753            notify_when_agent_waiting: NotifyWhenAgentWaiting::default(),
754            play_sound_when_agent_done: PlaySoundWhenAgentDone::Never,
755            single_file_review: false,
756            model_parameters: vec![],
757            enable_feedback: false,
758            expand_edit_card: true,
759            expand_terminal_card: true,
760            cancel_generation_on_terminal_stop: true,
761            use_modifier_to_send: true,
762            message_editor_min_lines: 1,
763            tool_permissions: Default::default(),
764            show_turn_stats: false,
765            show_merge_conflict_indicator: true,
766            new_thread_location: Default::default(),
767            sidebar_side: Default::default(),
768            thinking_display: Default::default(),
769        };
770
771        cx.update(|cx| {
772            AgentSettings::override_global(agent_settings.clone(), cx);
773            DisableAiSettings::override_global(DisableAiSettings { disable_ai: false }, cx);
774
775            // Initial update
776            update_command_palette_filter(cx);
777        });
778
779        // Assert visible
780        cx.update(|cx| {
781            let filter = CommandPaletteFilter::try_global(cx).unwrap();
782            assert!(
783                !filter.is_hidden(&NewThread),
784                "NewThread should be visible by default"
785            );
786        });
787
788        // Disable agent
789        cx.update(|cx| {
790            let mut new_settings = agent_settings.clone();
791            new_settings.enabled = false;
792            AgentSettings::override_global(new_settings, cx);
793
794            // Trigger update
795            update_command_palette_filter(cx);
796        });
797
798        // Assert hidden
799        cx.update(|cx| {
800            let filter = CommandPaletteFilter::try_global(cx).unwrap();
801            assert!(
802                filter.is_hidden(&NewThread),
803                "NewThread should be hidden when agent is disabled"
804            );
805        });
806
807        // Test EditPredictionProvider
808        // Enable EditPredictionProvider::Copilot
809        cx.update(|cx| {
810            cx.update_global::<SettingsStore, _>(|store, cx| {
811                store.update_user_settings(cx, |s| {
812                    s.project
813                        .all_languages
814                        .edit_predictions
815                        .get_or_insert(Default::default())
816                        .provider = Some(EditPredictionProvider::Copilot);
817                });
818            });
819            update_command_palette_filter(cx);
820        });
821
822        cx.update(|cx| {
823            let filter = CommandPaletteFilter::try_global(cx).unwrap();
824            assert!(
825                !filter.is_hidden(&AcceptEditPrediction),
826                "EditPrediction should be visible when provider is Copilot"
827            );
828        });
829
830        // Disable EditPredictionProvider (None)
831        cx.update(|cx| {
832            cx.update_global::<SettingsStore, _>(|store, cx| {
833                store.update_user_settings(cx, |s| {
834                    s.project
835                        .all_languages
836                        .edit_predictions
837                        .get_or_insert(Default::default())
838                        .provider = Some(EditPredictionProvider::None);
839                });
840            });
841            update_command_palette_filter(cx);
842        });
843
844        cx.update(|cx| {
845            let filter = CommandPaletteFilter::try_global(cx).unwrap();
846            assert!(
847                filter.is_hidden(&AcceptEditPrediction),
848                "EditPrediction should be hidden when provider is None"
849            );
850        });
851    }
852
853    async fn setup_backfill_test(cx: &mut TestAppContext) -> Arc<dyn Fs> {
854        let fs = fs::FakeFs::new(cx.background_executor.clone());
855        fs.save(
856            paths::settings_file().as_path(),
857            &"{}".into(),
858            Default::default(),
859        )
860        .await
861        .unwrap();
862
863        cx.update(|cx| {
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, true, 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, 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, true, 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, true, 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}