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::Sweep
410                | EditPredictionProvider::Mercury
411                | EditPredictionProvider::Experimental(_) => {
412                    filter.show_namespace("edit_prediction");
413                    filter.hide_namespace("copilot");
414                    filter.hide_namespace("supermaven");
415                    filter.show_action_types(edit_prediction_actions.iter());
416                }
417            }
418
419            filter.show_namespace("zed_predict_onboarding");
420            filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
421        }
422
423        if agent_v2_enabled {
424            filter.show_namespace("multi_workspace");
425        } else {
426            filter.hide_namespace("multi_workspace");
427        }
428    });
429}
430
431fn init_language_model_settings(cx: &mut App) {
432    update_active_language_model_from_settings(cx);
433
434    cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
435        .detach();
436    cx.subscribe(
437        &LanguageModelRegistry::global(cx),
438        |_, event: &language_model::Event, cx| match event {
439            language_model::Event::ProviderStateChanged(_)
440            | language_model::Event::AddedProvider(_)
441            | language_model::Event::RemovedProvider(_)
442            | language_model::Event::ProvidersChanged => {
443                update_active_language_model_from_settings(cx);
444            }
445            _ => {}
446        },
447    )
448    .detach();
449}
450
451fn update_active_language_model_from_settings(cx: &mut App) {
452    let settings = AgentSettings::get_global(cx);
453
454    fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
455        language_model::SelectedModel {
456            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
457            model: LanguageModelId::from(selection.model.clone()),
458        }
459    }
460
461    let default = settings.default_model.as_ref().map(to_selected_model);
462    let inline_assistant = settings
463        .inline_assistant_model
464        .as_ref()
465        .map(to_selected_model);
466    let commit_message = settings
467        .commit_message_model
468        .as_ref()
469        .map(to_selected_model);
470    let thread_summary = settings
471        .thread_summary_model
472        .as_ref()
473        .map(to_selected_model);
474    let inline_alternatives = settings
475        .inline_alternatives
476        .iter()
477        .map(to_selected_model)
478        .collect::<Vec<_>>();
479
480    LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
481        registry.select_default_model(default.as_ref(), cx);
482        registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
483        registry.select_commit_message_model(commit_message.as_ref(), cx);
484        registry.select_thread_summary_model(thread_summary.as_ref(), cx);
485        registry.select_inline_alternative_models(inline_alternatives, cx);
486    });
487}
488
489fn register_slash_commands(cx: &mut App) {
490    let slash_command_registry = SlashCommandRegistry::global(cx);
491
492    slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
493    slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
494    slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
495    slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
496    slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
497    slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
498    slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
499    slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
500    slash_command_registry
501        .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
502    slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
503
504    cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
505        move |is_enabled, _cx| {
506            if is_enabled {
507                slash_command_registry.register_command(
508                    assistant_slash_commands::StreamingExampleSlashCommand,
509                    false,
510                );
511            }
512        }
513    })
514    .detach();
515}
516
517#[cfg(test)]
518mod tests {
519    use super::*;
520    use agent_settings::{AgentProfileId, AgentSettings};
521    use command_palette_hooks::CommandPaletteFilter;
522    use editor::actions::AcceptEditPrediction;
523    use gpui::{BorrowAppContext, TestAppContext, px};
524    use project::DisableAiSettings;
525    use settings::{
526        DefaultAgentView, DockPosition, NotifyWhenAgentWaiting, Settings, SettingsStore,
527    };
528
529    #[gpui::test]
530    fn test_agent_command_palette_visibility(cx: &mut TestAppContext) {
531        // Init settings
532        cx.update(|cx| {
533            let store = SettingsStore::test(cx);
534            cx.set_global(store);
535            command_palette_hooks::init(cx);
536            AgentSettings::register(cx);
537            DisableAiSettings::register(cx);
538            AllLanguageSettings::register(cx);
539        });
540
541        let agent_settings = AgentSettings {
542            enabled: true,
543            button: true,
544            dock: DockPosition::Right,
545            default_width: px(300.),
546            default_height: px(600.),
547            default_model: None,
548            inline_assistant_model: None,
549            inline_assistant_use_streaming_tools: false,
550            commit_message_model: None,
551            thread_summary_model: None,
552            inline_alternatives: vec![],
553            favorite_models: vec![],
554            default_profile: AgentProfileId::default(),
555            default_view: DefaultAgentView::Thread,
556            profiles: Default::default(),
557
558            notify_when_agent_waiting: NotifyWhenAgentWaiting::default(),
559            play_sound_when_agent_done: false,
560            single_file_review: false,
561            model_parameters: vec![],
562            enable_feedback: false,
563            expand_edit_card: true,
564            expand_terminal_card: true,
565            cancel_generation_on_terminal_stop: true,
566            use_modifier_to_send: true,
567            message_editor_min_lines: 1,
568            tool_permissions: Default::default(),
569            show_turn_stats: false,
570        };
571
572        cx.update(|cx| {
573            AgentSettings::override_global(agent_settings.clone(), cx);
574            DisableAiSettings::override_global(DisableAiSettings { disable_ai: false }, cx);
575
576            // Initial update
577            update_command_palette_filter(cx);
578        });
579
580        // Assert visible
581        cx.update(|cx| {
582            let filter = CommandPaletteFilter::try_global(cx).unwrap();
583            assert!(
584                !filter.is_hidden(&NewThread),
585                "NewThread should be visible by default"
586            );
587            assert!(
588                !filter.is_hidden(&text_thread_editor::CopyCode),
589                "CopyCode should be visible when agent is enabled"
590            );
591        });
592
593        // Disable agent
594        cx.update(|cx| {
595            let mut new_settings = agent_settings.clone();
596            new_settings.enabled = false;
597            AgentSettings::override_global(new_settings, cx);
598
599            // Trigger update
600            update_command_palette_filter(cx);
601        });
602
603        // Assert hidden
604        cx.update(|cx| {
605            let filter = CommandPaletteFilter::try_global(cx).unwrap();
606            assert!(
607                filter.is_hidden(&NewThread),
608                "NewThread should be hidden when agent is disabled"
609            );
610            assert!(
611                filter.is_hidden(&text_thread_editor::CopyCode),
612                "CopyCode should be hidden when agent is disabled"
613            );
614        });
615
616        // Test EditPredictionProvider
617        // Enable EditPredictionProvider::Copilot
618        cx.update(|cx| {
619            cx.update_global::<SettingsStore, _>(|store, cx| {
620                store.update_user_settings(cx, |s| {
621                    s.project
622                        .all_languages
623                        .edit_predictions
624                        .get_or_insert(Default::default())
625                        .provider = Some(EditPredictionProvider::Copilot);
626                });
627            });
628            update_command_palette_filter(cx);
629        });
630
631        cx.update(|cx| {
632            let filter = CommandPaletteFilter::try_global(cx).unwrap();
633            assert!(
634                !filter.is_hidden(&AcceptEditPrediction),
635                "EditPrediction should be visible when provider is Copilot"
636            );
637        });
638
639        // Disable EditPredictionProvider (None)
640        cx.update(|cx| {
641            cx.update_global::<SettingsStore, _>(|store, cx| {
642                store.update_user_settings(cx, |s| {
643                    s.project
644                        .all_languages
645                        .edit_predictions
646                        .get_or_insert(Default::default())
647                        .provider = Some(EditPredictionProvider::None);
648                });
649            });
650            update_command_palette_filter(cx);
651        });
652
653        cx.update(|cx| {
654            let filter = CommandPaletteFilter::try_global(cx).unwrap();
655            assert!(
656                filter.is_hidden(&AcceptEditPrediction),
657                "EditPrediction should be hidden when provider is None"
658            );
659        });
660    }
661}