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