agent_ui.rs

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