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_servers::AgentServerSettings;
 32use agent_settings::{AgentProfileId, AgentSettings, LanguageModelSelection};
 33use assistant_slash_command::SlashCommandRegistry;
 34use client::Client;
 35use command_palette_hooks::CommandPaletteFilter;
 36use feature_flags::FeatureFlagAppExt as _;
 37use fs::Fs;
 38use gpui::{Action, App, Entity, SharedString, actions};
 39use language::LanguageRegistry;
 40use language_model::{
 41    ConfiguredModel, LanguageModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
 42};
 43use project::DisableAiSettings;
 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 selector for switching between agent profiles.
 76        ToggleProfileSelector,
 77        /// Removes all added context from the current conversation.
 78        RemoveAllContext,
 79        /// Expands the message editor to full size.
 80        ExpandMessageEditor,
 81        /// Opens the conversation history view.
 82        OpenHistory,
 83        /// Adds a context server to the configuration.
 84        AddContextServer,
 85        /// Removes the currently selected thread.
 86        RemoveSelectedThread,
 87        /// Starts a chat conversation with follow-up enabled.
 88        ChatWithFollow,
 89        /// Cycles to the next inline assist suggestion.
 90        CycleNextInlineAssist,
 91        /// Cycles to the previous inline assist suggestion.
 92        CyclePreviousInlineAssist,
 93        /// Moves focus up in the interface.
 94        FocusUp,
 95        /// Moves focus down in the interface.
 96        FocusDown,
 97        /// Moves focus left in the interface.
 98        FocusLeft,
 99        /// Moves focus right in the interface.
