agent_ui.rs

  1mod acp;
  2mod agent_configuration;
  3mod agent_diff;
  4mod agent_model_selector;
  5mod agent_panel;
  6mod buffer_codegen;
  7mod completion_provider;
  8mod context;
  9mod context_server_configuration;
 10#[cfg(test)]
 11mod evals;
 12mod inline_assistant;
 13mod inline_prompt_editor;
 14mod language_model_selector;
 15mod mention_set;
 16mod profile_selector;
 17mod slash_command;
 18mod slash_command_picker;
 19mod terminal_codegen;
 20mod terminal_inline_assistant;
 21mod text_thread_editor;
 22mod ui;
 23
 24use std::rc::Rc;
 25use std::sync::Arc;
 26
 27use agent_settings::{AgentProfileId, AgentSettings};
 28use assistant_slash_command::SlashCommandRegistry;
 29use client::Client;
 30use command_palette_hooks::CommandPaletteFilter;
 31use feature_flags::FeatureFlagAppExt as _;
 32use fs::Fs;
 33use gpui::{Action, App, Entity, SharedString, actions};
 34use language::{
 35    LanguageRegistry,
 36    language_settings::{AllLanguageSettings, EditPredictionProvider},
 37};
 38use language_model::{
 39    ConfiguredModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
 40};
 41use project::DisableAiSettings;
 42use prompt_store::PromptBuilder;
 43use schemars::JsonSchema;
 44use serde::{Deserialize, Serialize};
 45use settings::{LanguageModelSelection, Settings as _, SettingsStore};
 46use std::any::TypeId;
 47
 48use crate::agent_configuration::{ConfigureContextServerModal, ManageProfilesModal};
 49pub use crate::agent_panel::{AgentPanel, ConcreteAssistantPanelDelegate};
 50pub use crate::inline_assistant::InlineAssistant;
 51pub use agent_diff::{AgentDiffPane, AgentDiffToolbar};
 52pub use text_thread_editor::{AgentPanelDelegate, TextThreadEditor};
 53use zed_actions;
 54
 55actions!(
 56    agent,
 57    [
 58        /// Creates a new text-based conversation thread.
 59        NewTextThread,
 60        /// Toggles the menu to create new agent threads.
 61        ToggleNewThreadMenu,
 62        /// Toggles the navigation menu for switching between threads and views.
 63        ToggleNavigationMenu,
 64        /// Toggles the options menu for agent settings and preferences.
 65        ToggleOptionsMenu,
 66        /// Deletes the recently opened thread from history.
 67        DeleteRecentlyOpenThread,
 68        /// Toggles the profile or mode selector for switching between agent profiles.
 69        ToggleProfileSelector,
 70        /// Cycles through available session modes.
 71        CycleModeSelector,
 72        /// Expands the message editor to full size.
 73        ExpandMessageEditor,
 74        /// Removes all thread history.
 75        RemoveHistory,
 76        /// Opens the conversation history view.
 77        OpenHistory,
 78        /// Adds a context server to the configuration.
 79        AddContextServer,
 80        /// Removes the currently selected thread.
 81        RemoveSelectedThread,
 82        /// Starts a chat conversation with follow-up enabled.
 83        ChatWithFollow,
 84        /// Cycles to the next inline assist suggestion.
 85        CycleNextInlineAssist,
 86        /// Cycles to the previous inline assist suggestion.
 87        CyclePreviousInlineAssist,
 88        /// Moves focus up in the interface.
 89        FocusUp,
 90        /// Moves focus down in the interface.
 91        FocusDown,
 92        /// Moves focus left in the interface.
 93        FocusLeft,
 94        /// Moves focus right in the interface.
 95        FocusRight,
 96        /// Opens the active thread as a markdown file.
 97        OpenActiveThreadAsMarkdown,
 98        /// Opens the agent diff view to review changes.
 99        OpenAgentDiff,
100        /// Keeps the current suggestion or change.
101        Keep,
102        /// Rejects the current suggestion or change.
103        Reject,
104        /// Rejects all suggestions or changes.
105        RejectAll,
106        /// Keeps all suggestions or changes.
107        KeepAll,
108        /// Allow this operation only this time.
109        AllowOnce,
110        /// Allow this operation and remember the choice.
111        AllowAlways,
112        /// Reject this operation only this time.
113        RejectOnce,
114        /// Follows the agent's suggestions.
115        Follow,
116        /// Resets the trial upsell notification.
117        ResetTrialUpsell,
118        /// Resets the trial end upsell notification.
119        ResetTrialEndUpsell,
120        /// Continues the current thread.
121        ContinueThread,
122        /// Continues the thread with burn mode enabled.
123        ContinueWithBurnMode,
124        /// Toggles burn mode for faster responses.
125        ToggleBurnMode,
126    ]
127);
128
129/// Creates a new conversation thread, optionally based on an existing thread.
130#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
131#[action(namespace = agent)]
132#[serde(deny_unknown_fields)]
133pub struct NewThread;
134
135/// Creates a new external agent conversation thread.
136#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
137#[action(namespace = agent)]
138#[serde(deny_unknown_fields)]
139pub struct NewExternalAgentThread {
140    /// Which agent to use for the conversation.
141    agent: Option<ExternalAgent>,
142}
143
144#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
145#[action(namespace = agent)]
146#[serde(deny_unknown_fields)]
147pub struct NewNativeAgentThreadFromSummary {
148    from_session_id: agent_client_protocol::SessionId,
149}
150
151// TODO unify this with AgentType
152#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
153#[serde(rename_all = "snake_case")]
154pub enum ExternalAgent {
155    Gemini,
156    ClaudeCode,
157    Codex,
158    NativeAgent,
159    Custom { name: SharedString },
160}
161
162impl ExternalAgent {
163    pub fn parse_built_in(server: &dyn agent_servers::AgentServer) -> Option<Self> {
164        match server.telemetry_id() {
165            "gemini-cli" => Some(Self::Gemini),
166            "claude-code" => Some(Self::ClaudeCode),
167            "codex" => Some(Self::Codex),
168            "zed" => Some(Self::NativeAgent),
169            _ => None,
170        }
171    }
172
173    pub fn server(
174        &self,
175        fs: Arc<dyn fs::Fs>,
176        history: Entity<agent::HistoryStore>,
177    ) -> Rc<dyn agent_servers::AgentServer> {
178        match self {
179            Self::Gemini => Rc::new(agent_servers::Gemini),
180            Self::ClaudeCode => Rc::new(agent_servers::ClaudeCode),
181            Self::Codex => Rc::new(agent_servers::Codex),
182            Self::NativeAgent => Rc::new(agent::NativeAgentServer::new(fs, history)),
183            Self::Custom { name } => Rc::new(agent_servers::CustomAgentServer::new(name.clone())),
184        }
185    }
186}
187
188/// Opens the profile management interface for configuring agent tools and settings.
189#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
190#[action(namespace = agent)]
191#[serde(deny_unknown_fields)]
192pub struct ManageProfiles {
193    #[serde(default)]
194    pub customize_tools: Option<AgentProfileId>,
195}
196
197impl ManageProfiles {
198    pub fn customize_tools(profile_id: AgentProfileId) -> Self {
199        Self {
200            customize_tools: Some(profile_id),
201        }
202    }
203}
204
205#[derive(Clone)]
206pub(crate) enum ModelUsageContext {
207    InlineAssistant,
208}
209
210impl ModelUsageContext {
211    pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
212        match self {
213            Self::InlineAssistant => {
214                LanguageModelRegistry::read_global(cx).inline_assistant_model()
215            }
216        }
217    }
218}
219
220/// Initializes the `agent` crate.
221pub fn init(
222    fs: Arc<dyn Fs>,
223    client: Arc<Client>,
224    prompt_builder: Arc<PromptBuilder>,
225    language_registry: Arc<LanguageRegistry>,
226    is_eval: bool,
227    cx: &mut App,
228) {
229    assistant_text_thread::init(client.clone(), cx);
230    rules_library::init(cx);
231    if !is_eval {
232        // Initializing the language model from the user settings messes with the eval, so we only initialize them when
233        // we're not running inside of the eval.
234        init_language_model_settings(cx);
235    }
236    assistant_slash_command::init(cx);
237    agent_panel::init(cx);
238    context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
239    TextThreadEditor::init(cx);
240
241    register_slash_commands(cx);
242    inline_assistant::init(
243        fs.clone(),
244        prompt_builder.clone(),
245        client.telemetry().clone(),
246        cx,
247    );
248    terminal_inline_assistant::init(fs.clone(), prompt_builder, client.telemetry().clone(), cx);
249    cx.observe_new(move |workspace, window, cx| {
250        ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
251    })
252    .detach();
253    cx.observe_new(ManageProfilesModal::register).detach();
254
255    // Update command palette filter based on AI settings
256    update_command_palette_filter(cx);
257
258    // Watch for settings changes
259    cx.observe_global::<SettingsStore>(|app_cx| {
260        // When settings change, update the command palette filter
261        update_command_palette_filter(app_cx);
262    })
263    .detach();
264}
265
266fn update_command_palette_filter(cx: &mut App) {
267    let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
268    let agent_enabled = AgentSettings::get_global(cx).enabled;
269    let edit_prediction_provider = AllLanguageSettings::get_global(cx)
270        .edit_predictions
271        .provider;
272
273    CommandPaletteFilter::update_global(cx, |filter, _| {
274        use editor::actions::{
275            AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
276            PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
277        };
278        let edit_prediction_actions = [
279            TypeId::of::<AcceptEditPrediction>(),
280            TypeId::of::<AcceptPartialEditPrediction>(),
281            TypeId::of::<ShowEditPrediction>(),
282            TypeId::of::<NextEditPrediction>(),
283            TypeId::of::<PreviousEditPrediction>(),
284            TypeId::of::<ToggleEditPrediction>(),
285        ];
286
287        if disable_ai {
288            filter.hide_namespace("agent");
289            filter.hide_namespace("assistant");
290            filter.hide_namespace("copilot");
291            filter.hide_namespace("supermaven");
292            filter.hide_namespace("zed_predict_onboarding");
293            filter.hide_namespace("edit_prediction");
294
295            filter.hide_action_types(&edit_prediction_actions);
296            filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
297        } else {
298            if agent_enabled {
299                filter.show_namespace("agent");
300            } else {
301                filter.hide_namespace("agent");
302            }
303
304            filter.show_namespace("assistant");
305
306            match edit_prediction_provider {
307                EditPredictionProvider::None => {
308                    filter.hide_namespace("edit_prediction");
309                    filter.hide_namespace("copilot");
310                    filter.hide_namespace("supermaven");
311                    filter.hide_action_types(&edit_prediction_actions);
312                }
313                EditPredictionProvider::Copilot => {
314                    filter.show_namespace("edit_prediction");
315                    filter.show_namespace("copilot");
316                    filter.hide_namespace("supermaven");
317                    filter.show_action_types(edit_prediction_actions.iter());
318                }
319                EditPredictionProvider::Supermaven => {
320                    filter.show_namespace("edit_prediction");
321                    filter.hide_namespace("copilot");
322                    filter.show_namespace("supermaven");
323                    filter.show_action_types(edit_prediction_actions.iter());
324                }
325                EditPredictionProvider::Zed
326                | EditPredictionProvider::Codestral
327                | EditPredictionProvider::Experimental(_) => {
328                    filter.show_namespace("edit_prediction");
329                    filter.hide_namespace("copilot");
330                    filter.hide_namespace("supermaven");
331                    filter.show_action_types(edit_prediction_actions.iter());
332                }
333            }
334
335            filter.show_namespace("zed_predict_onboarding");
336            filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
337        }
338    });
339}
340
341fn init_language_model_settings(cx: &mut App) {
342    update_active_language_model_from_settings(cx);
343
344    cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
345        .detach();
346    cx.subscribe(
347        &LanguageModelRegistry::global(cx),
348        |_, event: &language_model::Event, cx| match event {
349            language_model::Event::ProviderStateChanged(_) => {
350                update_active_language_model_from_settings(cx);
351            }
352            language_model::Event::AddedProvider(_) => {
353                update_active_language_model_from_settings(cx);
354            }
355            language_model::Event::RemovedProvider(_) => {
356                update_active_language_model_from_settings(cx);
357            }
358            _ => {}
359        },
360    )
361    .detach();
362}
363
364fn update_active_language_model_from_settings(cx: &mut App) {
365    let settings = AgentSettings::get_global(cx);
366
367    fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
368        language_model::SelectedModel {
369            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
370            model: LanguageModelId::from(selection.model.clone()),
371        }
372    }
373
374    let default = settings.default_model.as_ref().map(to_selected_model);
375    let inline_assistant = settings
376        .inline_assistant_model
377        .as_ref()
378        .map(to_selected_model);
379    let commit_message = settings
380        .commit_message_model
381        .as_ref()
382        .map(to_selected_model);
383    let thread_summary = settings
384        .thread_summary_model
385        .as_ref()
386        .map(to_selected_model);
387    let inline_alternatives = settings
388        .inline_alternatives
389        .iter()
390        .map(to_selected_model)
391        .collect::<Vec<_>>();
392
393    LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
394        registry.select_default_model(default.as_ref(), cx);
395        registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
396        registry.select_commit_message_model(commit_message.as_ref(), cx);
397        registry.select_thread_summary_model(thread_summary.as_ref(), cx);
398        registry.select_inline_alternative_models(inline_alternatives, cx);
399    });
400}
401
402fn register_slash_commands(cx: &mut App) {
403    let slash_command_registry = SlashCommandRegistry::global(cx);
404
405    slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
406    slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
407    slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
408    slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
409    slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
410    slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
411    slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
412    slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
413    slash_command_registry
414        .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
415    slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
416
417    cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
418        move |is_enabled, _cx| {
419            if is_enabled {
420                slash_command_registry.register_command(
421                    assistant_slash_commands::StreamingExampleSlashCommand,
422                    false,
423                );
424            }
425        }
426    })
427    .detach();
428}
429
430#[cfg(test)]
431mod tests {
432    use super::*;
433    use agent_settings::{AgentProfileId, AgentSettings, CompletionMode};
434    use command_palette_hooks::CommandPaletteFilter;
435    use editor::actions::AcceptEditPrediction;
436    use gpui::{BorrowAppContext, TestAppContext, px};
437    use project::DisableAiSettings;
438    use settings::{
439        DefaultAgentView, DockPosition, NotifyWhenAgentWaiting, Settings, SettingsStore,
440    };
441
442    #[gpui::test]
443    fn test_agent_command_palette_visibility(cx: &mut TestAppContext) {
444        // Init settings
445        cx.update(|cx| {
446            let store = SettingsStore::test(cx);
447            cx.set_global(store);
448            command_palette_hooks::init(cx);
449            AgentSettings::register(cx);
450            DisableAiSettings::register(cx);
451            AllLanguageSettings::register(cx);
452        });
453
454        let agent_settings = AgentSettings {
455            enabled: true,
456            button: true,
457            dock: DockPosition::Right,
458            default_width: px(300.),
459            default_height: px(600.),
460            default_model: None,
461            inline_assistant_model: None,
462            commit_message_model: None,
463            thread_summary_model: None,
464            inline_alternatives: vec![],
465            default_profile: AgentProfileId::default(),
466            default_view: DefaultAgentView::Thread,
467            profiles: Default::default(),
468            always_allow_tool_actions: false,
469            notify_when_agent_waiting: NotifyWhenAgentWaiting::default(),
470            play_sound_when_agent_done: false,
471            single_file_review: false,
472            model_parameters: vec![],
473            preferred_completion_mode: CompletionMode::Normal,
474            enable_feedback: false,
475            expand_edit_card: true,
476            expand_terminal_card: true,
477            use_modifier_to_send: true,
478            message_editor_min_lines: 1,
479        };
480
481        cx.update(|cx| {
482            AgentSettings::override_global(agent_settings.clone(), cx);
483            DisableAiSettings::override_global(DisableAiSettings { disable_ai: false }, cx);
484
485            // Initial update
486            update_command_palette_filter(cx);
487        });
488
489        // Assert visible
490        cx.update(|cx| {
491            let filter = CommandPaletteFilter::try_global(cx).unwrap();
492            assert!(
493                !filter.is_hidden(&NewThread),
494                "NewThread should be visible by default"
495            );
496        });
497
498        // Disable agent
499        cx.update(|cx| {
500            let mut new_settings = agent_settings.clone();
501            new_settings.enabled = false;
502            AgentSettings::override_global(new_settings, cx);
503
504            // Trigger update
505            update_command_palette_filter(cx);
506        });
507
508        // Assert hidden
509        cx.update(|cx| {
510            let filter = CommandPaletteFilter::try_global(cx).unwrap();
511            assert!(
512                filter.is_hidden(&NewThread),
513                "NewThread should be hidden when agent is disabled"
514            );
515        });
516
517        // Test EditPredictionProvider
518        // Enable EditPredictionProvider::Copilot
519        cx.update(|cx| {
520            cx.update_global::<SettingsStore, _>(|store, cx| {
521                store.update_user_settings(cx, |s| {
522                    s.project
523                        .all_languages
524                        .features
525                        .get_or_insert(Default::default())
526                        .edit_prediction_provider = Some(EditPredictionProvider::Copilot);
527                });
528            });
529            update_command_palette_filter(cx);
530        });
531
532        cx.update(|cx| {
533            let filter = CommandPaletteFilter::try_global(cx).unwrap();
534            assert!(
535                !filter.is_hidden(&AcceptEditPrediction),
536                "EditPrediction should be visible when provider is Copilot"
537            );
538        });
539
540        // Disable EditPredictionProvider (None)
541        cx.update(|cx| {
542            cx.update_global::<SettingsStore, _>(|store, cx| {
543                store.update_user_settings(cx, |s| {
544                    s.project
545                        .all_languages
546                        .features
547                        .get_or_insert(Default::default())
548                        .edit_prediction_provider = Some(EditPredictionProvider::None);
549                });
550            });
551            update_command_palette_filter(cx);
552        });
553
554        cx.update(|cx| {
555            let filter = CommandPaletteFilter::try_global(cx).unwrap();
556            assert!(
557                filter.is_hidden(&AcceptEditPrediction),
558                "EditPrediction should be hidden when provider is None"
559            );
560        });
561    }
562}