agent_ui.rs

  1pub mod acp;
  2mod agent_configuration;
  3mod agent_diff;
  4mod agent_model_selector;
  5mod agent_panel;
  6mod agent_registry_ui;
  7mod buffer_codegen;
  8mod completion_provider;
  9mod context;
 10mod context_server_configuration;
 11mod favorite_models;
 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 text_thread_history;
 23mod ui;
 24
 25use std::rc::Rc;
 26use std::sync::Arc;
 27
 28// Another comment
 29use agent_settings::{AgentProfileId, AgentSettings};
 30use assistant_slash_command::SlashCommandRegistry;
 31use client::Client;
 32use command_palette_hooks::CommandPaletteFilter;
 33use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt as _};
 34use fs::Fs;
 35use gpui::{Action, App, Context, Entity, SharedString, Window, actions};
 36use language::{
 37    LanguageRegistry,
 38    language_settings::{AllLanguageSettings, EditPredictionProvider},
 39};
 40use language_model::{
 41    ConfiguredModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
 42};
 43use project::DisableAiSettings;
 44use prompt_store::PromptBuilder;
 45use schemars::JsonSchema;
 46use serde::{Deserialize, Serialize};
 47use settings::{LanguageModelSelection, Settings as _, SettingsStore};
 48use std::any::TypeId;
 49use workspace::Workspace;
 50
 51use crate::agent_configuration::{ConfigureContextServerModal, ManageProfilesModal};
 52pub use crate::agent_panel::{AgentPanel, AgentPanelEvent, ConcreteAssistantPanelDelegate};
 53use crate::agent_registry_ui::AgentRegistryPage;
 54pub use crate::inline_assistant::InlineAssistant;
 55pub use agent_diff::{AgentDiffPane, AgentDiffToolbar};
 56pub use text_thread_editor::{AgentPanelDelegate, TextThreadEditor};
 57use zed_actions;
 58
 59actions!(
 60    agent,
 61    [
 62        /// Creates a new text-based conversation thread.
 63        NewTextThread,
 64        /// Toggles the menu to create new agent threads.
 65        ToggleNewThreadMenu,
 66        /// Toggles the navigation menu for switching between threads and views.
 67        ToggleNavigationMenu,
 68        /// Toggles the options menu for agent settings and preferences.
 69        ToggleOptionsMenu,
 70        /// Toggles the profile or mode selector for switching between agent profiles.
 71        ToggleProfileSelector,
 72        /// Cycles through available session modes.
 73        CycleModeSelector,
 74        /// Cycles through favorited models in the ACP model selector.
 75        CycleFavoriteModels,
 76        /// Expands the message editor to full size.
 77        ExpandMessageEditor,
 78        /// Removes all thread history.
 79        RemoveHistory,
 80        /// Opens the conversation history view.
 81        OpenHistory,
 82        /// Adds a context server to the configuration.
 83        AddContextServer,
 84        /// Removes the currently selected thread.
 85        RemoveSelectedThread,
 86        /// Starts a chat conversation with follow-up enabled.
 87        ChatWithFollow,
 88        /// Cycles to the next inline assist suggestion.
 89        CycleNextInlineAssist,
 90        /// Cycles to the previous inline assist suggestion.
 91        CyclePreviousInlineAssist,
 92        /// Moves focus up in the interface.
 93        FocusUp,
 94        /// Moves focus down in the interface.
 95        FocusDown,
 96        /// Moves focus left in the interface.
 97        FocusLeft,
 98        /// Moves focus right in the interface.
 99        FocusRight,
100        /// Opens the active thread as a markdown file.
101        OpenActiveThreadAsMarkdown,
102        /// Opens the agent diff view to review changes.
103        OpenAgentDiff,
104        /// Copies the current thread to the clipboard as JSON for debugging.
105        CopyThreadToClipboard,
106        /// Loads a thread from the clipboard JSON for debugging.
107        LoadThreadFromClipboard,
108        /// Keeps the current suggestion or change.
109        Keep,
110        /// Rejects the current suggestion or change.
111        Reject,
112        /// Rejects all suggestions or changes.
113        RejectAll,
114        /// Keeps all suggestions or changes.
115        KeepAll,
116        /// Allow this operation only this time.
117        AllowOnce,
118        /// Allow this operation and remember the choice.
119        AllowAlways,
120        /// Reject this operation only this time.
121        RejectOnce,
122        /// Follows the agent's suggestions.
123        Follow,
124        /// Resets the trial upsell notification.
125        ResetTrialUpsell,
126        /// Resets the trial end upsell notification.
127        ResetTrialEndUpsell,
128        /// Opens the "Add Context" menu in the message editor.
129        OpenAddContextMenu,
130        /// Continues the current thread.
131        ContinueThread,
132        /// Interrupts the current generation and sends the message immediately.
133        SendImmediately,
134        /// Sends the next queued message immediately.
135        SendNextQueuedMessage,
136        /// Removes the first message from the queue (the next one to be sent).
137        RemoveFirstQueuedMessage,
138        /// Edits the first message in the queue (the next one to be sent).
139        EditFirstQueuedMessage,
140        /// Clears all messages from the queue.
141        ClearMessageQueue,
142        /// Opens the permission granularity dropdown for the current tool call.
143        OpenPermissionDropdown,
144        /// Toggles thinking mode for models that support extended thinking.
145        ToggleThinkingMode,
146        /// Cycles through available thinking effort levels for the current model.
147        CycleThinkingEffort,
148        /// Toggles the thinking effort selector menu open or closed.
149        ToggleThinkingEffortMenu,
150    ]
151);
152
153/// Action to authorize a tool call with a specific permission option.
154/// This is used by the permission granularity dropdown to authorize tool calls.
155#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
156#[action(namespace = agent)]
157#[serde(deny_unknown_fields)]
158pub struct AuthorizeToolCall {
159    /// The tool call ID to authorize.
160    pub tool_call_id: String,
161    /// The permission option ID to use.
162    pub option_id: String,
163    /// The kind of permission option (serialized as string).
164    pub option_kind: String,
165}
166
167/// Action to select a permission granularity option from the dropdown.
168/// This updates the selected granularity without triggering authorization.
169#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
170#[action(namespace = agent)]
171#[serde(deny_unknown_fields)]
172pub struct SelectPermissionGranularity {
173    /// The tool call ID for which to select the granularity.
174    pub tool_call_id: String,
175    /// The index of the selected granularity option.
176    pub index: usize,
177}
178
179/// Creates a new conversation thread, optionally based on an existing thread.
180#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
181#[action(namespace = agent)]
182#[serde(deny_unknown_fields)]
183pub struct NewThread;
184
185/// Creates a new external agent conversation thread.
186#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
187#[action(namespace = agent)]
188#[serde(deny_unknown_fields)]
189pub struct NewExternalAgentThread {
190    /// Which agent to use for the conversation.
191    agent: Option<ExternalAgent>,
192}
193
194#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
195#[action(namespace = agent)]
196#[serde(deny_unknown_fields)]
197pub struct NewNativeAgentThreadFromSummary {
198    from_session_id: agent_client_protocol::SessionId,
199}
200
201// TODO unify this with AgentType
202#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
203#[serde(rename_all = "snake_case")]
204pub enum ExternalAgent {
205    Gemini,
206    ClaudeCode,
207    Codex,
208    NativeAgent,
209    Custom { name: SharedString },
210}
211
212impl ExternalAgent {
213    pub fn server(
214        &self,
215        fs: Arc<dyn fs::Fs>,
216        thread_store: Entity<agent::ThreadStore>,
217    ) -> Rc<dyn agent_servers::AgentServer> {
218        match self {
219            Self::Gemini => Rc::new(agent_servers::Gemini),
220            Self::ClaudeCode => Rc::new(agent_servers::ClaudeCode),
221            Self::Codex => Rc::new(agent_servers::Codex),
222            Self::NativeAgent => Rc::new(agent::NativeAgentServer::new(fs, thread_store)),
223            Self::Custom { name } => Rc::new(agent_servers::CustomAgentServer::new(name.clone())),
224        }
225    }
226}
227
228/// Content to initialize new external agent with.
229pub enum ExternalAgentInitialContent {
230    ThreadSummary(acp_thread::AgentSessionInfo),
231    Text(String),
232}
233
234/// Opens the profile management interface for configuring agent tools and settings.
235#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
236#[action(namespace = agent)]
237#[serde(deny_unknown_fields)]
238pub struct ManageProfiles {
239    #[serde(default)]
240    pub customize_tools: Option<AgentProfileId>,
241}
242
243impl ManageProfiles {
244    pub fn customize_tools(profile_id: AgentProfileId) -> Self {
245        Self {
246            customize_tools: Some(profile_id),
247        }
248    }
249}
250
251#[derive(Clone)]
252pub(crate) enum ModelUsageContext {
253    InlineAssistant,
254}
255
256impl ModelUsageContext {
257    pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
258        match self {
259            Self::InlineAssistant => {
260                LanguageModelRegistry::read_global(cx).inline_assistant_model()
261            }
262        }
263    }
264}
265
266/// Initializes the `agent` crate.
267pub fn init(
268    fs: Arc<dyn Fs>,
269    client: Arc<Client>,
270    prompt_builder: Arc<PromptBuilder>,
271    language_registry: Arc<LanguageRegistry>,
272    is_eval: bool,
273    cx: &mut App,
274) {
275    agent::ThreadStore::init_global(cx);
276    assistant_text_thread::init(client, cx);
277    rules_library::init(cx);
278    if !is_eval {
279        // Initializing the language model from the user settings messes with the eval, so we only initialize them when
280        // we're not running inside of the eval.
281        init_language_model_settings(cx);
282    }
283    assistant_slash_command::init(cx);
284    agent_panel::init(cx);
285    context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
286    TextThreadEditor::init(cx);
287
288    register_slash_commands(cx);
289    inline_assistant::init(fs.clone(), prompt_builder.clone(), cx);
290    terminal_inline_assistant::init(fs.clone(), prompt_builder, cx);
291    cx.observe_new(move |workspace, window, cx| {
292        ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
293    })
294    .detach();
295    cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
296        workspace.register_action(
297            move |workspace: &mut Workspace,
298                  _: &zed_actions::AcpRegistry,
299                  window: &mut Window,
300                  cx: &mut Context<Workspace>| {
301                let existing = workspace
302                    .active_pane()
303                    .read(cx)
304                    .items()
305                    .find_map(|item| item.downcast::<AgentRegistryPage>());
306
307                if let Some(existing) = existing {
308                    workspace.activate_item(&existing, true, true, window, cx);
309                } else {
310                    let registry_page = AgentRegistryPage::new(workspace, window, cx);
311                    workspace.add_item_to_active_pane(
312                        Box::new(registry_page),
313                        None,
314                        true,
315                        window,
316                        cx,
317                    );
318                }
319            },
320        );
321    })
322    .detach();
323    cx.observe_new(ManageProfilesModal::register).detach();
324
325    // Update command palette filter based on AI settings
326    update_command_palette_filter(cx);
327
328    // Watch for settings changes
329    cx.observe_global::<SettingsStore>(|app_cx| {
330        // When settings change, update the command palette filter
331        update_command_palette_filter(app_cx);
332    })
333    .detach();
334
335    cx.on_flags_ready(|_, cx| {
336        update_command_palette_filter(cx);
337    })
338    .detach();
339}
340
341fn update_command_palette_filter(cx: &mut App) {
342    let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
343    let agent_enabled = AgentSettings::get_global(cx).enabled;
344    let agent_v2_enabled = cx.has_flag::<AgentV2FeatureFlag>();
345    let edit_prediction_provider = AllLanguageSettings::get_global(cx)
346        .edit_predictions
347        .provider;
348
349    CommandPaletteFilter::update_global(cx, |filter, _| {
350        use editor::actions::{
351            AcceptEditPrediction, AcceptNextLineEditPrediction, AcceptNextWordEditPrediction,
352            NextEditPrediction, PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
353        };
354        let edit_prediction_actions = [
355            TypeId::of::<AcceptEditPrediction>(),
356            TypeId::of::<AcceptNextWordEditPrediction>(),
357            TypeId::of::<AcceptNextLineEditPrediction>(),
358            TypeId::of::<AcceptEditPrediction>(),
359            TypeId::of::<ShowEditPrediction>(),
360            TypeId::of::<NextEditPrediction>(),
361            TypeId::of::<PreviousEditPrediction>(),
362            TypeId::of::<ToggleEditPrediction>(),
363        ];
364
365        if disable_ai {
366            filter.hide_namespace("agent");
367            filter.hide_namespace("agents");
368            filter.hide_namespace("assistant");
369            filter.hide_namespace("copilot");
370            filter.hide_namespace("supermaven");
371            filter.hide_namespace("zed_predict_onboarding");
372            filter.hide_namespace("edit_prediction");
373
374            filter.hide_action_types(&edit_prediction_actions);
375            filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
376        } else {
377            if agent_enabled {
378                filter.show_namespace("agent");
379                filter.show_namespace("agents");
380                filter.show_namespace("assistant");
381            } else {
382                filter.hide_namespace("agent");
383                filter.hide_namespace("agents");
384                filter.hide_namespace("assistant");
385            }
386
387            match edit_prediction_provider {
388                EditPredictionProvider::None => {
389                    filter.hide_namespace("edit_prediction");
390                    filter.hide_namespace("copilot");
391                    filter.hide_namespace("supermaven");
392                    filter.hide_action_types(&edit_prediction_actions);
393                }
394                EditPredictionProvider::Copilot => {
395                    filter.show_namespace("edit_prediction");
396                    filter.show_namespace("copilot");
397                    filter.hide_namespace("supermaven");
398                    filter.show_action_types(edit_prediction_actions.iter());
399                }
400                EditPredictionProvider::Supermaven => {
401                    filter.show_namespace("edit_prediction");
402                    filter.hide_namespace("copilot");
403                    filter.show_namespace("supermaven");
404                    filter.show_action_types(edit_prediction_actions.iter());
405                }
406                EditPredictionProvider::Zed
407                | EditPredictionProvider::Codestral
408                | EditPredictionProvider::Ollama
409                | EditPredictionProvider::OpenAiCompatibleApi
410                | EditPredictionProvider::Sweep
411                | EditPredictionProvider::Mercury
412                | EditPredictionProvider::Experimental(_) => {
413                    filter.show_namespace("edit_prediction");
414                    filter.hide_namespace("copilot");
415                    filter.hide_namespace("supermaven");
416                    filter.show_action_types(edit_prediction_actions.iter());
417                }
418            }
419
420            filter.show_namespace("zed_predict_onboarding");
421            filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
422        }
423
424        if agent_v2_enabled {
425            filter.show_namespace("multi_workspace");
426        } else {
427            filter.hide_namespace("multi_workspace");
428        }
429    });
430}
431
432fn init_language_model_settings(cx: &mut App) {
433    update_active_language_model_from_settings(cx);
434
435    cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
436        .detach();
437    cx.subscribe(
438        &LanguageModelRegistry::global(cx),
439        |_, event: &language_model::Event, cx| match event {
440            language_model::Event::ProviderStateChanged(_)
441            | language_model::Event::AddedProvider(_)
442            | language_model::Event::RemovedProvider(_)
443            | language_model::Event::ProvidersChanged => {
444                update_active_language_model_from_settings(cx);
445            }
446            _ => {}
447        },
448    )
449    .detach();
450}
451
452fn update_active_language_model_from_settings(cx: &mut App) {
453    let settings = AgentSettings::get_global(cx);
454
455    fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
456        language_model::SelectedModel {
457            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
458            model: LanguageModelId::from(selection.model.clone()),
459        }
460    }
461
462    let default = settings.default_model.as_ref().map(to_selected_model);
463    let inline_assistant = settings
464        .inline_assistant_model
465        .as_ref()
466        .map(to_selected_model);
467    let commit_message = settings
468        .commit_message_model
469        .as_ref()
470        .map(to_selected_model);
471    let thread_summary = settings
472        .thread_summary_model
473        .as_ref()
474        .map(to_selected_model);
475    let inline_alternatives = settings
476        .inline_alternatives
477        .iter()
478        .map(to_selected_model)
479        .collect::<Vec<_>>();
480
481    LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
482        registry.select_default_model(default.as_ref(), cx);
483        registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
484        registry.select_commit_message_model(commit_message.as_ref(), cx);
485        registry.select_thread_summary_model(thread_summary.as_ref(), cx);
486        registry.select_inline_alternative_models(inline_alternatives, cx);
487    });
488}
489
490fn register_slash_commands(cx: &mut App) {
491    let slash_command_registry = SlashCommandRegistry::global(cx);
492
493    slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
494    slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
495    slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
496    slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
497    slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
498    slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
499    slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
500    slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
501    slash_command_registry
502        .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
503    slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
504
505    cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
506        move |is_enabled, _cx| {
507            if is_enabled {
508                slash_command_registry.register_command(
509                    assistant_slash_commands::StreamingExampleSlashCommand,
510                    false,
511                );
512            }
513        }
514    })
515    .detach();
516}
517
518#[cfg(test)]
519mod tests {
520    use super::*;
521    use agent_settings::{AgentProfileId, AgentSettings};
522    use command_palette_hooks::CommandPaletteFilter;
523    use editor::actions::AcceptEditPrediction;
524    use gpui::{BorrowAppContext, TestAppContext, px};
525    use project::DisableAiSettings;
526    use settings::{
527        DefaultAgentView, DockPosition, NotifyWhenAgentWaiting, Settings, SettingsStore,
528    };
529
530    #[gpui::test]
531    fn test_agent_command_palette_visibility(cx: &mut TestAppContext) {
532        // Init settings
533        cx.update(|cx| {
534            let store = SettingsStore::test(cx);
535            cx.set_global(store);
536            command_palette_hooks::init(cx);
537            AgentSettings::register(cx);
538            DisableAiSettings::register(cx);
539            AllLanguageSettings::register(cx);
540        });
541
542        let agent_settings = AgentSettings {
543            enabled: true,
544            button: true,
545            dock: DockPosition::Right,
546            default_width: px(300.),
547            default_height: px(600.),
548            default_model: None,
549            inline_assistant_model: None,
550            inline_assistant_use_streaming_tools: false,
551            commit_message_model: None,
552            thread_summary_model: None,
553            inline_alternatives: vec![],
554            favorite_models: vec![],
555            default_profile: AgentProfileId::default(),
556            default_view: DefaultAgentView::Thread,
557            profiles: Default::default(),
558
559            notify_when_agent_waiting: NotifyWhenAgentWaiting::default(),
560            play_sound_when_agent_done: false,
561            single_file_review: false,
562            model_parameters: vec![],
563            enable_feedback: false,
564            expand_edit_card: true,
565            expand_terminal_card: true,
566            cancel_generation_on_terminal_stop: true,
567            use_modifier_to_send: true,
568            message_editor_min_lines: 1,
569            tool_permissions: Default::default(),
570            show_turn_stats: false,
571        };
572
573        cx.update(|cx| {
574            AgentSettings::override_global(agent_settings.clone(), cx);
575            DisableAiSettings::override_global(DisableAiSettings { disable_ai: false }, cx);
576
577            // Initial update
578            update_command_palette_filter(cx);
579        });
580
581        // Assert visible
582        cx.update(|cx| {
583            let filter = CommandPaletteFilter::try_global(cx).unwrap();
584            assert!(
585                !filter.is_hidden(&NewThread),
586                "NewThread should be visible by default"
587            );
588            assert!(
589                !filter.is_hidden(&text_thread_editor::CopyCode),
590                "CopyCode should be visible when agent is enabled"
591            );
592        });
593
594        // Disable agent
595        cx.update(|cx| {
596            let mut new_settings = agent_settings.clone();
597            new_settings.enabled = false;
598            AgentSettings::override_global(new_settings, cx);
599
600            // Trigger update
601            update_command_palette_filter(cx);
602        });
603
604        // Assert hidden
605        cx.update(|cx| {
606            let filter = CommandPaletteFilter::try_global(cx).unwrap();
607            assert!(
608                filter.is_hidden(&NewThread),
609                "NewThread should be hidden when agent is disabled"
610            );
611            assert!(
612                filter.is_hidden(&text_thread_editor::CopyCode),
613                "CopyCode should be hidden when agent is disabled"
614            );
615        });
616
617        // Test EditPredictionProvider
618        // Enable EditPredictionProvider::Copilot
619        cx.update(|cx| {
620            cx.update_global::<SettingsStore, _>(|store, cx| {
621                store.update_user_settings(cx, |s| {
622                    s.project
623                        .all_languages
624                        .edit_predictions
625                        .get_or_insert(Default::default())
626                        .provider = Some(EditPredictionProvider::Copilot);
627                });
628            });
629            update_command_palette_filter(cx);
630        });
631
632        cx.update(|cx| {
633            let filter = CommandPaletteFilter::try_global(cx).unwrap();
634            assert!(
635                !filter.is_hidden(&AcceptEditPrediction),
636                "EditPrediction should be visible when provider is Copilot"
637            );
638        });
639
640        // Disable EditPredictionProvider (None)
641        cx.update(|cx| {
642            cx.update_global::<SettingsStore, _>(|store, cx| {
643                store.update_user_settings(cx, |s| {
644                    s.project
645                        .all_languages
646                        .edit_predictions
647                        .get_or_insert(Default::default())
648                        .provider = Some(EditPredictionProvider::None);
649                });
650            });
651            update_command_palette_filter(cx);
652        });
653
654        cx.update(|cx| {
655            let filter = CommandPaletteFilter::try_global(cx).unwrap();
656            assert!(
657                filter.is_hidden(&AcceptEditPrediction),
658                "EditPrediction should be hidden when provider is None"
659            );
660        });
661    }
662}