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 let default = settings.default_model.as_ref().map(to_selected_model);
371 let inline_assistant = settings
372 .inline_assistant_model
373 .as_ref()
374 .map(to_selected_model);
375 let commit_message = settings
376 .commit_message_model
377 .as_ref()
378 .map(to_selected_model);
379 let thread_summary = settings
380 .thread_summary_model
381 .as_ref()
382 .map(to_selected_model);
383 let inline_alternatives = settings
384 .inline_alternatives
385 .iter()
386 .map(to_selected_model)
387 .collect::<Vec<_>>();
388
389 LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
390 registry.select_default_model(default.as_ref(), cx);
391 registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
392 registry.select_commit_message_model(commit_message.as_ref(), cx);
393 registry.select_thread_summary_model(thread_summary.as_ref(), cx);
394 registry.select_inline_alternative_models(inline_alternatives, cx);
395 });
396}
397
398fn register_slash_commands(cx: &mut App) {
399 let slash_command_registry = SlashCommandRegistry::global(cx);
400
401 slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
402 slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
403 slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
404 slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
405 slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
406 slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
407 slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
408 slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
409 slash_command_registry
410 .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
411 slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
412
413 cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
414 move |is_enabled, _cx| {
415 if is_enabled {
416 slash_command_registry.register_command(
417 assistant_slash_commands::StreamingExampleSlashCommand,
418 false,
419 );
420 }
421 }
422 })
423 .detach();
424}
425
426#[cfg(test)]
427mod tests {
428 use super::*;
429 use agent_settings::{AgentProfileId, AgentSettings, CompletionMode};
430 use command_palette_hooks::CommandPaletteFilter;
431 use editor::actions::AcceptEditPrediction;
432 use gpui::{BorrowAppContext, TestAppContext, px};
433 use project::DisableAiSettings;
434 use settings::{
435 DefaultAgentView, DockPosition, NotifyWhenAgentWaiting, Settings, SettingsStore,
436 };
437
438 #[gpui::test]
439 fn test_agent_command_palette_visibility(cx: &mut TestAppContext) {
440 // Init settings
441 cx.update(|cx| {
442 let store = SettingsStore::test(cx);
443 cx.set_global(store);
444 command_palette_hooks::init(cx);
445 AgentSettings::register(cx);
446 DisableAiSettings::register(cx);
447 AllLanguageSettings::register(cx);
448 });
449
450 let agent_settings = AgentSettings {
451 enabled: true,
452 button: true,
453 dock: DockPosition::Right,
454 default_width: px(300.),
455 default_height: px(600.),
456 default_model: None,
457 inline_assistant_model: None,
458 commit_message_model: None,
459 thread_summary_model: None,
460 inline_alternatives: vec![],
461 default_profile: AgentProfileId::default(),
462 default_view: DefaultAgentView::Thread,
463 profiles: Default::default(),
464 always_allow_tool_actions: false,
465 notify_when_agent_waiting: NotifyWhenAgentWaiting::default(),
466 play_sound_when_agent_done: false,
467 single_file_review: false,
468 model_parameters: vec![],
469 preferred_completion_mode: CompletionMode::Normal,
470 enable_feedback: false,
471 expand_edit_card: true,
472 expand_terminal_card: true,
473 use_modifier_to_send: true,
474 message_editor_min_lines: 1,
475 };
476
477 cx.update(|cx| {
478 AgentSettings::override_global(agent_settings.clone(), cx);
479 DisableAiSettings::override_global(DisableAiSettings { disable_ai: false }, cx);
480
481 // Initial update
482 update_command_palette_filter(cx);
483 });
484
485 // Assert visible
486 cx.update(|cx| {
487 let filter = CommandPaletteFilter::try_global(cx).unwrap();
488 assert!(
489 !filter.is_hidden(&NewThread),
490 "NewThread should be visible by default"
491 );
492 });
493
494 // Disable agent
495 cx.update(|cx| {
496 let mut new_settings = agent_settings.clone();
497 new_settings.enabled = false;
498 AgentSettings::override_global(new_settings, cx);
499
500 // Trigger update
501 update_command_palette_filter(cx);
502 });
503
504 // Assert hidden
505 cx.update(|cx| {
506 let filter = CommandPaletteFilter::try_global(cx).unwrap();
507 assert!(
508 filter.is_hidden(&NewThread),
509 "NewThread should be hidden when agent is disabled"
510 );
511 });
512
513 // Test EditPredictionProvider
514 // Enable EditPredictionProvider::Copilot
515 cx.update(|cx| {
516 cx.update_global::<SettingsStore, _>(|store, cx| {
517 store.update_user_settings(cx, |s| {
518 s.project
519 .all_languages
520 .features
521 .get_or_insert(Default::default())
522 .edit_prediction_provider = Some(EditPredictionProvider::Copilot);
523 });
524 });
525 update_command_palette_filter(cx);
526 });
527
528 cx.update(|cx| {
529 let filter = CommandPaletteFilter::try_global(cx).unwrap();
530 assert!(
531 !filter.is_hidden(&AcceptEditPrediction),
532 "EditPrediction should be visible when provider is Copilot"
533 );
534 });
535
536 // Disable EditPredictionProvider (None)
537 cx.update(|cx| {
538 cx.update_global::<SettingsStore, _>(|store, cx| {
539 store.update_user_settings(cx, |s| {
540 s.project
541 .all_languages
542 .features
543 .get_or_insert(Default::default())
544 .edit_prediction_provider = Some(EditPredictionProvider::None);
545 });
546 });
547 update_command_palette_filter(cx);
548 });
549
550 cx.update(|cx| {
551 let filter = CommandPaletteFilter::try_global(cx).unwrap();
552 assert!(
553 filter.is_hidden(&AcceptEditPrediction),
554 "EditPrediction should be hidden when provider is None"
555 );
556 });
557 }
558}