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