agent_ui.rs

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