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