100        FocusRight,
101        /// Removes the currently focused context item.
102        RemoveFocusedContext,
103        /// Accepts the suggested context item.
104        AcceptSuggestedContext,
105        /// Opens the active thread as a markdown file.
106        OpenActiveThreadAsMarkdown,
107        /// Opens the agent diff view to review changes.
108        OpenAgentDiff,
109        /// Keeps the current suggestion or change.
110        Keep,
111        /// Rejects the current suggestion or change.
112        Reject,
113        /// Rejects all suggestions or changes.
114        RejectAll,
115        /// Keeps all suggestions or changes.
116        KeepAll,
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    NativeAgent,
171    Custom {
172        name: SharedString,
173        settings: AgentServerSettings,
174    },
175}
176
177impl ExternalAgent {
178    pub fn server(
179        &self,
180        fs: Arc<dyn fs::Fs>,
181        history: Entity<agent2::HistoryStore>,
182    ) -> Rc<dyn agent_servers::AgentServer> {
183        match self {
184            Self::Gemini => Rc::new(agent_servers::Gemini),
185            Self::ClaudeCode => Rc::new(agent_servers::ClaudeCode),
186            Self::NativeAgent => Rc::new(agent2::NativeAgentServer::new(fs, history)),
187            Self::Custom { name, settings } => Rc::new(agent_servers::CustomAgentServer::new(
188                name.clone(),
189                settings,
190            )),
191        }
192    }
193}
194
195/// Opens the profile management interface for configuring agent tools and settings.
196#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
197#[action(namespace = agent)]
198#[serde(deny_unknown_fields)]
199pub struct ManageProfiles {
200    #[serde(default)]
201    pub customize_tools: Option<AgentProfileId>,
202}
203
204impl ManageProfiles {
205    pub fn customize_tools(profile_id: AgentProfileId) -> Self {
206        Self {
207            customize_tools: Some(profile_id),
208        }
209    }
210}
211
212#[derive(Clone)]
213pub(crate) enum ModelUsageContext {
214    Thread(Entity<Thread>),
215    InlineAssistant,
216}
217
218impl ModelUsageContext {
219    pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
220        match self {
221            Self::Thread(thread) => thread.read(cx).configured_model(),
222            Self::InlineAssistant => {
223                LanguageModelRegistry::read_global(cx).inline_assistant_model()
224            }
225        }
226    }
227
228    pub fn language_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
229        self.configured_model(cx)
230            .map(|configured_model| configured_model.model)
231    }
232}
233
234/// Initializes the `agent` crate.
235pub fn init(
236    fs: Arc<dyn Fs>,
237    client: Arc<Client>,
238    prompt_builder: Arc<PromptBuilder>,
239    language_registry: Arc<LanguageRegistry>,
240    is_eval: bool,
241    cx: &mut App,
242) {
243    AgentSettings::register(cx);
244    SlashCommandSettings::register(cx);
245
246    assistant_context::init(client.clone(), cx);
247    rules_library::init(cx);
248    if !is_eval {
249        // Initializing the language model from the user settings messes with the eval, so we only initialize them when
250        // we're not running inside of the eval.
251        init_language_model_settings(cx);
252    }
253    assistant_slash_command::init(cx);
254    agent::init(cx);
255    agent_panel::init(cx);
256    context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
257    TextThreadEditor::init(cx);
258
259    register_slash_commands(cx);
260    inline_assistant::init(
261        fs.clone(),
262        prompt_builder.clone(),
263        client.telemetry().clone(),
264        cx,
265    );
266    terminal_inline_assistant::init(fs.clone(), prompt_builder, client.telemetry().clone(), cx);
267    cx.observe_new(move |workspace, window, cx| {
268        ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
269    })
270    .detach();
271    cx.observe_new(ManageProfilesModal::register).detach();
272
273    // Update command palette filter based on AI settings
274    update_command_palette_filter(cx);
275
276    // Watch for settings changes
277    cx.observe_global::<SettingsStore>(|app_cx| {
278        // When settings change, update the command palette filter
279        update_command_palette_filter(app_cx);
280    })
281    .detach();
282}
283
284fn update_command_palette_filter(cx: &mut App) {
285    let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
286    CommandPaletteFilter::update_global(cx, |filter, _| {
287        if disable_ai {
288            filter.hide_namespace("agent");
289            filter.hide_namespace("assistant");
290            filter.hide_namespace("copilot");
291            filter.hide_namespace("supermaven");
292            filter.hide_namespace("zed_predict_onboarding");
293            filter.hide_namespace("edit_prediction");
294
295            use editor::actions::{
296                AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
297                PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
298            };
299            let edit_prediction_actions = [
300                TypeId::of::<AcceptEditPrediction>(),
301                TypeId::of::<AcceptPartialEditPrediction>(),
302                TypeId::of::<ShowEditPrediction>(),
303                TypeId::of::<NextEditPrediction>(),
304                TypeId::of::<PreviousEditPrediction>(),
305                TypeId::of::<ToggleEditPrediction>(),
306            ];
307            filter.hide_action_types(&edit_prediction_actions);
308            filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
309        } else {
310            filter.show_namespace("agent");
311            filter.show_namespace("assistant");
312            filter.show_namespace("copilot");
313            filter.show_namespace("zed_predict_onboarding");
314
315            filter.show_namespace("edit_prediction");
316
317            use editor::actions::{
318                AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
319                PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
320            };
321            let edit_prediction_actions = [
322                TypeId::of::<AcceptEditPrediction>(),
323                TypeId::of::<AcceptPartialEditPrediction>(),
324                TypeId::of::<ShowEditPrediction>(),
325                TypeId::of::<NextEditPrediction>(),
326                TypeId::of::<PreviousEditPrediction>(),
327                TypeId::of::<ToggleEditPrediction>(),
328            ];
329            filter.show_action_types(edit_prediction_actions.iter());
330
331            filter
332                .show_action_types([TypeId::of::<zed_actions::OpenZedPredictOnboarding>()].iter());
333        }
334    });
335}
336
337fn init_language_model_settings(cx: &mut App) {
338    update_active_language_model_from_settings(cx);
339
340    cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
341        .detach();
342    cx.subscribe(
343        &LanguageModelRegistry::global(cx),
344        |_, event: &language_model::Event, cx| match event {
345            language_model::Event::ProviderStateChanged(_)
346            | language_model::Event::AddedProvider(_)
347            | language_model::Event::RemovedProvider(_) => {
348                update_active_language_model_from_settings(cx);
349            }
350            _ => {}
351        },
352    )
353    .detach();
354}
355
356fn update_active_language_model_from_settings(cx: &mut App) {
357    let settings = AgentSettings::get_global(cx);
358
359    fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
360        language_model::SelectedModel {
361            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
362            model: LanguageModelId::from(selection.model.clone()),
363        }
364    }
365
366    let default = settings.default_model.as_ref().map(to_selected_model);
367    let inline_assistant = settings
368        .inline_assistant_model
369        .as_ref()
370        .map(to_selected_model);
371    let commit_message = settings
372        .commit_message_model
373        .as_ref()
374        .map(to_selected_model);
375    let thread_summary = settings
376        .thread_summary_model
377        .as_ref()
378        .map(to_selected_model);
379    let inline_alternatives = settings
380        .inline_alternatives
381        .iter()
382        .map(to_selected_model)
383        .collect::<Vec<_>>();
384
385    LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
386        registry.select_default_model(default.as_ref(), cx);
387        registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
388        registry.select_commit_message_model(commit_message.as_ref(), cx);
389        registry.select_thread_summary_model(thread_summary.as_ref(), cx);
390        registry.select_inline_alternative_models(inline_alternatives, cx);
391    });
392}
393
394fn register_slash_commands(cx: &mut App) {
395    let slash_command_registry = SlashCommandRegistry::global(cx);
396
397    slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
398    slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
399    slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
400    slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
401    slash_command_registry
402        .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
403    slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
404    slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
405    slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
406    slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
407    slash_command_registry
408        .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
409    slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
410
411    cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
412        move |is_enabled, _cx| {
413            if is_enabled {
414                slash_command_registry.register_command(
415                    assistant_slash_commands::StreamingExampleSlashCommand,
416                    false,
417                );
418            }
419        }
420    })
421    .detach();
422
423    update_slash_commands_from_settings(cx);
424    cx.observe_global::<SettingsStore>(update_slash_commands_from_settings)
425        .detach();
426}
427
428fn update_slash_commands_from_settings(cx: &mut App) {
429    let slash_command_registry = SlashCommandRegistry::global(cx);
430    let settings = SlashCommandSettings::get_global(cx);
431
432    if settings.cargo_workspace.enabled {
433        slash_command_registry
434            .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
435    } else {
436        slash_command_registry
437            .unregister_command(assistant_slash_commands::CargoWorkspaceSlashCommand);
438    }
439}