agent_ui.rs

  1mod acp;
  2mod agent_configuration;
  3mod agent_diff;
  4mod agent_model_selector;
  5mod agent_panel;
  6mod buffer_codegen;
  7mod context_picker;
  8mod context_server_configuration;
  9mod context_strip;
 10mod inline_assistant;
 11mod inline_prompt_editor;
 12mod language_model_selector;
 13mod message_editor;
 14mod profile_selector;
 15mod slash_command;
 16mod slash_command_picker;
 17mod slash_command_settings;
 18mod terminal_codegen;
 19mod terminal_inline_assistant;
 20mod text_thread_editor;
 21mod ui;
 22
 23use std::rc::Rc;
 24use std::sync::Arc;
 25
 26use agent::ThreadId;
 27use agent_settings::{AgentProfileId, AgentSettings, LanguageModelSelection};
 28use assistant_slash_command::SlashCommandRegistry;
 29use client::Client;
 30use command_palette_hooks::CommandPaletteFilter;
 31use feature_flags::FeatureFlagAppExt as _;
 32use fs::Fs;
 33use gpui::{Action, App, Entity, SharedString, actions};
 34use language::LanguageRegistry;
 35use language_model::{
 36    ConfiguredModel, LanguageModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
 37};
 38use project::DisableAiSettings;
 39use project::agent_server_store::AgentServerCommand;
 40use prompt_store::PromptBuilder;
 41use schemars::JsonSchema;
 42use serde::{Deserialize, Serialize};
 43use settings::{Settings as _, SettingsStore};
 44use std::any::TypeId;
 45
 46use crate::agent_configuration::{ConfigureContextServerModal, ManageProfilesModal};
 47pub use crate::agent_panel::{AgentPanel, ConcreteAssistantPanelDelegate};
 48pub use crate::inline_assistant::InlineAssistant;
 49use crate::slash_command_settings::SlashCommandSettings;
 50pub use agent_diff::{AgentDiffPane, AgentDiffToolbar};
 51pub use text_thread_editor::{AgentPanelDelegate, TextThreadEditor};
 52use zed_actions;
 53
 54actions!(
 55    agent,
 56    [
 57        /// Creates a new text-based conversation thread.
 58        NewTextThread,
 59        /// Toggles the context picker interface for adding files, symbols, or other context.
 60        ToggleContextPicker,
 61        /// Toggles the menu to create new agent threads.
 62        ToggleNewThreadMenu,
 63        /// Toggles the navigation menu for switching between threads and views.
 64        ToggleNavigationMenu,
 65        /// Toggles the options menu for agent settings and preferences.
 66        ToggleOptionsMenu,
 67        /// Deletes the recently opened thread from history.
 68        DeleteRecentlyOpenThread,
 69        /// Toggles the profile or mode selector for switching between agent profiles.
 70        ToggleProfileSelector,
 71        /// Cycles through available session modes.
 72        CycleModeSelector,
 73        /// Removes all added context from the current conversation.
 74        RemoveAllContext,
 75        /// Expands the message editor to full size.
 76        ExpandMessageEditor,
 77        /// Opens the conversation history view.
 78        OpenHistory,
 79        /// Adds a context server to the configuration.
 80        AddContextServer,
 81        /// Removes the currently selected thread.
 82        RemoveSelectedThread,
 83        /// Starts a chat conversation with follow-up enabled.
 84        ChatWithFollow,
 85        /// Cycles to the next inline assist suggestion.
 86        CycleNextInlineAssist,
 87        /// Cycles to the previous inline assist suggestion.
 88        CyclePreviousInlineAssist,
 89        /// Moves focus up in the interface.
 90        FocusUp,
 91        /// Moves focus down in the interface.
 92        FocusDown,
 93        /// Moves focus left in the interface.
 94        FocusLeft,
 95        /// Moves focus right in the interface.
 96        FocusRight,
 97        /// Removes the currently focused context item.
 98        RemoveFocusedContext,
 99        /// Accepts the suggested context item.
100        AcceptSuggestedContext,
101        /// Opens the active thread as a markdown file.
102        OpenActiveThreadAsMarkdown,
103        /// Opens the agent diff view to review changes.
104        OpenAgentDiff,
105        /// Keeps the current suggestion or change.
106        Keep,
107        /// Rejects the current suggestion or change.
108        Reject,
109        /// Rejects all suggestions or changes.
110        RejectAll,
111        /// Keeps all suggestions or changes.
112        KeepAll,
113        /// Allow this operation only this time.
114        AllowOnce,
115        /// Allow this operation and remember the choice.
116        AllowAlways,
117        /// Reject this operation only this time.
118        RejectOnce,
119        /// Follows the agent's suggestions.
120        Follow,
121        /// Resets the trial upsell notification.
122        ResetTrialUpsell,
123        /// Resets the trial end upsell notification.
124        ResetTrialEndUpsell,
125        /// Continues the current thread.
126        ContinueThread,
127        /// Continues the thread with burn mode enabled.
128        ContinueWithBurnMode,
129        /// Toggles burn mode for faster responses.
130        ToggleBurnMode,
131    ]
132);
133
134#[derive(Clone, Copy, Debug, PartialEq, Eq, Action)]
135#[action(namespace = agent)]
136#[action(deprecated_aliases = ["assistant::QuoteSelection"])]
137/// Quotes the current selection in the agent panel's message editor.
138pub struct QuoteSelection;
139
140/// Creates a new conversation thread, optionally based on an existing thread.
141#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
142#[action(namespace = agent)]
143#[serde(deny_unknown_fields)]
144pub struct NewThread {
145    #[serde(default)]
146    from_thread_id: Option<ThreadId>,
147}
148
149/// Creates a new external agent conversation thread.
150#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
151#[action(namespace = agent)]
152#[serde(deny_unknown_fields)]
153pub struct NewExternalAgentThread {
154    /// Which agent to use for the conversation.
155    agent: Option<ExternalAgent>,
156}
157
158#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
159#[action(namespace = agent)]
160#[serde(deny_unknown_fields)]
161pub struct NewNativeAgentThreadFromSummary {
162    from_session_id: agent_client_protocol::SessionId,
163}
164
165// TODO unify this with AgentType
166#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
167#[serde(rename_all = "snake_case")]
168enum ExternalAgent {
169    #[default]
170    Gemini,
171    ClaudeCode,
172    NativeAgent,
173    Custom {
174        name: SharedString,
175        command: AgentServerCommand,
176    },
177}
178
179fn placeholder_command() -> AgentServerCommand {
180    AgentServerCommand {
181        path: "/placeholder".into(),
182        args: vec![],
183        env: None,
184    }
185}
186
187impl ExternalAgent {
188    fn name(&self) -> &'static str {
189        match self {
190            Self::NativeAgent => "zed",
191            Self::Gemini => "gemini-cli",
192            Self::ClaudeCode => "claude-code",
193            Self::Custom { .. } => "custom",
194        }
195    }
196
197    pub fn server(
198        &self,
199        fs: Arc<dyn fs::Fs>,
200        history: Entity<agent2::HistoryStore>,
201    ) -> Rc<dyn agent_servers::AgentServer> {
202        match self {
203            Self::Gemini => Rc::new(agent_servers::Gemini),
204            Self::ClaudeCode => Rc::new(agent_servers::ClaudeCode),
205            Self::NativeAgent => Rc::new(agent2::NativeAgentServer::new(fs, history)),
206            Self::Custom { name, command: _ } => {
207                Rc::new(agent_servers::CustomAgentServer::new(name.clone()))
208            }
209        }
210    }
211}
212
213/// Opens the profile management interface for configuring agent tools and settings.
214#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
215#[action(namespace = agent)]
216#[serde(deny_unknown_fields)]
217pub struct ManageProfiles {
218    #[serde(default)]
219    pub customize_tools: Option<AgentProfileId>,
220}
221
222impl ManageProfiles {
223    pub fn customize_tools(profile_id: AgentProfileId) -> Self {
224        Self {
225            customize_tools: Some(profile_id),
226        }
227    }
228}
229
230#[derive(Clone)]
231pub(crate) enum ModelUsageContext {
232    InlineAssistant,
233}
234
235impl ModelUsageContext {
236    pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
237        match self {
238            Self::InlineAssistant => {
239                LanguageModelRegistry::read_global(cx).inline_assistant_model()
240            }
241        }
242    }
243
244    pub fn language_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
245        self.configured_model(cx)
246            .map(|configured_model| configured_model.model)
247    }
248}
249
250/// Initializes the `agent` crate.
251pub fn init(
252    fs: Arc<dyn Fs>,
253    client: Arc<Client>,
254    prompt_builder: Arc<PromptBuilder>,
255    language_registry: Arc<LanguageRegistry>,
256    is_eval: bool,
257    cx: &mut App,
258) {
259    AgentSettings::register(cx);
260    SlashCommandSettings::register(cx);
261
262    assistant_context::init(client.clone(), cx);
263    rules_library::init(cx);
264    if !is_eval {
265        // Initializing the language model from the user settings messes with the eval, so we only initialize them when
266        // we're not running inside of the eval.
267        init_language_model_settings(cx);
268    }
269    assistant_slash_command::init(cx);
270    agent::init(cx);
271    agent_panel::init(cx);
272    context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
273    TextThreadEditor::init(cx);
274
275    register_slash_commands(cx);
276    inline_assistant::init(
277        fs.clone(),
278        prompt_builder.clone(),
279        client.telemetry().clone(),
280        cx,
281    );
282    terminal_inline_assistant::init(fs.clone(), prompt_builder, client.telemetry().clone(), cx);
283    cx.observe_new(move |workspace, window, cx| {
284        ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
285    })
286    .detach();
287    cx.observe_new(ManageProfilesModal::register).detach();
288
289    // Update command palette filter based on AI settings
290    update_command_palette_filter(cx);
291
292    // Watch for settings changes
293    cx.observe_global::<SettingsStore>(|app_cx| {
294        // When settings change, update the command palette filter
295        update_command_palette_filter(app_cx);
296    })
297    .detach();
298}
299
300fn update_command_palette_filter(cx: &mut App) {
301    let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
302    CommandPaletteFilter::update_global(cx, |filter, _| {
303        if disable_ai {
304            filter.hide_namespace("agent");
305            filter.hide_namespace("assistant");
306            filter.hide_namespace("copilot");
307            filter.hide_namespace("supermaven");
308            filter.hide_namespace("zed_predict_onboarding");
309            filter.hide_namespace("edit_prediction");
310
311            use editor::actions::{
312                AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
313                PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
314            };
315            let edit_prediction_actions = [
316                TypeId::of::<AcceptEditPrediction>(),
317                TypeId::of::<AcceptPartialEditPrediction>(),
318                TypeId::of::<ShowEditPrediction>(),
319                TypeId::of::<NextEditPrediction>(),
320                TypeId::of::<PreviousEditPrediction>(),
321                TypeId::of::<ToggleEditPrediction>(),
322            ];
323            filter.hide_action_types(&edit_prediction_actions);
324            filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
325        } else {
326            filter.show_namespace("agent");
327            filter.show_namespace("assistant");
328            filter.show_namespace("copilot");
329            filter.show_namespace("zed_predict_onboarding");
330
331            filter.show_namespace("edit_prediction");
332
333            use editor::actions::{
334                AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
335                PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
336            };
337            let edit_prediction_actions = [
338                TypeId::of::<AcceptEditPrediction>(),
339                TypeId::of::<AcceptPartialEditPrediction>(),
340                TypeId::of::<ShowEditPrediction>(),
341                TypeId::of::<NextEditPrediction>(),
342                TypeId::of::<PreviousEditPrediction>(),
343                TypeId::of::<ToggleEditPrediction>(),
344            ];
345            filter.show_action_types(edit_prediction_actions.iter());
346
347            filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
348        }
349    });
350}
351
352fn init_language_model_settings(cx: &mut App) {
353    update_active_language_model_from_settings(cx);
354
355    cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
356        .detach();
357    cx.subscribe(
358        &LanguageModelRegistry::global(cx),
359        |_, event: &language_model::Event, cx| match event {
360            language_model::Event::ProviderStateChanged(_)
361            | language_model::Event::AddedProvider(_)
362            | language_model::Event::RemovedProvider(_) => {
363                update_active_language_model_from_settings(cx);
364            }
365            _ => {}
366        },
367    )
368    .detach();
369}
370
371fn update_active_language_model_from_settings(cx: &mut App) {
372    let settings = AgentSettings::get_global(cx);
373
374    fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
375        language_model::SelectedModel {
376            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
377            model: LanguageModelId::from(selection.model.clone()),
378        }
379    }
380
381    let default = settings.default_model.as_ref().map(to_selected_model);
382    let inline_assistant = settings
383        .inline_assistant_model
384        .as_ref()
385        .map(to_selected_model);
386    let commit_message = settings
387        .commit_message_model
388        .as_ref()
389        .map(to_selected_model);
390    let thread_summary = settings
391        .thread_summary_model
392        .as_ref()
393        .map(to_selected_model);
394    let inline_alternatives = settings
395        .inline_alternatives
396        .iter()
397        .map(to_selected_model)
398        .collect::<Vec<_>>();
399
400    LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
401        registry.select_default_model(default.as_ref(), cx);
402        registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
403        registry.select_commit_message_model(commit_message.as_ref(), cx);
404        registry.select_thread_summary_model(thread_summary.as_ref(), cx);
405        registry.select_inline_alternative_models(inline_alternatives, cx);
406    });
407}
408
409fn register_slash_commands(cx: &mut App) {
410    let slash_command_registry = SlashCommandRegistry::global(cx);
411
412    slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
413    slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
414    slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
415    slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
416    slash_command_registry
417        .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
418    slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
419    slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
420    slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
421    slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
422    slash_command_registry
423        .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
424    slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
425
426    cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
427        move |is_enabled, _cx| {
428            if is_enabled {
429                slash_command_registry.register_command(
430                    assistant_slash_commands::StreamingExampleSlashCommand,
431                    false,
432                );
433            }
434        }
435    })
436    .detach();
437
438    update_slash_commands_from_settings(cx);
439    cx.observe_global::<SettingsStore>(update_slash_commands_from_settings)
440        .detach();
441}
442
443fn update_slash_commands_from_settings(cx: &mut App) {
444    let slash_command_registry = SlashCommandRegistry::global(cx);
445    let settings = SlashCommandSettings::get_global(cx);
446
447    if settings.cargo_workspace.enabled {
448        slash_command_registry
449            .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
450    } else {
451        slash_command_registry
452            .unregister_command(assistant_slash_commands::CargoWorkspaceSlashCommand);
453    }
454}