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::AgentServerCommand;
 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        command: AgentServerCommand,
174    },
175}
176
177impl ExternalAgent {
178    fn name(&self) -> &'static str {
179        match self {
180            Self::NativeAgent => "zed",
181            Self::Gemini => "gemini-cli",
182            Self::ClaudeCode => "claude-code",
183            Self::Custom { .. } => "custom",
184        }
185    }
186
187    pub fn server(
188        &self,
189        fs: Arc<dyn fs::Fs>,
190        history: Entity<agent2::HistoryStore>,
191    ) -> Rc<dyn agent_servers::AgentServer> {
192        match self {
193            Self::Gemini => Rc::new(agent_servers::Gemini),
194            Self::ClaudeCode => Rc::new(agent_servers::ClaudeCode),
195            Self::NativeAgent => Rc::new(agent2::NativeAgentServer::new(fs, history)),
196            Self::Custom { name, command } => Rc::new(agent_servers::CustomAgentServer::new(
197                name.clone(),
198                command.clone(),
199            )),
200        }
201    }
202}
203
204/// Opens the profile management interface for configuring agent tools and settings.
205#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
206#[action(namespace = agent)]
207#[serde(deny_unknown_fields)]
208pub struct ManageProfiles {
209    #[serde(default)]
210    pub customize_tools: Option<AgentProfileId>,
211}
212
213impl ManageProfiles {
214    pub fn customize_tools(profile_id: AgentProfileId) -> Self {
215        Self {
216            customize_tools: Some(profile_id),
217        }
218    }
219}
220
221#[derive(Clone)]
222pub(crate) enum ModelUsageContext {
223    Thread(Entity<Thread>),
224    InlineAssistant,
225}
226
227impl ModelUsageContext {
228    pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
229        match self {
230            Self::Thread(thread) => thread.read(cx).configured_model(),
231            Self::InlineAssistant => {
232                LanguageModelRegistry::read_global(cx).inline_assistant_model()
233            }
234        }
235    }
236
237    pub fn language_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
238        self.configured_model(cx)
239            .map(|configured_model| configured_model.model)
240    }
241}
242
243/// Initializes the `agent` crate.
244pub fn init(
245    fs: Arc<dyn Fs>,
246    client: Arc<Client>,
247    prompt_builder: Arc<PromptBuilder>,
248    language_registry: Arc<LanguageRegistry>,
249    is_eval: bool,
250    cx: &mut App,
251) {
252    AgentSettings::register(cx);
253    SlashCommandSettings::register(cx);
254
255    assistant_context::init(client.clone(), cx);
256    rules_library::init(cx);
257    if !is_eval {
258        // Initializing the language model from the user settings messes with the eval, so we only initialize them when
259        // we're not running inside of the eval.
260        init_language_model_settings(cx);
261    }
262    assistant_slash_command::init(cx);
263    agent::init(cx);
264    agent_panel::init(cx);
265    context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
266    TextThreadEditor::init(cx);
267
268    register_slash_commands(cx);
269    inline_assistant::init(
270        fs.clone(),
271        prompt_builder.clone(),
272        client.telemetry().clone(),
273        cx,
274    );
275    terminal_inline_assistant::init(fs.clone(), prompt_builder, client.telemetry().clone(), cx);
276    cx.observe_new(move |workspace, window, cx| {
277        ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
278    })
279    .detach();
280    cx.observe_new(ManageProfilesModal::register).detach();
281
282    // Update command palette filter based on AI settings
283    update_command_palette_filter(cx);
284
285    // Watch for settings changes
286    cx.observe_global::<SettingsStore>(|app_cx| {
287        // When settings change, update the command palette filter
288        update_command_palette_filter(app_cx);
289    })
290    .detach();
291}
292
293fn update_command_palette_filter(cx: &mut App) {
294    let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
295    CommandPaletteFilter::update_global(cx, |filter, _| {
296        if disable_ai {
297            filter.hide_namespace("agent");
298            filter.hide_namespace("assistant");
299            filter.hide_namespace("copilot");
300            filter.hide_namespace("supermaven");
301            filter.hide_namespace("zed_predict_onboarding");
302            filter.hide_namespace("edit_prediction");
303
304            use editor::actions::{
305                AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
306                PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
307            };
308            let edit_prediction_actions = [
309                TypeId::of::<AcceptEditPrediction>(),
310                TypeId::of::<AcceptPartialEditPrediction>(),
311                TypeId::of::<ShowEditPrediction>(),
312                TypeId::of::<NextEditPrediction>(),
313                TypeId::of::<PreviousEditPrediction>(),
314                TypeId::of::<ToggleEditPrediction>(),
315            ];
316            filter.hide_action_types(&edit_prediction_actions);
317            filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
318        } else {
319            filter.show_namespace("agent");
320            filter.show_namespace("assistant");
321            filter.show_namespace("copilot");
322            filter.show_namespace("zed_predict_onboarding");
323
324            filter.show_namespace("edit_prediction");
325
326            use editor::actions::{
327                AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
328                PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
329            };
330            let edit_prediction_actions = [
331                TypeId::of::<AcceptEditPrediction>(),
332                TypeId::of::<AcceptPartialEditPrediction>(),
333                TypeId::of::<ShowEditPrediction>(),
334                TypeId::of::<NextEditPrediction>(),
335                TypeId::of::<PreviousEditPrediction>(),
336                TypeId::of::<ToggleEditPrediction>(),
337            ];
338            filter.show_action_types(edit_prediction_actions.iter());
339
340            filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
341        }
342    });
343}
344
345fn init_language_model_settings(cx: &mut App) {
346    update_active_language_model_from_settings(cx);
347
348    cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
349        .detach();
350    cx.subscribe(
351        &LanguageModelRegistry::global(cx),
352        |_, event: &language_model::Event, cx| match event {
353            language_model::Event::ProviderStateChanged(_)
354            | language_model::Event::AddedProvider(_)
355            | language_model::Event::RemovedProvider(_) => {
356                update_active_language_model_from_settings(cx);
357            }
358            _ => {}
359        },
360    )
361    .detach();
362}
363
364fn update_active_language_model_from_settings(cx: &mut App) {
365    let settings = AgentSettings::get_global(cx);
366
367    fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
368        language_model::SelectedModel {
369            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
370            model: LanguageModelId::from(selection.model.clone()),
371        }
372    }
373
374    let default = settings.default_model.as_ref().map(to_selected_model);
375    let inline_assistant = settings
376        .inline_assistant_model
377        .as_ref()
378        .map(to_selected_model);
379    let commit_message = settings
380        .commit_message_model
381        .as_ref()
382        .map(to_selected_model);
383    let thread_summary = settings
384        .thread_summary_model
385        .as_ref()
386        .map(to_selected_model);
387    let inline_alternatives = settings
388        .inline_alternatives
389        .iter()
390        .map(to_selected_model)
391        .collect::<Vec<_>>();
392
393    LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
394        registry.select_default_model(default.as_ref(), cx);
395        registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
396        registry.select_commit_message_model(commit_message.as_ref(), cx);
397        registry.select_thread_summary_model(thread_summary.as_ref(), cx);
398        registry.select_inline_alternative_models(inline_alternatives, cx);
399    });
400}
401
402fn register_slash_commands(cx: &mut App) {
403    let slash_command_registry = SlashCommandRegistry::global(cx);
404
405    slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
406    slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
407    slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
408    slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
409    slash_command_registry
410        .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
411    slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
412    slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
413    slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
414    slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
415    slash_command_registry
416        .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
417    slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
418
419    cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
420        move |is_enabled, _cx| {
421            if is_enabled {
422                slash_command_registry.register_command(
423                    assistant_slash_commands::StreamingExampleSlashCommand,
424                    false,
425                );
426            }
427        }
428    })
429    .detach();
430
431    update_slash_commands_from_settings(cx);
432    cx.observe_global::<SettingsStore>(update_slash_commands_from_settings)
433        .detach();
434}
435
436fn update_slash_commands_from_settings(cx: &mut App) {
437    let slash_command_registry = SlashCommandRegistry::global(cx);
438    let settings = SlashCommandSettings::get_global(cx);
439
440    if settings.cargo_workspace.enabled {
441        slash_command_registry
442            .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
443    } else {
444        slash_command_registry
445            .unregister_command(assistant_slash_commands::CargoWorkspaceSlashCommand);
446    }
447}