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        /// Allow this operation only this time.
120        AllowOnce,
121        /// Allow this operation and remember the choice.
122        AllowAlways,
123        /// Reject this operation only this time.
124        RejectOnce,
125        /// Follows the agent's suggestions.
126        Follow,
127        /// Resets the trial upsell notification.
128        ResetTrialUpsell,
129        /// Resets the trial end upsell notification.
130        ResetTrialEndUpsell,
131        /// Continues the current thread.
132        ContinueThread,
133        /// Continues the thread with burn mode enabled.
134        ContinueWithBurnMode,
135        /// Toggles burn mode for faster responses.
136        ToggleBurnMode,
137    ]
138);
139
140#[derive(Clone, Copy, Debug, PartialEq, Eq, Action)]
141#[action(namespace = agent)]
142#[action(deprecated_aliases = ["assistant::QuoteSelection"])]
143/// Quotes the current selection in the agent panel's message editor.
144pub struct QuoteSelection;
145
146/// Creates a new conversation thread, optionally based on an existing thread.
147#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
148#[action(namespace = agent)]
149#[serde(deny_unknown_fields)]
150pub struct NewThread {
151    #[serde(default)]
152    from_thread_id: Option<ThreadId>,
153}
154
155/// Creates a new external agent conversation thread.
156#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
157#[action(namespace = agent)]
158#[serde(deny_unknown_fields)]
159pub struct NewExternalAgentThread {
160    /// Which agent to use for the conversation.
161    agent: Option<ExternalAgent>,
162}
163
164#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
165#[action(namespace = agent)]
166#[serde(deny_unknown_fields)]
167pub struct NewNativeAgentThreadFromSummary {
168    from_session_id: agent_client_protocol::SessionId,
169}
170
171// TODO unify this with AgentType
172#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
173#[serde(rename_all = "snake_case")]
174enum ExternalAgent {
175    #[default]
176    Gemini,
177    ClaudeCode,
178    NativeAgent,
179    Custom {
180        name: SharedString,
181        command: AgentServerCommand,
182    },
183}
184
185fn placeholder_command() -> AgentServerCommand {
186    AgentServerCommand {
187        path: "/placeholder".into(),
188        args: vec![],
189        env: None,
190    }
191}
192
193impl ExternalAgent {
194    fn name(&self) -> &'static str {
195        match self {
196            Self::NativeAgent => "zed",
197            Self::Gemini => "gemini-cli",
198            Self::ClaudeCode => "claude-code",
199            Self::Custom { .. } => "custom",
200        }
201    }
202
203    pub fn server(
204        &self,
205        fs: Arc<dyn fs::Fs>,
206        history: Entity<agent2::HistoryStore>,
207    ) -> Rc<dyn agent_servers::AgentServer> {
208        match self {
209            Self::Gemini => Rc::new(agent_servers::Gemini),
210            Self::ClaudeCode => Rc::new(agent_servers::ClaudeCode),
211            Self::NativeAgent => Rc::new(agent2::NativeAgentServer::new(fs, history)),
212            Self::Custom { name, command: _ } => {
213                Rc::new(agent_servers::CustomAgentServer::new(name.clone()))
214            }
215        }
216    }
217}
218
219/// Opens the profile management interface for configuring agent tools and settings.
220#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
221#[action(namespace = agent)]
222#[serde(deny_unknown_fields)]
223pub struct ManageProfiles {
224    #[serde(default)]
225    pub customize_tools: Option<AgentProfileId>,
226}
227
228impl ManageProfiles {
229    pub fn customize_tools(profile_id: AgentProfileId) -> Self {
230        Self {
231            customize_tools: Some(profile_id),
232        }
233    }
234}
235
236#[derive(Clone)]
237pub(crate) enum ModelUsageContext {
238    Thread(Entity<Thread>),
239    InlineAssistant,
240}
241
242impl ModelUsageContext {
243    pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
244        match self {
245            Self::Thread(thread) => thread.read(cx).configured_model(),
246            Self::InlineAssistant => {
247                LanguageModelRegistry::read_global(cx).inline_assistant_model()
248            }
249        }
250    }
251
252    pub fn language_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
253        self.configured_model(cx)
254            .map(|configured_model| configured_model.model)
255    }
256}
257
258/// Initializes the `agent` crate.
259pub fn init(
260    fs: Arc<dyn Fs>,
261    client: Arc<Client>,
262    prompt_builder: Arc<PromptBuilder>,
263    language_registry: Arc<LanguageRegistry>,
264    is_eval: bool,
265    cx: &mut App,
266) {
267    AgentSettings::register(cx);
268    SlashCommandSettings::register(cx);
269
270    assistant_context::init(client.clone(), cx);
271    rules_library::init(cx);
272    if !is_eval {
273        // Initializing the language model from the user settings messes with the eval, so we only initialize them when
274        // we're not running inside of the eval.
275        init_language_model_settings(cx);
276    }
277    assistant_slash_command::init(cx);
278    agent::init(cx);
279    agent_panel::init(cx);
280    context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
281    TextThreadEditor::init(cx);
282
283    register_slash_commands(cx);
284    inline_assistant::init(
285        fs.clone(),
286        prompt_builder.clone(),
287        client.telemetry().clone(),
288        cx,
289    );
290    terminal_inline_assistant::init(fs.clone(), prompt_builder, client.telemetry().clone(), 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(ManageProfilesModal::register).detach();
296
297    // Update command palette filter based on AI settings
298    update_command_palette_filter(cx);
299
300    // Watch for settings changes
301    cx.observe_global::<SettingsStore>(|app_cx| {
302        // When settings change, update the command palette filter
303        update_command_palette_filter(app_cx);
304    })
305    .detach();
306}
307
308fn update_command_palette_filter(cx: &mut App) {
309    let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
310    CommandPaletteFilter::update_global(cx, |filter, _| {
311        if disable_ai {
312            filter.hide_namespace("agent");
313            filter.hide_namespace("assistant");
314            filter.hide_namespace("copilot");
315            filter.hide_namespace("supermaven");
316            filter.hide_namespace("zed_predict_onboarding");
317            filter.hide_namespace("edit_prediction");
318
319            use editor::actions::{
320                AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
321                PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
322            };
323            let edit_prediction_actions = [
324                TypeId::of::<AcceptEditPrediction>(),
325                TypeId::of::<AcceptPartialEditPrediction>(),
326                TypeId::of::<ShowEditPrediction>(),
327                TypeId::of::<NextEditPrediction>(),
328                TypeId::of::<PreviousEditPrediction>(),
329                TypeId::of::<ToggleEditPrediction>(),
330            ];
331            filter.hide_action_types(&edit_prediction_actions);
332            filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
333        } else {
334            filter.show_namespace("agent");
335            filter.show_namespace("assistant");
336            filter.show_namespace("copilot");
337            filter.show_namespace("zed_predict_onboarding");
338
339            filter.show_namespace("edit_prediction");
340
341            use editor::actions::{
342                AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
343                PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
344            };
345            let edit_prediction_actions = [
346                TypeId::of::<AcceptEditPrediction>(),
347                TypeId::of::<AcceptPartialEditPrediction>(),
348                TypeId::of::<ShowEditPrediction>(),
349                TypeId::of::<NextEditPrediction>(),
350                TypeId::of::<PreviousEditPrediction>(),
351                TypeId::of::<ToggleEditPrediction>(),
352            ];
353            filter.show_action_types(edit_prediction_actions.iter());
354
355            filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
356        }
357    });
358}
359
360fn init_language_model_settings(cx: &mut App) {
361    update_active_language_model_from_settings(cx);
362
363    cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
364        .detach();
365    cx.subscribe(
366        &LanguageModelRegistry::global(cx),
367        |_, event: &language_model::Event, cx| match event {
368            language_model::Event::ProviderStateChanged(_)
369            | language_model::Event::AddedProvider(_)
370            | language_model::Event::RemovedProvider(_) => {
371                update_active_language_model_from_settings(cx);
372            }
373            _ => {}
374        },
375    )
376    .detach();
377}
378
379fn update_active_language_model_from_settings(cx: &mut App) {
380    let settings = AgentSettings::get_global(cx);
381
382    fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
383        language_model::SelectedModel {
384            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
385            model: LanguageModelId::from(selection.model.clone()),
386        }
387    }
388
389    let default = settings.default_model.as_ref().map(to_selected_model);
390    let inline_assistant = settings
391        .inline_assistant_model
392        .as_ref()
393        .map(to_selected_model);
394    let commit_message = settings
395        .commit_message_model
396        .as_ref()
397        .map(to_selected_model);
398    let thread_summary = settings
399        .thread_summary_model
400        .as_ref()
401        .map(to_selected_model);
402    let inline_alternatives = settings
403        .inline_alternatives
404        .iter()
405        .map(to_selected_model)
406        .collect::<Vec<_>>();
407
408    LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
409        registry.select_default_model(default.as_ref(), cx);
410        registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
411        registry.select_commit_message_model(commit_message.as_ref(), cx);
412        registry.select_thread_summary_model(thread_summary.as_ref(), cx);
413        registry.select_inline_alternative_models(inline_alternatives, cx);
414    });
415}
416
417fn register_slash_commands(cx: &mut App) {
418    let slash_command_registry = SlashCommandRegistry::global(cx);
419
420    slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
421    slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
422    slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
423    slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
424    slash_command_registry
425        .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
426    slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
427    slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
428    slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
429    slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
430    slash_command_registry
431        .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
432    slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
433
434    cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
435        move |is_enabled, _cx| {
436            if is_enabled {
437                slash_command_registry.register_command(
438                    assistant_slash_commands::StreamingExampleSlashCommand,
439                    false,
440                );
441            }
442        }
443    })
444    .detach();
445
446    update_slash_commands_from_settings(cx);
447    cx.observe_global::<SettingsStore>(update_slash_commands_from_settings)
448        .detach();
449}
450
451fn update_slash_commands_from_settings(cx: &mut App) {
452    let slash_command_registry = SlashCommandRegistry::global(cx);
453    let settings = SlashCommandSettings::get_global(cx);
454
455    if settings.cargo_workspace.enabled {
456        slash_command_registry
457            .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
458    } else {
459        slash_command_registry
460            .unregister_command(assistant_slash_commands::CargoWorkspaceSlashCommand);
461    }
462}