agent_ui.rs

  1mod acp;
  2mod active_thread;
  3mod agent_configuration;
  4mod agent_diff;
  5mod agent_model_selector;
  6mod agent_panel;
  7mod buffer_codegen;
  8mod context_picker;
  9mod context_server_configuration;
 10mod context_strip;
 11mod debug;
 12mod inline_assistant;
 13mod inline_prompt_editor;
 14mod language_model_selector;
 15mod message_editor;
 16mod profile_selector;
 17mod slash_command;
 18mod slash_command_picker;
 19mod slash_command_settings;
 20mod terminal_codegen;
 21mod terminal_inline_assistant;
 22mod text_thread_editor;
 23mod thread_history;
 24mod tool_compatibility;
 25mod ui;
 26
 27use std::rc::Rc;
 28use std::sync::Arc;
 29
 30use agent::{Thread, ThreadId};
 31use agent_settings::{AgentProfileId, AgentSettings, LanguageModelSelection};
 32use assistant_slash_command::SlashCommandRegistry;
 33use client::Client;
 34use command_palette_hooks::CommandPaletteFilter;
 35use feature_flags::FeatureFlagAppExt as _;
 36use fs::Fs;
 37use gpui::{Action, App, Entity, SharedString, actions};
 38use language::LanguageRegistry;
 39use language_model::{
 40    ConfiguredModel, LanguageModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
 41};
 42use project::DisableAiSettings;
 43use project::agent_server_store::AgentServerCommand;
 44use prompt_store::PromptBuilder;
 45use schemars::JsonSchema;
 46use serde::{Deserialize, Serialize};
 47use settings::{Settings as _, SettingsStore};
 48use std::any::TypeId;
 49
 50pub use crate::active_thread::ActiveThread;
 51use crate::agent_configuration::{ConfigureContextServerModal, ManageProfilesModal};
 52pub use crate::agent_panel::{AgentPanel, ConcreteAssistantPanelDelegate};
 53pub use crate::inline_assistant::InlineAssistant;
 54use crate::slash_command_settings::SlashCommandSettings;
 55pub use agent_diff::{AgentDiffPane, AgentDiffToolbar};
 56pub use text_thread_editor::{AgentPanelDelegate, TextThreadEditor};
 57pub use ui::preview::{all_agent_previews, get_agent_preview};
 58use zed_actions;
 59
 60actions!(
 61    agent,
 62    [
 63        /// Creates a new text-based conversation thread.
 64        NewTextThread,
 65        /// Toggles the context picker interface for adding files, symbols, or other context.
 66        ToggleContextPicker,
 67        /// Toggles the menu to create new agent threads.
 68        ToggleNewThreadMenu,
 69        /// Toggles the navigation menu for switching between threads and views.
 70        ToggleNavigationMenu,
 71        /// Toggles the options menu for agent settings and preferences.
 72        ToggleOptionsMenu,
 73        /// Deletes the recently opened thread from history.
 74        DeleteRecentlyOpenThread,
 75        /// Toggles the profile or mode selector for switching between agent profiles.
 76        ToggleProfileSelector,
 77        /// Cycles through available session modes.
 78        CycleModeSelector,
 79        /// Removes all added context from the current conversation.
 80        RemoveAllContext,
 81        /// Expands the message editor to full size.
 82        ExpandMessageEditor,
 83        /// Opens the conversation history view.
 84        OpenHistory,
 85        /// Adds a context server to the configuration.
 86        AddContextServer,
 87        /// Removes the currently selected thread.
 88        RemoveSelectedThread,
 89        /// Starts a chat conversation with follow-up enabled.
 90        ChatWithFollow,
 91        /// Cycles to the next inline assist suggestion.
 92        CycleNextInlineAssist,
 93        /// Cycles to the previous inline assist suggestion.
 94        CyclePreviousInlineAssist,
 95        /// Moves focus up in the interface.
 96        FocusUp,
 97        /// Moves focus down in the interface.
 98        FocusDown,
 99        /// Moves focus left in the interface.
100        FocusLeft,
101        /// Moves focus right in the interface.
102        FocusRight,
103        /// Removes the currently focused context item.
104        RemoveFocusedContext,
105        /// Accepts the suggested context item.
106        AcceptSuggestedContext,
107        /// Opens the active thread as a markdown file.
108        OpenActiveThreadAsMarkdown,
109        /// Opens the agent diff view to review changes.
110        OpenAgentDiff,
111        /// Keeps the current suggestion or change.
112        Keep,
113        /// Rejects the current suggestion or change.
114        Reject,
115        /// Rejects all suggestions or changes.
116        RejectAll,
117        /// Keeps all suggestions or changes.
118        KeepAll,
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    Thread(Entity<Thread>),
233    InlineAssistant,
234}
235
236impl ModelUsageContext {
237    pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
238        match self {
239            Self::Thread(thread) => thread.read(cx).configured_model(),
240            Self::InlineAssistant => {
241                LanguageModelRegistry::read_global(cx).inline_assistant_model()
242            }
243        }
244    }
245
246    pub fn language_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
247        self.configured_model(cx)
248            .map(|configured_model| configured_model.model)
249    }
250}
251
252/// Initializes the `agent` crate.
253pub fn init(
254    fs: Arc<dyn Fs>,
255    client: Arc<Client>,
256    prompt_builder: Arc<PromptBuilder>,
257    language_registry: Arc<LanguageRegistry>,
258    is_eval: bool,
259    cx: &mut App,
260) {
261    AgentSettings::register(cx);
262    SlashCommandSettings::register(cx);
263
264    assistant_context::init(client.clone(), cx);
265    rules_library::init(cx);
266    if !is_eval {
267        // Initializing the language model from the user settings messes with the eval, so we only initialize them when
268        // we're not running inside of the eval.
269        init_language_model_settings(cx);
270    }
271    assistant_slash_command::init(cx);
272    agent::init(cx);
273    agent_panel::init(cx);
274    context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
275    TextThreadEditor::init(cx);
276
277    register_slash_commands(cx);
278    inline_assistant::init(
279        fs.clone(),
280        prompt_builder.clone(),
281        client.telemetry().clone(),
282        cx,
283    );
284    terminal_inline_assistant::init(fs.clone(), prompt_builder, client.telemetry().clone(), cx);
285    cx.observe_new(move |workspace, window, cx| {
286        ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
287    })
288    .detach();
289    cx.observe_new(ManageProfilesModal::register).detach();
290
291    // Update command palette filter based on AI settings
292    update_command_palette_filter(cx);
293
294    // Watch for settings changes
295    cx.observe_global::<SettingsStore>(|app_cx| {
296        // When settings change, update the command palette filter
297        update_command_palette_filter(app_cx);
298    })
299    .detach();
300}
301
302fn update_command_palette_filter(cx: &mut App) {
303    let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
304    CommandPaletteFilter::update_global(cx, |filter, _| {
305        if disable_ai {
306            filter.hide_namespace("agent");
307            filter.hide_namespace("assistant");
308            filter.hide_namespace("copilot");
309            filter.hide_namespace("supermaven");
310            filter.hide_namespace("zed_predict_onboarding");
311            filter.hide_namespace("edit_prediction");
312
313            use editor::actions::{
314                AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
315                PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
316            };
317            let edit_prediction_actions = [
318                TypeId::of::<AcceptEditPrediction>(),
319                TypeId::of::<AcceptPartialEditPrediction>(),
320                TypeId::of::<ShowEditPrediction>(),
321                TypeId::of::<NextEditPrediction>(),
322                TypeId::of::<PreviousEditPrediction>(),
323                TypeId::of::<ToggleEditPrediction>(),
324            ];
325            filter.hide_action_types(&edit_prediction_actions);
326            filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
327        } else {
328            filter.show_namespace("agent");
329            filter.show_namespace("assistant");
330            filter.show_namespace("copilot");
331            filter.show_namespace("zed_predict_onboarding");
332
333            filter.show_namespace("edit_prediction");
334
335            use editor::actions::{
336                AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
337                PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
338            };
339            let edit_prediction_actions = [
340                TypeId::of::<AcceptEditPrediction>(),
341                TypeId::of::<AcceptPartialEditPrediction>(),
342                TypeId::of::<ShowEditPrediction>(),
343                TypeId::of::<NextEditPrediction>(),
344                TypeId::of::<PreviousEditPrediction>(),
345                TypeId::of::<ToggleEditPrediction>(),
346            ];
347            filter.show_action_types(edit_prediction_actions.iter());
348
349            filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
350        }
351    });
352}
353
354fn init_language_model_settings(cx: &mut App) {
355    update_active_language_model_from_settings(cx);
356
357    cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
358        .detach();
359    cx.subscribe(
360        &LanguageModelRegistry::global(cx),
361        |_, event: &language_model::Event, cx| match event {
362            language_model::Event::ProviderStateChanged(_)
363            | language_model::Event::AddedProvider(_)
364            | language_model::Event::RemovedProvider(_) => {
365                update_active_language_model_from_settings(cx);
366            }
367            _ => {}
368        },
369    )
370    .detach();
371}
372
373fn update_active_language_model_from_settings(cx: &mut App) {
374    let settings = AgentSettings::get_global(cx);
375
376    fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
377        language_model::SelectedModel {
378            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
379            model: LanguageModelId::from(selection.model.clone()),
380        }
381    }
382
383    let default = settings.default_model.as_ref().map(to_selected_model);
384    let inline_assistant = settings
385        .inline_assistant_model
386        .as_ref()
387        .map(to_selected_model);
388    let commit_message = settings
389        .commit_message_model
390        .as_ref()
391        .map(to_selected_model);
392    let thread_summary = settings
393        .thread_summary_model
394        .as_ref()
395        .map(to_selected_model);
396    let inline_alternatives = settings
397        .inline_alternatives
398        .iter()
399        .map(to_selected_model)
400        .collect::<Vec<_>>();
401
402    LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
403        registry.select_default_model(default.as_ref(), cx);
404        registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
405        registry.select_commit_message_model(commit_message.as_ref(), cx);
406        registry.select_thread_summary_model(thread_summary.as_ref(), cx);
407        registry.select_inline_alternative_models(inline_alternatives, cx);
408    });
409}
410
411fn register_slash_commands(cx: &mut App) {
412    let slash_command_registry = SlashCommandRegistry::global(cx);
413
414    slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
415    slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
416    slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
417    slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
418    slash_command_registry
419        .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
420    slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
421    slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
422    slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
423    slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
424    slash_command_registry
425        .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
426    slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
427
428    cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
429        move |is_enabled, _cx| {
430            if is_enabled {
431                slash_command_registry.register_command(
432                    assistant_slash_commands::StreamingExampleSlashCommand,
433                    false,
434                );
435            }
436        }
437    })
438    .detach();
439
440    update_slash_commands_from_settings(cx);
441    cx.observe_global::<SettingsStore>(update_slash_commands_from_settings)
442        .detach();
443}
444
445fn update_slash_commands_from_settings(cx: &mut App) {
446    let slash_command_registry = SlashCommandRegistry::global(cx);
447    let settings = SlashCommandSettings::get_global(cx);
448
449    if settings.cargo_workspace.enabled {
450        slash_command_registry
451            .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
452    } else {
453        slash_command_registry
454            .unregister_command(assistant_slash_commands::CargoWorkspaceSlashCommand);
455    }
456}