agent_ui.rs

  1mod acp;
  2mod agent_configuration;
  3mod agent_diff;
  4mod agent_model_selector;
  5mod agent_panel;
  6pub mod agents_panel;
  7mod buffer_codegen;
  8mod context;
  9mod context_picker;
 10mod context_server_configuration;
 11mod context_store;
 12mod context_strip;
 13mod inline_assistant;
 14mod inline_prompt_editor;
 15mod language_model_selector;
 16mod message_editor;
 17mod profile_selector;
 18mod slash_command;
 19mod slash_command_picker;
 20mod terminal_codegen;
 21mod terminal_inline_assistant;
 22mod text_thread_editor;
 23mod ui;
 24
 25use std::rc::Rc;
 26use std::sync::Arc;
 27
 28use agent_settings::{AgentProfileId, AgentSettings};
 29use assistant_slash_command::SlashCommandRegistry;
 30use client::Client;
 31use command_palette_hooks::CommandPaletteFilter;
 32use feature_flags::FeatureFlagAppExt as _;
 33use fs::Fs;
 34use gpui::{Action, App, Entity, SharedString, actions};
 35use language::LanguageRegistry;
 36use language_model::{
 37    ConfiguredModel, LanguageModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
 38};
 39use project::DisableAiSettings;
 40use project::agent_server_store::AgentServerCommand;
 41use prompt_store::PromptBuilder;
 42use schemars::JsonSchema;
 43use serde::{Deserialize, Serialize};
 44use settings::{LanguageModelSelection, Settings as _, SettingsStore};
 45use std::any::TypeId;
 46
 47use crate::agent_configuration::{ConfigureContextServerModal, ManageProfilesModal};
 48pub use crate::agent_panel::{AgentPanel, ConcreteAssistantPanelDelegate};
 49pub use crate::inline_assistant::InlineAssistant;
 50pub use agent_diff::{AgentDiffPane, AgentDiffToolbar};
 51pub use text_thread_editor::{AgentPanelDelegate, TextThreadEditor};
 52use zed_actions;
 53
 54actions!(
 55    agent,
 56    [
 57        /// Creates a new text-based conversation thread.
 58        NewTextThread,
 59        /// Toggles the context picker interface for adding files, symbols, or other context.
 60        ToggleContextPicker,
 61        /// Toggles the menu to create new agent threads.
 62        ToggleNewThreadMenu,
 63        /// Toggles the navigation menu for switching between threads and views.
 64        ToggleNavigationMenu,
 65        /// Toggles the options menu for agent settings and preferences.
 66        ToggleOptionsMenu,
 67        /// Deletes the recently opened thread from history.
 68        DeleteRecentlyOpenThread,
 69        /// Toggles the profile or mode selector for switching between agent profiles.
 70        ToggleProfileSelector,
 71        /// Cycles through available session modes.
 72        CycleModeSelector,
 73        /// Removes all added context from the current conversation.
 74        RemoveAllContext,
 75        /// Expands the message editor to full size.
 76        ExpandMessageEditor,
 77        /// Opens the conversation history view.
 78        OpenHistory,
 79        /// Adds a context server to the configuration.
 80        AddContextServer,
 81        /// Removes the currently selected thread.
 82        RemoveSelectedThread,
 83        /// Starts a chat conversation with follow-up enabled.
 84        ChatWithFollow,
 85        /// Cycles to the next inline assist suggestion.
 86        CycleNextInlineAssist,
 87        /// Cycles to the previous inline assist suggestion.
 88        CyclePreviousInlineAssist,
 89        /// Moves focus up in the interface.
 90        FocusUp,
 91        /// Moves focus down in the interface.
 92        FocusDown,
 93        /// Moves focus left in the interface.
 94        FocusLeft,
 95        /// Moves focus right in the interface.
 96        FocusRight,
 97        /// Removes the currently focused context item.
 98        RemoveFocusedContext,
 99        /// Accepts the suggested context item.
100        AcceptSuggestedContext,
101        /// Opens the active thread as a markdown file.
102        OpenActiveThreadAsMarkdown,
103        /// Opens the agent diff view to review changes.
104        OpenAgentDiff,
105        /// Keeps the current suggestion or change.
106        Keep,
107        /// Rejects the current suggestion or change.
108        Reject,
109        /// Rejects all suggestions or changes.
110        RejectAll,
111        /// Keeps all suggestions or changes.
112        KeepAll,
113        /// Allow this operation only this time.
114        AllowOnce,
115        /// Allow this operation and remember the choice.
116        AllowAlways,
117        /// Reject this operation only this time.
118        RejectOnce,
119        /// Follows the agent's suggestions.
120        Follow,
121        /// Resets the trial upsell notification.
122        ResetTrialUpsell,
123        /// Resets the trial end upsell notification.
124        ResetTrialEndUpsell,
125        /// Continues the current thread.
126        ContinueThread,
127        /// Continues the thread with burn mode enabled.
128        ContinueWithBurnMode,
129        /// Toggles burn mode for faster responses.
130        ToggleBurnMode,
131    ]
132);
133
134/// Creates a new conversation thread, optionally based on an existing thread.
135#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
136#[action(namespace = agent)]
137#[serde(deny_unknown_fields)]
138pub struct NewThread;
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// TODO unify this with AgentType
157#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
158#[serde(rename_all = "snake_case")]
159pub enum ExternalAgent {
160    Gemini,
161    ClaudeCode,
162    Codex,
163    NativeAgent,
164    Custom {
165        name: SharedString,
166        command: AgentServerCommand,
167    },
168}
169
170fn placeholder_command() -> AgentServerCommand {
171    AgentServerCommand {
172        path: "/placeholder".into(),
173        args: vec![],
174        env: None,
175    }
176}
177
178impl ExternalAgent {
179    pub fn parse_built_in(server: &dyn agent_servers::AgentServer) -> Option<Self> {
180        match server.telemetry_id() {
181            "gemini-cli" => Some(Self::Gemini),
182            "claude-code" => Some(Self::ClaudeCode),
183            "codex" => Some(Self::Codex),
184            "zed" => Some(Self::NativeAgent),
185            _ => None,
186        }
187    }
188
189    pub fn server(
190        &self,
191        fs: Arc<dyn fs::Fs>,
192        history: Entity<agent::HistoryStore>,
193    ) -> Rc<dyn agent_servers::AgentServer> {
194        match self {
195            Self::Gemini => Rc::new(agent_servers::Gemini),
196            Self::ClaudeCode => Rc::new(agent_servers::ClaudeCode),
197            Self::Codex => Rc::new(agent_servers::Codex),
198            Self::NativeAgent => Rc::new(agent::NativeAgentServer::new(fs, history)),
199            Self::Custom { name, command: _ } => {
200                Rc::new(agent_servers::CustomAgentServer::new(name.clone()))
201            }
202        }
203    }
204}
205
206/// Opens the profile management interface for configuring agent tools and settings.
207#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
208#[action(namespace = agent)]
209#[serde(deny_unknown_fields)]
210pub struct ManageProfiles {
211    #[serde(default)]
212    pub customize_tools: Option<AgentProfileId>,
213}
214
215impl ManageProfiles {
216    pub fn customize_tools(profile_id: AgentProfileId) -> Self {
217        Self {
218            customize_tools: Some(profile_id),
219        }
220    }
221}
222
223#[derive(Clone)]
224pub(crate) enum ModelUsageContext {
225    InlineAssistant,
226}
227
228impl ModelUsageContext {
229    pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
230        match self {
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    agents_panel::init(cx);
254
255    assistant_text_thread::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_panel::init(cx);
264    context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
265    TextThreadEditor::init(cx);
266
267    register_slash_commands(cx);
268    inline_assistant::init(
269        fs.clone(),
270        prompt_builder.clone(),
271        client.telemetry().clone(),
272        cx,
273    );
274    terminal_inline_assistant::init(fs.clone(), prompt_builder, client.telemetry().clone(), cx);
275    cx.observe_new(move |workspace, window, cx| {
276        ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
277    })
278    .detach();
279    cx.observe_new(ManageProfilesModal::register).detach();
280
281    // Update command palette filter based on AI settings
282    update_command_palette_filter(cx);
283
284    // Watch for settings changes
285    cx.observe_global::<SettingsStore>(|app_cx| {
286        // When settings change, update the command palette filter
287        update_command_palette_filter(app_cx);
288    })
289    .detach();
290}
291
292fn update_command_palette_filter(cx: &mut App) {
293    let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
294    CommandPaletteFilter::update_global(cx, |filter, _| {
295        if disable_ai {
296            filter.hide_namespace("agent");
297            filter.hide_namespace("assistant");
298            filter.hide_namespace("copilot");
299            filter.hide_namespace("supermaven");
300            filter.hide_namespace("zed_predict_onboarding");
301            filter.hide_namespace("edit_prediction");
302
303            use editor::actions::{
304                AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
305                PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
306            };
307            let edit_prediction_actions = [
308                TypeId::of::<AcceptEditPrediction>(),
309                TypeId::of::<AcceptPartialEditPrediction>(),
310                TypeId::of::<ShowEditPrediction>(),
311                TypeId::of::<NextEditPrediction>(),
312                TypeId::of::<PreviousEditPrediction>(),
313                TypeId::of::<ToggleEditPrediction>(),
314            ];
315            filter.hide_action_types(&edit_prediction_actions);
316            filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
317        } else {
318            filter.show_namespace("agent");
319            filter.show_namespace("assistant");
320            filter.show_namespace("copilot");
321            filter.show_namespace("zed_predict_onboarding");
322
323            filter.show_namespace("edit_prediction");
324
325            use editor::actions::{
326                AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
327                PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
328            };
329            let edit_prediction_actions = [
330                TypeId::of::<AcceptEditPrediction>(),
331                TypeId::of::<AcceptPartialEditPrediction>(),
332                TypeId::of::<ShowEditPrediction>(),
333                TypeId::of::<NextEditPrediction>(),
334                TypeId::of::<PreviousEditPrediction>(),
335                TypeId::of::<ToggleEditPrediction>(),
336            ];
337            filter.show_action_types(edit_prediction_actions.iter());
338
339            filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
340        }
341    });
342}
343
344fn init_language_model_settings(cx: &mut App) {
345    update_active_language_model_from_settings(cx);
346
347    cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
348        .detach();
349    cx.subscribe(
350        &LanguageModelRegistry::global(cx),
351        |_, event: &language_model::Event, cx| match event {
352            language_model::Event::ProviderStateChanged(_)
353            | language_model::Event::AddedProvider(_)
354            | language_model::Event::RemovedProvider(_) => {
355                update_active_language_model_from_settings(cx);
356            }
357            _ => {}
358        },
359    )
360    .detach();
361}
362
363fn update_active_language_model_from_settings(cx: &mut App) {
364    let settings = AgentSettings::get_global(cx);
365
366    fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
367        language_model::SelectedModel {
368            provider: LanguageModelProviderId::from(selection.provider.0.clone()),
369            model: LanguageModelId::from(selection.model.clone()),
370        }
371    }
372
373    let default = settings.default_model.as_ref().map(to_selected_model);
374    let inline_assistant = settings
375        .inline_assistant_model
376        .as_ref()
377        .map(to_selected_model);
378    let commit_message = settings
379        .commit_message_model
380        .as_ref()
381        .map(to_selected_model);
382    let thread_summary = settings
383        .thread_summary_model
384        .as_ref()
385        .map(to_selected_model);
386    let inline_alternatives = settings
387        .inline_alternatives
388        .iter()
389        .map(to_selected_model)
390        .collect::<Vec<_>>();
391
392    LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
393        registry.select_default_model(default.as_ref(), cx);
394        registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
395        registry.select_commit_message_model(commit_message.as_ref(), cx);
396        registry.select_thread_summary_model(thread_summary.as_ref(), cx);
397        registry.select_inline_alternative_models(inline_alternatives, cx);
398    });
399}
400
401fn register_slash_commands(cx: &mut App) {
402    let slash_command_registry = SlashCommandRegistry::global(cx);
403
404    slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
405    slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
406    slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
407    slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
408    slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
409    slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
410    slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
411    slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
412    slash_command_registry
413        .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
414    slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
415
416    cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
417        move |is_enabled, _cx| {
418            if is_enabled {
419                slash_command_registry.register_command(
420                    assistant_slash_commands::StreamingExampleSlashCommand,
421                    false,
422                );
423            }
424        }
425    })
426    .detach();
427}