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, actions};
 38use language::LanguageRegistry;
 39use language_model::{
 40    ConfiguredModel, LanguageModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
 41};
 42use project::DisableAiSettings;
 43use prompt_store::PromptBuilder;
 44use schemars::JsonSchema;
 45use serde::{Deserialize, Serialize};
 46use settings::{Settings as _, SettingsStore};
 47use std::any::TypeId;
 48
 49pub use crate::active_thread::ActiveThread;
 50use crate::agent_configuration::{ConfigureContextServerModal, ManageProfilesModal};
 51pub use crate::agent_panel::{AgentPanel, ConcreteAssistantPanelDelegate};
 52pub use crate::inline_assistant::InlineAssistant;
 53use crate::slash_command_settings::SlashCommandSettings;
 54pub use agent_diff::{AgentDiffPane, AgentDiffToolbar};
 55pub use text_thread_editor::{AgentPanelDelegate, TextThreadEditor};
 56pub use ui::preview::{all_agent_previews, get_agent_preview};
 57use zed_actions;
 58
 59actions!(
 60    agent,
 61    [
 62        /// Creates a new text-based conversation thread.
 63        NewTextThread,
 64        /// Toggles the context picker interface for adding files, symbols, or other context.
 65        ToggleContextPicker,
 66        /// Toggles the menu to create new agent threads.
 67        ToggleNewThreadMenu,
 68        /// Toggles the navigation menu for switching between threads and views.
 69        ToggleNavigationMenu,
 70        /// Toggles the options menu for agent settings and preferences.
 71        ToggleOptionsMenu,
 72        /// Deletes the recently opened thread from history.
 73        DeleteRecentlyOpenThread,
 74        /// Toggles the profile selector for switching between agent profiles.
 75        ToggleProfileSelector,
 76        /// Removes all added context from the current conversation.
 77        RemoveAllContext,
 78        /// Expands the message editor to full size.
 79        ExpandMessageEditor,
 80        /// Opens the conversation history view.
 81        OpenHistory,
 82        /// Adds a context server to the configuration.
 83        AddContextServer,
 84        /// Removes the currently selected thread.
 85        RemoveSelectedThread,
 86        /// Starts a chat conversation with follow-up enabled.
 87        ChatWithFollow,
 88        /// Cycles to the next inline assist suggestion.
 89        CycleNextInlineAssist,
 90        /// Cycles to the previous inline assist suggestion.
 91        CyclePreviousInlineAssist,
 92        /// Moves focus up in the interface.
 93        FocusUp,
 94        /// Moves focus down in the interface.
 95        FocusDown,
 96        /// Moves focus left in the interface.
 97        FocusLeft,
 98        /// Moves focus right in the interface.
 99        FocusRight,
100        /// Removes the currently focused context item.
101        RemoveFocusedContext,
102        /// Accepts the suggested context item.
103        AcceptSuggestedContext,
104        /// Opens the active thread as a markdown file.
105        OpenActiveThreadAsMarkdown,
106        /// Opens the agent diff view to review changes.
107        OpenAgentDiff,
108        /// Keeps the current suggestion or change.
109        Keep,
110        /// Rejects the current suggestion or change.
111        Reject,
112        /// Rejects all suggestions or changes.
113        RejectAll,
114        /// Keeps all suggestions or changes.
115        KeepAll,
116        /// Follows the agent's suggestions.
117        Follow,
118        /// Resets the trial upsell notification.
119        ResetTrialUpsell,
120        /// Resets the trial end upsell notification.
121        ResetTrialEndUpsell,
122        /// Continues the current thread.
123        ContinueThread,
124        /// Continues the thread with burn mode enabled.
125        ContinueWithBurnMode,
126        /// Toggles burn mode for faster responses.
127        ToggleBurnMode,
128    ]
129);
130
131/// Creates a new conversation thread, optionally based on an existing thread.
132#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
133#[action(namespace = agent)]
134#[serde(deny_unknown_fields)]
135pub struct NewThread {
136    #[serde(default)]
137    from_thread_id: Option<ThreadId>,
138}
139
140/// Creates a new external agent conversation thread.
141#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
142#[action(namespace = agent)]
143#[serde(deny_unknown_fields)]
144pub struct NewExternalAgentThread {
145    /// Which agent to use for the conversation.
146    agent: Option<ExternalAgent>,
147}
148
149#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
150#[action(namespace = agent)]
151#[serde(deny_unknown_fields)]
152pub struct NewNativeAgentThreadFromSummary {
153    from_session_id: agent_client_protocol::SessionId,
154}
155
156#[derive(Default, Debug, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
157#[serde(rename_all = "snake_case")]
158enum ExternalAgent {
159    #[default]
160    Gemini,
161    ClaudeCode,
162    NativeAgent,
163}
164
165impl ExternalAgent {
166    pub fn server(
167        &self,
168        fs: Arc<dyn fs::Fs>,
169        history: Entity<agent2::HistoryStore>,
170    ) -> Rc<dyn agent_servers::AgentServer> {
171        match self {
172            ExternalAgent::Gemini => Rc::new(agent_servers::Gemini),
173            ExternalAgent::ClaudeCode => Rc::new(agent_servers::ClaudeCode),
174            ExternalAgent::NativeAgent => Rc::new(agent2::NativeAgentServer::new(fs, history)),
175        }
176    }
177}
178
179/// Opens the profile management interface for configuring agent tools and settings.
180#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
181#[action(namespace = agent)]
182#[serde(deny_unknown_fields)]
183pub struct ManageProfiles {
184    #[serde(default)]
185    pub customize_tools: Option<AgentProfileId>,
186}
187
188impl ManageProfiles {
189    pub fn customize_tools(profile_id: AgentProfileId) -> Self {
190        Self {
191            customize_tools: Some(profile_id),
192        }
193    }
194}
195
196#[derive(Clone)]
197pub(crate) enum ModelUsageContext {
198    Thread(Entity<Thread>),
199    InlineAssistant,
200}
201
202impl ModelUsageContext {
203    pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
204        match self {
205            Self::Thread(thread) => thread.read(cx).configured_model(),
206            Self::InlineAssistant => {
207                LanguageModelRegistry::read_global(cx).inline_assistant_model()
208            }
209        }
210    }
211
212    pub fn language_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
213        self.configured_model(cx)
214            .map(|configured_model| configured_model.model)
215    }
216}
217
218/// Initializes the `agent` crate.
219pub fn init(
220    fs: Arc<dyn Fs>,
221    client: Arc<Client>,
222    prompt_builder: Arc<PromptBuilder>,
223    language_registry: Arc<LanguageRegistry>,
224    is_eval: bool,
225    cx: &mut App,
226) {
227    AgentSettings::register(cx);
228    SlashCommandSettings::register(cx);
229
230    assistant_context::init(client.clone(), cx);
231    rules_library::init(cx);
232    if !is_eval {
233        // Initializing the language model from the user settings messes with the eval, so we only initialize them when
234        // we're not running inside of the eval.
235        init_language_model_settings(cx);
236    }
237    assistant_slash_command::init(cx);
238    agent::init(cx);
239    agent_panel::init(cx);
240    context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
241    TextThreadEditor::init(cx);
242
243    register_slash_commands(cx);
244    inline_assistant::init(
245        fs.clone(),
246        prompt_builder.clone(),
247        client.telemetry().clone(),
248        cx,
249    );
250    terminal_inline_assistant::init(fs.clone(), prompt_builder, client.telemetry().clone(), cx);
251    cx.observe_new(move |workspace, window, cx| {
252        ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
253    })
254    .detach();
255    cx.observe_new(ManageProfilesModal::register).detach();
256
257    // Update command palette filter based on AI settings
258    update_command_palette_filter(cx);
259
260    // Watch for settings changes
261    cx.observe_global::<SettingsStore>(|app_cx| {
262        // When settings change, update the command palette filter
263        update_command_palette_filter(app_cx);
264    })
265    .detach();
266}
267
268fn update_command_palette_filter(cx: &mut App) {
269    let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
270    CommandPaletteFilter::update_global(cx, |filter, _| {
271        if disable_ai {
272            filter.hide_namespace("agent");
273            filter.hide_namespace("assistant");
274            filter.hide_namespace("copilot");
275            filter.hide_namespace("supermaven");
276            filter.hide_namespace("zed_predict_onboarding");
277            filter.hide_namespace("edit_prediction");
278
279            use editor::actions::{
280                AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
281                PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
282            };
283            let edit_prediction_actions = [
284                TypeId::of::<AcceptEditPrediction>(),
285                TypeId::of::<AcceptPartialEditPrediction>(),
286                TypeId::of::<ShowEditPrediction>(),
287                TypeId::of::<NextEditPrediction>(),
288                TypeId::of::<PreviousEditPrediction>(),
289                TypeId::of::<ToggleEditPrediction>(),
290            ];
291            filter.hide_action_types(&edit_prediction_actions);
292            filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
293        } else {
294            filter.show_namespace("agent");
295            filter.show_namespace("assistant");
296            filter.show_namespace("copilot");
297            filter.show_namespace("zed_predict_onboarding");
298
299            filter.show_namespace("edit_prediction");
300
301            use editor::actions::{
302                AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
303                PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
304            };
305            let edit_prediction_actions = [
306                TypeId::of::<AcceptEditPrediction>(),
307                TypeId::of::<AcceptPartialEditPrediction>(),
308                TypeId::of::<ShowEditPrediction>(),
309                TypeId::of::<NextEditPrediction>(),
310                TypeId::of::<PreviousEditPrediction>(),
311                TypeId::of::<ToggleEditPrediction>(),
312            ];
313            filter.show_action_types(edit_prediction_actions.iter());
314
315            filter
316                .show_action_types([TypeId::of::<zed_actions::OpenZedPredictOnboarding>()].iter());
317        }
318    });
319}
320
321fn init_language_model_settings(cx: &mut App) {
322    update_active_language_model_from_settings(cx);
323
324    cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
325        .detach();
326    cx.subscribe(
327        &LanguageModelRegistry::global(cx),
328        |_, event: &language_model::Event, cx| match event {
329            language_model::Event::ProviderStateChanged(_)
330            | language_model::Event::AddedProvider(_)
331            | language_model::Event::RemovedProvider(_) => {
332                update_active_language_model_from_settings(cx);
333            }
334            _ => {}
335        },
336    )
337    .detach();
338}
339
340fn update_active_language_model_from_settings(cx: &mut App) {
341    let settings = AgentSettings::get_global(cx);
342
343    fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
344        language_model::SelectedModel {
345            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
346            model: LanguageModelId::from(selection.model.clone()),
347        }
348    }
349
350    let default = settings.default_model.as_ref().map(to_selected_model);
351    let inline_assistant = settings
352        .inline_assistant_model
353        .as_ref()
354        .map(to_selected_model);
355    let commit_message = settings
356        .commit_message_model
357        .as_ref()
358        .map(to_selected_model);
359    let thread_summary = settings
360        .thread_summary_model
361        .as_ref()
362        .map(to_selected_model);
363    let inline_alternatives = settings
364        .inline_alternatives
365        .iter()
366        .map(to_selected_model)
367        .collect::<Vec<_>>();
368
369    LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
370        registry.select_default_model(default.as_ref(), cx);
371        registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
372        registry.select_commit_message_model(commit_message.as_ref(), cx);
373        registry.select_thread_summary_model(thread_summary.as_ref(), cx);
374        registry.select_inline_alternative_models(inline_alternatives, cx);
375    });
376}
377
378fn register_slash_commands(cx: &mut App) {
379    let slash_command_registry = SlashCommandRegistry::global(cx);
380
381    slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
382    slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
383    slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
384    slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
385    slash_command_registry
386        .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
387    slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
388    slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
389    slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
390    slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
391    slash_command_registry
392        .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
393    slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
394
395    cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
396        move |is_enabled, _cx| {
397            if is_enabled {
398                slash_command_registry.register_command(
399                    assistant_slash_commands::StreamingExampleSlashCommand,
400                    false,
401                );
402            }
403        }
404    })
405    .detach();
406
407    update_slash_commands_from_settings(cx);
408    cx.observe_global::<SettingsStore>(update_slash_commands_from_settings)
409        .detach();
410}
411
412fn update_slash_commands_from_settings(cx: &mut App) {
413    let slash_command_registry = SlashCommandRegistry::global(cx);
414    let settings = SlashCommandSettings::get_global(cx);
415
416    if settings.cargo_workspace.enabled {
417        slash_command_registry
418            .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
419    } else {
420        slash_command_registry
421            .unregister_command(assistant_slash_commands::CargoWorkspaceSlashCommand);
422    }
423}