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