1pub mod acp;
2mod agent_configuration;
3mod agent_diff;
4mod agent_model_selector;
5mod agent_panel;
6mod buffer_codegen;
7mod completion_provider;
8mod context;
9mod context_server_configuration;
10mod favorite_models;
11mod inline_assistant;
12mod inline_prompt_editor;
13mod language_model_selector;
14mod mention_set;
15mod profile_selector;
16mod slash_command;
17mod slash_command_picker;
18mod terminal_codegen;
19mod terminal_inline_assistant;
20mod text_thread_editor;
21mod text_thread_history;
22mod ui;
23
24use std::rc::Rc;
25use std::sync::Arc;
26
27use agent_settings::{AgentProfileId, AgentSettings};
28use assistant_slash_command::SlashCommandRegistry;
29use client::Client;
30use command_palette_hooks::CommandPaletteFilter;
31use feature_flags::{AgentV2FeatureFlag, FeatureFlagAppExt as _};
32use fs::Fs;
33use gpui::{Action, App, Entity, SharedString, actions};
34use language::{
35 LanguageRegistry,
36 language_settings::{AllLanguageSettings, EditPredictionProvider},
37};
38use language_model::{
39 ConfiguredModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
40};
41use project::DisableAiSettings;
42use prompt_store::PromptBuilder;
43use schemars::JsonSchema;
44use serde::{Deserialize, Serialize};
45use settings::{LanguageModelSelection, Settings as _, SettingsStore};
46use std::any::TypeId;
47
48use crate::agent_configuration::{ConfigureContextServerModal, ManageProfilesModal};
49pub use crate::agent_panel::{AgentPanel, ConcreteAssistantPanelDelegate};
50pub use crate::inline_assistant::InlineAssistant;
51pub use agent_diff::{AgentDiffPane, AgentDiffToolbar};
52pub use text_thread_editor::{AgentPanelDelegate, TextThreadEditor};
53use zed_actions;
54
55actions!(
56 agent,
57 [
58 /// Creates a new text-based conversation thread.
59 NewTextThread,
60 /// Toggles the menu to create new agent threads.
61 ToggleNewThreadMenu,
62 /// Toggles the navigation menu for switching between threads and views.
63 ToggleNavigationMenu,
64 /// Toggles the options menu for agent settings and preferences.
65 ToggleOptionsMenu,
66 /// Toggles the profile or mode selector for switching between agent profiles.
67 ToggleProfileSelector,
68 /// Cycles through available session modes.
69 CycleModeSelector,
70 /// Cycles through favorited models in the ACP model selector.
71 CycleFavoriteModels,
72 /// Expands the message editor to full size.
73 ExpandMessageEditor,
74 /// Removes all thread history.
75 RemoveHistory,
76 /// Opens the conversation history view.
77 OpenHistory,
78 /// Adds a context server to the configuration.
79 AddContextServer,
80 /// Removes the currently selected thread.
81 RemoveSelectedThread,
82 /// Starts a chat conversation with follow-up enabled.
83 ChatWithFollow,
84 /// Cycles to the next inline assist suggestion.
85 CycleNextInlineAssist,
86 /// Cycles to the previous inline assist suggestion.
87 CyclePreviousInlineAssist,
88 /// Moves focus up in the interface.
89 FocusUp,
90 /// Moves focus down in the interface.
91 FocusDown,
92 /// Moves focus left in the interface.
93 FocusLeft,
94 /// Moves focus right in the interface.
95 FocusRight,
96 /// Opens the active thread as a markdown file.
97 OpenActiveThreadAsMarkdown,
98 /// Opens the agent diff view to review changes.
99 OpenAgentDiff,
100 /// Keeps the current suggestion or change.
101 Keep,
102 /// Rejects the current suggestion or change.
103 Reject,
104 /// Rejects all suggestions or changes.
105 RejectAll,
106 /// Keeps all suggestions or changes.
107 KeepAll,
108 /// Allow this operation only this time.
109 AllowOnce,
110 /// Allow this operation and remember the choice.
111 AllowAlways,
112 /// Reject this operation only this time.
113 RejectOnce,
114 /// Follows the agent's suggestions.
115 Follow,
116 /// Resets the trial upsell notification.
117 ResetTrialUpsell,
118 /// Resets the trial end upsell notification.
119 ResetTrialEndUpsell,
120 /// Continues the current thread.
121 ContinueThread,
122 /// Interrupts the current generation and sends the message immediately.
123 SendImmediately,
124 /// Sends the next queued message immediately.
125 SendNextQueuedMessage,
126 /// Clears all messages from the queue.
127 ClearMessageQueue,
128 /// Opens the permission granularity dropdown for the current tool call.
129 OpenPermissionDropdown,
130 ]
131);
132
133/// Action to authorize a tool call with a specific permission option.
134/// This is used by the permission granularity dropdown to authorize tool calls.
135#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
136#[action(namespace = agent)]
137#[serde(deny_unknown_fields)]
138pub struct AuthorizeToolCall {
139 /// The tool call ID to authorize.
140 pub tool_call_id: String,
141 /// The permission option ID to use.
142 pub option_id: String,
143 /// The kind of permission option (serialized as string).
144 pub option_kind: String,
145}
146
147/// Action to select a permission granularity option from the dropdown.
148/// This updates the selected granularity without triggering authorization.
149#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
150#[action(namespace = agent)]
151#[serde(deny_unknown_fields)]
152pub struct SelectPermissionGranularity {
153 /// The tool call ID for which to select the granularity.
154 pub tool_call_id: String,
155 /// The index of the selected granularity option.
156 pub index: usize,
157}
158
159/// Creates a new conversation thread, optionally based on an existing thread.
160#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
161#[action(namespace = agent)]
162#[serde(deny_unknown_fields)]
163pub struct NewThread;
164
165/// Creates a new external agent conversation thread.
166#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
167#[action(namespace = agent)]
168#[serde(deny_unknown_fields)]
169pub struct NewExternalAgentThread {
170 /// Which agent to use for the conversation.
171 agent: Option<ExternalAgent>,
172}
173
174#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
175#[action(namespace = agent)]
176#[serde(deny_unknown_fields)]
177pub struct NewNativeAgentThreadFromSummary {
178 from_session_id: agent_client_protocol::SessionId,
179}
180
181// TODO unify this with AgentType
182#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
183#[serde(rename_all = "snake_case")]
184pub enum ExternalAgent {
185 Gemini,
186 ClaudeCode,
187 Codex,
188 NativeAgent,
189 Custom { name: SharedString },
190}
191
192impl ExternalAgent {
193 pub fn server(
194 &self,
195 fs: Arc<dyn fs::Fs>,
196 thread_store: Entity<agent::ThreadStore>,
197 ) -> Rc<dyn agent_servers::AgentServer> {
198 match self {
199 Self::Gemini => Rc::new(agent_servers::Gemini),
200 Self::ClaudeCode => Rc::new(agent_servers::ClaudeCode),
201 Self::Codex => Rc::new(agent_servers::Codex),
202 Self::NativeAgent => Rc::new(agent::NativeAgentServer::new(fs, thread_store)),
203 Self::Custom { name } => Rc::new(agent_servers::CustomAgentServer::new(name.clone())),
204 }
205 }
206}
207
208/// Opens the profile management interface for configuring agent tools and settings.
209#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
210#[action(namespace = agent)]
211#[serde(deny_unknown_fields)]
212pub struct ManageProfiles {
213 #[serde(default)]
214 pub customize_tools: Option<AgentProfileId>,
215}
216
217impl ManageProfiles {
218 pub fn customize_tools(profile_id: AgentProfileId) -> Self {
219 Self {
220 customize_tools: Some(profile_id),
221 }
222 }
223}
224
225#[derive(Clone)]
226pub(crate) enum ModelUsageContext {
227 InlineAssistant,
228}
229
230impl ModelUsageContext {
231 pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
232 match self {
233 Self::InlineAssistant => {
234 LanguageModelRegistry::read_global(cx).inline_assistant_model()
235 }
236 }
237 }
238}
239
240/// Initializes the `agent` crate.
241pub fn init(
242 fs: Arc<dyn Fs>,
243 client: Arc<Client>,
244 prompt_builder: Arc<PromptBuilder>,
245 language_registry: Arc<LanguageRegistry>,
246 is_eval: bool,
247 cx: &mut App,
248) {
249 assistant_text_thread::init(client, cx);
250 rules_library::init(cx);
251 if !is_eval {
252 // Initializing the language model from the user settings messes with the eval, so we only initialize them when
253 // we're not running inside of the eval.
254 init_language_model_settings(cx);
255 }
256 assistant_slash_command::init(cx);
257 agent_panel::init(cx);
258 context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
259 TextThreadEditor::init(cx);
260
261 register_slash_commands(cx);
262 inline_assistant::init(fs.clone(), prompt_builder.clone(), cx);
263 terminal_inline_assistant::init(fs.clone(), prompt_builder, cx);
264 cx.observe_new(move |workspace, window, cx| {
265 ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
266 })
267 .detach();
268 cx.observe_new(ManageProfilesModal::register).detach();
269
270 // Update command palette filter based on AI settings
271 update_command_palette_filter(cx);
272
273 // Watch for settings changes
274 cx.observe_global::<SettingsStore>(|app_cx| {
275 // When settings change, update the command palette filter
276 update_command_palette_filter(app_cx);
277 })
278 .detach();
279
280 cx.on_flags_ready(|_, cx| {
281 update_command_palette_filter(cx);
282 })
283 .detach();
284}
285
286fn update_command_palette_filter(cx: &mut App) {
287 let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
288 let agent_enabled = AgentSettings::get_global(cx).enabled;
289 let agent_v2_enabled = cx.has_flag::<AgentV2FeatureFlag>();
290 let edit_prediction_provider = AllLanguageSettings::get_global(cx)
291 .edit_predictions
292 .provider;
293
294 CommandPaletteFilter::update_global(cx, |filter, _| {
295 use editor::actions::{
296 AcceptEditPrediction, AcceptNextLineEditPrediction, AcceptNextWordEditPrediction,
297 NextEditPrediction, PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
298 };
299 let edit_prediction_actions = [
300 TypeId::of::<AcceptEditPrediction>(),
301 TypeId::of::<AcceptNextWordEditPrediction>(),
302 TypeId::of::<AcceptNextLineEditPrediction>(),
303 TypeId::of::<AcceptEditPrediction>(),
304 TypeId::of::<ShowEditPrediction>(),
305 TypeId::of::<NextEditPrediction>(),
306 TypeId::of::<PreviousEditPrediction>(),
307 TypeId::of::<ToggleEditPrediction>(),
308 ];
309
310 if disable_ai {
311 filter.hide_namespace("agent");
312 filter.hide_namespace("agents");
313 filter.hide_namespace("assistant");
314 filter.hide_namespace("copilot");
315 filter.hide_namespace("supermaven");
316 filter.hide_namespace("zed_predict_onboarding");
317 filter.hide_namespace("edit_prediction");
318
319 filter.hide_action_types(&edit_prediction_actions);
320 filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
321 } else {
322 if agent_enabled {
323 filter.show_namespace("agent");
324 filter.show_namespace("agents");
325 } else {
326 filter.hide_namespace("agent");
327 filter.hide_namespace("agents");
328 }
329
330 filter.show_namespace("assistant");
331
332 match edit_prediction_provider {
333 EditPredictionProvider::None => {
334 filter.hide_namespace("edit_prediction");
335 filter.hide_namespace("copilot");
336 filter.hide_namespace("supermaven");
337 filter.hide_action_types(&edit_prediction_actions);
338 }
339 EditPredictionProvider::Copilot => {
340 filter.show_namespace("edit_prediction");
341 filter.show_namespace("copilot");
342 filter.hide_namespace("supermaven");
343 filter.show_action_types(edit_prediction_actions.iter());
344 }
345 EditPredictionProvider::Supermaven => {
346 filter.show_namespace("edit_prediction");
347 filter.hide_namespace("copilot");
348 filter.show_namespace("supermaven");
349 filter.show_action_types(edit_prediction_actions.iter());
350 }
351 EditPredictionProvider::Zed
352 | EditPredictionProvider::Codestral
353 | EditPredictionProvider::Experimental(_) => {
354 filter.show_namespace("edit_prediction");
355 filter.hide_namespace("copilot");
356 filter.hide_namespace("supermaven");
357 filter.show_action_types(edit_prediction_actions.iter());
358 }
359 }
360
361 filter.show_namespace("zed_predict_onboarding");
362 filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
363 if !agent_v2_enabled {
364 filter.hide_action_types(&[TypeId::of::<zed_actions::agent::ToggleAgentPane>()]);
365 }
366 }
367 });
368}
369
370fn init_language_model_settings(cx: &mut App) {
371 update_active_language_model_from_settings(cx);
372
373 cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
374 .detach();
375 cx.subscribe(
376 &LanguageModelRegistry::global(cx),
377 |_, event: &language_model::Event, cx| match event {
378 language_model::Event::ProviderStateChanged(_)
379 | language_model::Event::AddedProvider(_)
380 | language_model::Event::RemovedProvider(_)
381 | language_model::Event::ProvidersChanged => {
382 update_active_language_model_from_settings(cx);
383 }
384 _ => {}
385 },
386 )
387 .detach();
388}
389
390fn update_active_language_model_from_settings(cx: &mut App) {
391 let settings = AgentSettings::get_global(cx);
392
393 fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
394 language_model::SelectedModel {
395 provider: LanguageModelProviderId::from(selection.provider.0.clone()),
396 model: LanguageModelId::from(selection.model.clone()),
397 }
398 }
399
400 let default = settings.default_model.as_ref().map(to_selected_model);
401 let inline_assistant = settings
402 .inline_assistant_model
403 .as_ref()
404 .map(to_selected_model);
405 let commit_message = settings
406 .commit_message_model
407 .as_ref()
408 .map(to_selected_model);
409 let thread_summary = settings
410 .thread_summary_model
411 .as_ref()
412 .map(to_selected_model);
413 let inline_alternatives = settings
414 .inline_alternatives
415 .iter()
416 .map(to_selected_model)
417 .collect::<Vec<_>>();
418
419 LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
420 registry.select_default_model(default.as_ref(), cx);
421 registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
422 registry.select_commit_message_model(commit_message.as_ref(), cx);
423 registry.select_thread_summary_model(thread_summary.as_ref(), cx);
424 registry.select_inline_alternative_models(inline_alternatives, cx);
425 });
426}
427
428fn register_slash_commands(cx: &mut App) {
429 let slash_command_registry = SlashCommandRegistry::global(cx);
430
431 slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
432 slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
433 slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
434 slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
435 slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
436 slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
437 slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
438 slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
439 slash_command_registry
440 .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
441 slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
442
443 cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
444 move |is_enabled, _cx| {
445 if is_enabled {
446 slash_command_registry.register_command(
447 assistant_slash_commands::StreamingExampleSlashCommand,
448 false,
449 );
450 }
451 }
452 })
453 .detach();
454}
455
456#[cfg(test)]
457mod tests {
458 use super::*;
459 use agent_settings::{AgentProfileId, AgentSettings};
460 use command_palette_hooks::CommandPaletteFilter;
461 use editor::actions::AcceptEditPrediction;
462 use gpui::{BorrowAppContext, TestAppContext, px};
463 use project::DisableAiSettings;
464 use settings::{
465 DefaultAgentView, DockPosition, DockSide, NotifyWhenAgentWaiting, Settings, SettingsStore,
466 };
467
468 #[gpui::test]
469 fn test_agent_command_palette_visibility(cx: &mut TestAppContext) {
470 // Init settings
471 cx.update(|cx| {
472 let store = SettingsStore::test(cx);
473 cx.set_global(store);
474 command_palette_hooks::init(cx);
475 AgentSettings::register(cx);
476 DisableAiSettings::register(cx);
477 AllLanguageSettings::register(cx);
478 });
479
480 let agent_settings = AgentSettings {
481 enabled: true,
482 button: true,
483 dock: DockPosition::Right,
484 agents_panel_dock: DockSide::Left,
485 default_width: px(300.),
486 default_height: px(600.),
487 default_model: None,
488 inline_assistant_model: None,
489 inline_assistant_use_streaming_tools: false,
490 commit_message_model: None,
491 thread_summary_model: None,
492 inline_alternatives: vec![],
493 favorite_models: vec![],
494 default_profile: AgentProfileId::default(),
495 default_view: DefaultAgentView::Thread,
496 profiles: Default::default(),
497 always_allow_tool_actions: false,
498 notify_when_agent_waiting: NotifyWhenAgentWaiting::default(),
499 play_sound_when_agent_done: false,
500 single_file_review: false,
501 model_parameters: vec![],
502 enable_feedback: false,
503 expand_edit_card: true,
504 expand_terminal_card: true,
505 use_modifier_to_send: true,
506 message_editor_min_lines: 1,
507 tool_permissions: Default::default(),
508 show_turn_stats: false,
509 };
510
511 cx.update(|cx| {
512 AgentSettings::override_global(agent_settings.clone(), cx);
513 DisableAiSettings::override_global(DisableAiSettings { disable_ai: false }, cx);
514
515 // Initial update
516 update_command_palette_filter(cx);
517 });
518
519 // Assert visible
520 cx.update(|cx| {
521 let filter = CommandPaletteFilter::try_global(cx).unwrap();
522 assert!(
523 !filter.is_hidden(&NewThread),
524 "NewThread should be visible by default"
525 );
526 });
527
528 // Disable agent
529 cx.update(|cx| {
530 let mut new_settings = agent_settings.clone();
531 new_settings.enabled = false;
532 AgentSettings::override_global(new_settings, cx);
533
534 // Trigger update
535 update_command_palette_filter(cx);
536 });
537
538 // Assert hidden
539 cx.update(|cx| {
540 let filter = CommandPaletteFilter::try_global(cx).unwrap();
541 assert!(
542 filter.is_hidden(&NewThread),
543 "NewThread should be hidden when agent is disabled"
544 );
545 });
546
547 // Test EditPredictionProvider
548 // Enable EditPredictionProvider::Copilot
549 cx.update(|cx| {
550 cx.update_global::<SettingsStore, _>(|store, cx| {
551 store.update_user_settings(cx, |s| {
552 s.project
553 .all_languages
554 .features
555 .get_or_insert(Default::default())
556 .edit_prediction_provider = Some(EditPredictionProvider::Copilot);
557 });
558 });
559 update_command_palette_filter(cx);
560 });
561
562 cx.update(|cx| {
563 let filter = CommandPaletteFilter::try_global(cx).unwrap();
564 assert!(
565 !filter.is_hidden(&AcceptEditPrediction),
566 "EditPrediction should be visible when provider is Copilot"
567 );
568 });
569
570 // Disable EditPredictionProvider (None)
571 cx.update(|cx| {
572 cx.update_global::<SettingsStore, _>(|store, cx| {
573 store.update_user_settings(cx, |s| {
574 s.project
575 .all_languages
576 .features
577 .get_or_insert(Default::default())
578 .edit_prediction_provider = Some(EditPredictionProvider::None);
579 });
580 });
581 update_command_palette_filter(cx);
582 });
583
584 cx.update(|cx| {
585 let filter = CommandPaletteFilter::try_global(cx).unwrap();
586 assert!(
587 filter.is_hidden(&AcceptEditPrediction),
588 "EditPrediction should be hidden when provider is None"
589 );
590 });
591 }
592}