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 terminal_codegen;
 18mod terminal_inline_assistant;
 19mod text_thread_editor;
 20mod ui;
 21
 22use std::rc::Rc;
 23use std::sync::Arc;
 24
 25use agent::ThreadId;
 26use agent_settings::{AgentProfileId, AgentSettings};
 27use assistant_slash_command::SlashCommandRegistry;
 28use client::Client;
 29use command_palette_hooks::CommandPaletteFilter;
 30use feature_flags::FeatureFlagAppExt as _;
 31use fs::Fs;
 32use gpui::{Action, App, Entity, SharedString, actions};
 33use language::LanguageRegistry;
 34use language_model::{
 35    ConfiguredModel, LanguageModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
 36};
 37use project::DisableAiSettings;
 38use project::agent_server_store::AgentServerCommand;
 39use prompt_store::PromptBuilder;
 40use schemars::JsonSchema;
 41use serde::{Deserialize, Serialize};
 42use settings::{LanguageModelSelection, Settings as _, SettingsStore};
 43use std::any::TypeId;
 44
 45use crate::agent_configuration::{ConfigureContextServerModal, ManageProfilesModal};
 46pub use crate::agent_panel::{AgentPanel, ConcreteAssistantPanelDelegate};
 47pub use crate::inline_assistant::InlineAssistant;
 48pub use agent_diff::{AgentDiffPane, AgentDiffToolbar};
 49pub use text_thread_editor::{AgentPanelDelegate, TextThreadEditor};
 50use zed_actions;
 51
 52actions!(
 53    agent,
 54    [
 55        /// Creates a new text-based conversation thread.
 56        NewTextThread,
 57        /// Toggles the context picker interface for adding files, symbols, or other context.
 58        ToggleContextPicker,
 59        /// Toggles the menu to create new agent threads.
 60        ToggleNewThreadMenu,
 61        /// Toggles the navigation menu for switching between threads and views.
 62        ToggleNavigationMenu,
 63        /// Toggles the options menu for agent settings and preferences.
 64        ToggleOptionsMenu,
 65        /// Deletes the recently opened thread from history.
 66        DeleteRecentlyOpenThread,
 67        /// Toggles the profile or mode selector for switching between agent profiles.
 68        ToggleProfileSelector,
 69        /// Cycles through available session modes.
 70        CycleModeSelector,
 71        /// Removes all added context from the current conversation.
 72        RemoveAllContext,
 73        /// Expands the message editor to full size.
 74        ExpandMessageEditor,
 75        /// Opens the conversation history view.
 76        OpenHistory,
 77        /// Adds a context server to the configuration.
 78        AddContextServer,
 79        /// Removes the currently selected thread.
 80        RemoveSelectedThread,
 81        /// Starts a chat conversation with follow-up enabled.
 82        ChatWithFollow,
 83        /// Cycles to the next inline assist suggestion.
 84        CycleNextInlineAssist,
 85        /// Cycles to the previous inline assist suggestion.
 86        CyclePreviousInlineAssist,
 87        /// Moves focus up in the interface.
 88        FocusUp,
 89        /// Moves focus down in the interface.
 90        FocusDown,
 91        /// Moves focus left in the interface.
 92        FocusLeft,
 93        /// Moves focus right in the interface.
 94        FocusRight,
 95        /// Removes the currently focused context item.
 96        RemoveFocusedContext,
 97        /// Accepts the suggested context item.
 98        AcceptSuggestedContext,
 99        /// Opens the active thread as a markdown file.
100        OpenActiveThreadAsMarkdown,
101        /// Opens the agent diff view to review changes.
102        OpenAgentDiff,
103        /// Keeps the current suggestion or change.
104        Keep,
105        /// Rejects the current suggestion or change.
106        Reject,
107        /// Rejects all suggestions or changes.
108        RejectAll,
109        /// Keeps all suggestions or changes.
110        KeepAll,
111        /// Allow this operation only this time.
112        AllowOnce,
113        /// Allow this operation and remember the choice.
114        AllowAlways,
115        /// Reject this operation only this time.
116        RejectOnce,
117        /// Follows the agent's suggestions.
118        Follow,
119        /// Resets the trial upsell notification.
120        ResetTrialUpsell,
121        /// Resets the trial end upsell notification.
122        ResetTrialEndUpsell,
123        /// Continues the current thread.
124        ContinueThread,
125        /// Continues the thread with burn mode enabled.
126        ContinueWithBurnMode,
127        /// Toggles burn mode for faster responses.
128        ToggleBurnMode,
129    ]
130);
131
132#[derive(Clone, Copy, Debug, PartialEq, Eq, Action)]
133#[action(namespace = agent)]
134#[action(deprecated_aliases = ["assistant::QuoteSelection"])]
135/// Quotes the current selection in the agent panel's message editor.
136pub struct QuoteSelection;
137
138/// Creates a new conversation thread, optionally based on an existing thread.
139#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
140#[action(namespace = agent)]
141#[serde(deny_unknown_fields)]
142pub struct NewThread {
143    #[serde(default)]
144    from_thread_id: Option<ThreadId>,
145}
146
147/// Creates a new external agent conversation thread.
148#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
149#[action(namespace = agent)]
150#[serde(deny_unknown_fields)]
151pub struct NewExternalAgentThread {
152    /// Which agent to use for the conversation.
153    agent: Option<ExternalAgent>,
154}
155
156#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
157#[action(namespace = agent)]
158#[serde(deny_unknown_fields)]
159pub struct NewNativeAgentThreadFromSummary {
160    from_session_id: agent_client_protocol::SessionId,
161}
162
163// TODO unify this with AgentType
164#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
165#[serde(rename_all = "snake_case")]
166enum ExternalAgent {
167    #[default]
168    Gemini,
169    ClaudeCode,
170    Codex,
171    NativeAgent,
172    Custom {
173        name: SharedString,
174        command: AgentServerCommand,
175    },
176}
177
178fn placeholder_command() -> AgentServerCommand {
179    AgentServerCommand {
180        path: "/placeholder".into(),
181        args: vec![],
182        env: None,
183    }
184}
185
186impl ExternalAgent {
187    fn name(&self) -> &'static str {
188        match self {
189            Self::NativeAgent => "zed",
190            Self::Gemini => "gemini-cli",
191            Self::ClaudeCode => "claude-code",
192            Self::Codex => "codex",
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::Codex => Rc::new(agent_servers::Codex),
206            Self::NativeAgent => Rc::new(agent2::NativeAgentServer::new(fs, history)),
207            Self::Custom { name, command: _ } => {
208                Rc::new(agent_servers::CustomAgentServer::new(name.clone()))
209            }
210        }
211    }
212}
213
214/// Opens the profile management interface for configuring agent tools and settings.
215#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
216#[action(namespace = agent)]
217#[serde(deny_unknown_fields)]
218pub struct ManageProfiles {
219    #[serde(default)]
220    pub customize_tools: Option<AgentProfileId>,
221}
222
223impl ManageProfiles {
224    pub fn customize_tools(profile_id: AgentProfileId) -> Self {
225        Self {
226            customize_tools: Some(profile_id),
227        }
228    }
229}
230
231#[derive(Clone)]
232pub(crate) enum ModelUsageContext {
233    InlineAssistant,
234}
235
236impl ModelUsageContext {
237    pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
238        match self {
239            Self::InlineAssistant => {
240                LanguageModelRegistry::read_global(cx).inline_assistant_model()
241            }
242        }
243    }
244
245    pub fn language_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
246        self.configured_model(cx)
247            .map(|configured_model| configured_model.model)
248    }
249}
250
251/// Initializes the `agent` crate.
252pub fn init(
253    fs: Arc<dyn Fs>,
254    client: Arc<Client>,
255    prompt_builder: Arc<PromptBuilder>,
256    language_registry: Arc<LanguageRegistry>,
257    is_eval: bool,
258    cx: &mut App,
259) {
260    AgentSettings::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(fs.clone(), 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.register_command(assistant_slash_commands::PromptSlashCommand, true);
417    slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
418    slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
419    slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
420    slash_command_registry
421        .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
422    slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
423
424    cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
425        move |is_enabled, _cx| {
426            if is_enabled {
427                slash_command_registry.register_command(
428                    assistant_slash_commands::StreamingExampleSlashCommand,
429                    false,
430                );
431            }
432        }
433    })
434    .detach();
435}