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 parse_built_in(server: &dyn agent_servers::AgentServer) -> Option<Self> {
164 match server.telemetry_id() {
165 "gemini-cli" => Some(Self::Gemini),
166 "claude-code" => Some(Self::ClaudeCode),
167 "codex" => Some(Self::Codex),
168 "zed" => Some(Self::NativeAgent),
169 _ => None,
170 }
171 }
172
173 pub fn server(
174 &self,
175 fs: Arc<dyn fs::Fs>,
176 history: Entity<agent::HistoryStore>,
177 ) -> Rc<dyn agent_servers::AgentServer> {
178 match self {
179 Self::Gemini => Rc::new(agent_servers::Gemini),
180 Self::ClaudeCode => Rc::new(agent_servers::ClaudeCode),
181 Self::Codex => Rc::new(agent_servers::Codex),
182 Self::NativeAgent => Rc::new(agent::NativeAgentServer::new(fs, history)),
183 Self::Custom { name } => Rc::new(agent_servers::CustomAgentServer::new(name.clone())),
184 }
185 }
186}
187
188/// Opens the profile management interface for configuring agent tools and settings.
189#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
190#[action(namespace = agent)]
191#[serde(deny_unknown_fields)]
192pub struct ManageProfiles {
193 #[serde(default)]
194 pub customize_tools: Option<AgentProfileId>,
195}
196
197impl ManageProfiles {
198 pub fn customize_tools(profile_id: AgentProfileId) -> Self {
199 Self {
200 customize_tools: Some(profile_id),
201 }
202 }
203}
204
205#[derive(Clone)]
206pub(crate) enum ModelUsageContext {
207 InlineAssistant,
208}
209
210impl ModelUsageContext {
211 pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
212 match self {
213 Self::InlineAssistant => {
214 LanguageModelRegistry::read_global(cx).inline_assistant_model()
215 }
216 }
217 }
218}
219
220/// Initializes the `agent` crate.
221pub fn init(
222 fs: Arc<dyn Fs>,
223 client: Arc<Client>,
224 prompt_builder: Arc<PromptBuilder>,
225 language_registry: Arc<LanguageRegistry>,
226 is_eval: bool,
227 cx: &mut App,
228) {
229 assistant_text_thread::init(client.clone(), cx);
230 rules_library::init(cx);
231 if !is_eval {
232 // Initializing the language model from the user settings messes with the eval, so we only initialize them when
233 // we're not running inside of the eval.
234 init_language_model_settings(cx);
235 }
236 assistant_slash_command::init(cx);
237 agent_panel::init(cx);
238 context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
239 TextThreadEditor::init(cx);
240
241 register_slash_commands(cx);
242 inline_assistant::init(
243 fs.clone(),
244 prompt_builder.clone(),
245 client.telemetry().clone(),
246 cx,
247 );
248 terminal_inline_assistant::init(fs.clone(), prompt_builder, client.telemetry().clone(), cx);
249 cx.observe_new(move |workspace, window, cx| {
250 ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
251 })
252 .detach();
253 cx.observe_new(ManageProfilesModal::register).detach();
254
255 // Update command palette filter based on AI settings
256 update_command_palette_filter(cx);
257
258 // Watch for settings changes
259 cx.observe_global::<SettingsStore>(|app_cx| {
260 // When settings change, update the command palette filter
261 update_command_palette_filter(app_cx);
262 })
263 .detach();
264}
265
266fn update_command_palette_filter(cx: &mut App) {
267 let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
268 let agent_enabled = AgentSettings::get_global(cx).enabled;
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, AcceptPartialEditPrediction, NextEditPrediction,
276 PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
277 };
278 let edit_prediction_actions = [
279 TypeId::of::<AcceptEditPrediction>(),
280 TypeId::of::<AcceptPartialEditPrediction>(),
281 TypeId::of::<ShowEditPrediction>(),
282 TypeId::of::<NextEditPrediction>(),
283 TypeId::of::<PreviousEditPrediction>(),
284 TypeId::of::<ToggleEditPrediction>(),
285 ];
286
287 if disable_ai {
288 filter.hide_namespace("agent");
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 } else {
301 filter.hide_namespace("agent");
302 }
303
304 filter.show_namespace("assistant");
305
306 match edit_prediction_provider {
307 EditPredictionProvider::None => {
308 filter.hide_namespace("edit_prediction");
309 filter.hide_namespace("copilot");
310 filter.hide_namespace("supermaven");
311 filter.hide_action_types(&edit_prediction_actions);
312 }
313 EditPredictionProvider::Copilot => {
314 filter.show_namespace("edit_prediction");
315 filter.show_namespace("copilot");
316 filter.hide_namespace("supermaven");
317 filter.show_action_types(edit_prediction_actions.iter());
318 }
319 EditPredictionProvider::Supermaven => {
320 filter.show_namespace("edit_prediction");
321 filter.hide_namespace("copilot");
322 filter.show_namespace("supermaven");
323 filter.show_action_types(edit_prediction_actions.iter());
324 }
325 EditPredictionProvider::Zed
326 | EditPredictionProvider::Codestral
327 | EditPredictionProvider::Experimental(_) => {
328 filter.show_namespace("edit_prediction");
329 filter.hide_namespace("copilot");
330 filter.hide_namespace("supermaven");
331 filter.show_action_types(edit_prediction_actions.iter());
332 }
333 }
334
335 filter.show_namespace("zed_predict_onboarding");
336 filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
337 }
338 });
339}
340
341fn init_language_model_settings(cx: &mut App) {
342 update_active_language_model_from_settings(cx);
343
344 cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
345 .detach();
346 cx.subscribe(
347 &LanguageModelRegistry::global(cx),
348 |_, event: &language_model::Event, cx| match event {
349 language_model::Event::ProviderStateChanged(_)
350 | language_model::Event::AddedProvider(_)
351 | language_model::Event::RemovedProvider(_) => {
352 update_active_language_model_from_settings(cx);
353 }
354 _ => {}
355 },
356 )
357 .detach();
358}
359
360fn update_active_language_model_from_settings(cx: &mut App) {
361 let settings = AgentSettings::get_global(cx);
362
363 fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
364 language_model::SelectedModel {
365 provider: LanguageModelProviderId::from(selection.provider.0.clone()),
366 model: LanguageModelId::from(selection.model.clone()),
367 }
368 }
369
370 // Filter out models from providers that are not authenticated
371 fn is_provider_authenticated(
372 selection: &LanguageModelSelection,
373 registry: &LanguageModelRegistry,
374 cx: &App,
375 ) -> bool {
376 let provider_id = LanguageModelProviderId::from(selection.provider.0.clone());
377 registry
378 .provider(&provider_id)
379 .map_or(false, |provider| provider.is_authenticated(cx))
380 }
381
382 let registry = LanguageModelRegistry::global(cx);
383 let registry_ref = registry.read(cx);
384
385 let default = settings
386 .default_model
387 .as_ref()
388 .filter(|s| is_provider_authenticated(s, registry_ref, cx))
389 .map(to_selected_model);
390 let inline_assistant = settings
391 .inline_assistant_model
392 .as_ref()
393 .filter(|s| is_provider_authenticated(s, registry_ref, cx))
394 .map(to_selected_model);
395 let commit_message = settings
396 .commit_message_model
397 .as_ref()
398 .filter(|s| is_provider_authenticated(s, registry_ref, cx))
399 .map(to_selected_model);
400 let thread_summary = settings
401 .thread_summary_model
402 .as_ref()
403 .filter(|s| is_provider_authenticated(s, registry_ref, cx))
404 .map(to_selected_model);
405 let inline_alternatives = settings
406 .inline_alternatives
407 .iter()
408 .filter(|s| is_provider_authenticated(s, registry_ref, cx))
409 .map(to_selected_model)
410 .collect::<Vec<_>>();
411
412 registry.update(cx, |registry, cx| {
413 registry.select_default_model(default.as_ref(), cx);
414 registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
415 registry.select_commit_message_model(commit_message.as_ref(), cx);
416 registry.select_thread_summary_model(thread_summary.as_ref(), cx);
417 registry.select_inline_alternative_models(inline_alternatives, cx);
418 });
419}
420
421fn register_slash_commands(cx: &mut App) {
422 let slash_command_registry = SlashCommandRegistry::global(cx);
423
424 slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
425 slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
426 slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
427 slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
428 slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
429 slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
430 slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
431 slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
432 slash_command_registry
433 .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
434 slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
435
436 cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
437 move |is_enabled, _cx| {
438 if is_enabled {
439 slash_command_registry.register_command(
440 assistant_slash_commands::StreamingExampleSlashCommand,
441 false,
442 );
443 }
444 }
445 })
446 .detach();
447}
448
449#[cfg(test)]
450mod tests {
451 use super::*;
452 use agent_settings::{AgentProfileId, AgentSettings, CompletionMode};
453 use command_palette_hooks::CommandPaletteFilter;
454 use editor::actions::AcceptEditPrediction;
455 use gpui::{BorrowAppContext, TestAppContext, px};
456 use project::DisableAiSettings;
457 use settings::{
458 DefaultAgentView, DockPosition, NotifyWhenAgentWaiting, Settings, SettingsStore,
459 };
460
461 #[gpui::test]
462 fn test_agent_command_palette_visibility(cx: &mut TestAppContext) {
463 // Init settings
464 cx.update(|cx| {
465 let store = SettingsStore::test(cx);
466 cx.set_global(store);
467 command_palette_hooks::init(cx);
468 AgentSettings::register(cx);
469 DisableAiSettings::register(cx);
470 AllLanguageSettings::register(cx);
471 });
472
473 let agent_settings = AgentSettings {
474 enabled: true,
475 button: true,
476 dock: DockPosition::Right,
477 default_width: px(300.),
478 default_height: px(600.),
479 default_model: None,
480 inline_assistant_model: None,
481 commit_message_model: None,
482 thread_summary_model: None,
483 inline_alternatives: vec![],
484 default_profile: AgentProfileId::default(),
485 default_view: DefaultAgentView::Thread,
486 profiles: Default::default(),
487 always_allow_tool_actions: false,
488 notify_when_agent_waiting: NotifyWhenAgentWaiting::default(),
489 play_sound_when_agent_done: false,
490 single_file_review: false,
491 model_parameters: vec![],
492 preferred_completion_mode: CompletionMode::Normal,
493 enable_feedback: false,
494 expand_edit_card: true,
495 expand_terminal_card: true,
496 use_modifier_to_send: true,
497 message_editor_min_lines: 1,
498 };
499
500 cx.update(|cx| {
501 AgentSettings::override_global(agent_settings.clone(), cx);
502 DisableAiSettings::override_global(DisableAiSettings { disable_ai: false }, cx);
503
504 // Initial update
505 update_command_palette_filter(cx);
506 });
507
508 // Assert visible
509 cx.update(|cx| {
510 let filter = CommandPaletteFilter::try_global(cx).unwrap();
511 assert!(
512 !filter.is_hidden(&NewThread),
513 "NewThread should be visible by default"
514 );
515 });
516
517 // Disable agent
518 cx.update(|cx| {
519 let mut new_settings = agent_settings.clone();
520 new_settings.enabled = false;
521 AgentSettings::override_global(new_settings, cx);
522
523 // Trigger update
524 update_command_palette_filter(cx);
525 });
526
527 // Assert hidden
528 cx.update(|cx| {
529 let filter = CommandPaletteFilter::try_global(cx).unwrap();
530 assert!(
531 filter.is_hidden(&NewThread),
532 "NewThread should be hidden when agent is disabled"
533 );
534 });
535
536 // Test EditPredictionProvider
537 // Enable EditPredictionProvider::Copilot
538 cx.update(|cx| {
539 cx.update_global::<SettingsStore, _>(|store, cx| {
540 store.update_user_settings(cx, |s| {
541 s.project
542 .all_languages
543 .features
544 .get_or_insert(Default::default())
545 .edit_prediction_provider = Some(EditPredictionProvider::Copilot);
546 });
547 });
548 update_command_palette_filter(cx);
549 });
550
551 cx.update(|cx| {
552 let filter = CommandPaletteFilter::try_global(cx).unwrap();
553 assert!(
554 !filter.is_hidden(&AcceptEditPrediction),
555 "EditPrediction should be visible when provider is Copilot"
556 );
557 });
558
559 // Disable EditPredictionProvider (None)
560 cx.update(|cx| {
561 cx.update_global::<SettingsStore, _>(|store, cx| {
562 store.update_user_settings(cx, |s| {
563 s.project
564 .all_languages
565 .features
566 .get_or_insert(Default::default())
567 .edit_prediction_provider = Some(EditPredictionProvider::None);
568 });
569 });
570 update_command_palette_filter(cx);
571 });
572
573 cx.update(|cx| {
574 let filter = CommandPaletteFilter::try_global(cx).unwrap();
575 assert!(
576 filter.is_hidden(&AcceptEditPrediction),
577 "EditPrediction should be hidden when provider is None"
578 );
579 });
580 }
581}