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