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