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;
10mod inline_assistant;
11mod inline_prompt_editor;
12mod language_model_selector;
13mod mention_set;
14mod profile_selector;
15mod slash_command;
16mod slash_command_picker;
17mod terminal_codegen;
18mod terminal_inline_assistant;
19mod text_thread_editor;
20mod ui;
21
22use std::rc::Rc;
23use std::sync::Arc;
24
25use agent_settings::{AgentProfileId, AgentSettings};
26use assistant_slash_command::SlashCommandRegistry;
27use client::Client;
28use command_palette_hooks::CommandPaletteFilter;
29use feature_flags::FeatureFlagAppExt as _;
30use fs::Fs;
31use gpui::{Action, App, Entity, SharedString, actions};
32use language::{
33 LanguageRegistry,
34 language_settings::{AllLanguageSettings, EditPredictionProvider},
35};
36use language_model::{
37 ConfiguredModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
38};
39use project::DisableAiSettings;
40use prompt_store::PromptBuilder;
41use schemars::JsonSchema;
42use serde::{Deserialize, Serialize};
43use settings::{LanguageModelSelection, Settings as _, SettingsStore};
44use std::any::TypeId;
45
46use crate::agent_configuration::{ConfigureContextServerModal, ManageProfilesModal};
47pub use crate::agent_panel::{AgentPanel, ConcreteAssistantPanelDelegate};
48pub use crate::inline_assistant::InlineAssistant;
49pub use agent_diff::{AgentDiffPane, AgentDiffToolbar};
50pub use text_thread_editor::{AgentPanelDelegate, TextThreadEditor};
51use zed_actions;
52
53actions!(
54 agent,
55 [
56 /// Creates a new text-based conversation thread.
57 NewTextThread,
58 /// Toggles the menu to create new agent threads.
59 ToggleNewThreadMenu,
60 /// Toggles the navigation menu for switching between threads and views.
61 ToggleNavigationMenu,
62 /// Toggles the options menu for agent settings and preferences.
63 ToggleOptionsMenu,
64 /// Deletes the recently opened thread from history.
65 DeleteRecentlyOpenThread,
66 /// Toggles the profile or mode selector for switching between agent profiles.
67 ToggleProfileSelector,
68 /// Cycles through available session modes.
69 CycleModeSelector,
70 /// Expands the message editor to full size.
71 ExpandMessageEditor,
72 /// Removes all thread history.
73 RemoveHistory,
74 /// Opens the conversation history view.
75 OpenHistory,
76 /// Adds a context server to the configuration.
77 AddContextServer,
78 /// Removes the currently selected thread.
79 RemoveSelectedThread,
80 /// Starts a chat conversation with follow-up enabled.
81 ChatWithFollow,
82 /// Cycles to the next inline assist suggestion.
83 CycleNextInlineAssist,
84 /// Cycles to the previous inline assist suggestion.
85 CyclePreviousInlineAssist,
86 /// Moves focus up in the interface.
87 FocusUp,
88 /// Moves focus down in the interface.
89 FocusDown,
90 /// Moves focus left in the interface.
91 FocusLeft,
92 /// Moves focus right in the interface.
93 FocusRight,
94 /// Opens the active thread as a markdown file.
95 OpenActiveThreadAsMarkdown,
96 /// Opens the agent diff view to review changes.
97 OpenAgentDiff,
98 /// Keeps the current suggestion or change.
99 Keep,
100 /// Rejects the current suggestion or change.
101 Reject,
102 /// Rejects all suggestions or changes.
103 RejectAll,
104 /// Keeps all suggestions or changes.
105 KeepAll,
106 /// Allow this operation only this time.
107 AllowOnce,
108 /// Allow this operation and remember the choice.
109 AllowAlways,
110 /// Reject this operation only this time.
111 RejectOnce,
112 /// Follows the agent's suggestions.
113 Follow,
114 /// Resets the trial upsell notification.
115 ResetTrialUpsell,
116 /// Resets the trial end upsell notification.
117 ResetTrialEndUpsell,
118 /// Continues the current thread.
119 ContinueThread,
120 /// Continues the thread with burn mode enabled.
121 ContinueWithBurnMode,
122 /// Toggles burn mode for faster responses.
123 ToggleBurnMode,
124 ]
125);
126
127/// Creates a new conversation thread, optionally based on an existing thread.
128#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
129#[action(namespace = agent)]
130#[serde(deny_unknown_fields)]
131pub struct NewThread;
132
133/// Creates a new external agent conversation thread.
134#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
135#[action(namespace = agent)]
136#[serde(deny_unknown_fields)]
137pub struct NewExternalAgentThread {
138 /// Which agent to use for the conversation.
139 agent: Option<ExternalAgent>,
140}
141
142#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
143#[action(namespace = agent)]
144#[serde(deny_unknown_fields)]
145pub struct NewNativeAgentThreadFromSummary {
146 from_session_id: agent_client_protocol::SessionId,
147}
148
149// TODO unify this with AgentType
150#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
151#[serde(rename_all = "snake_case")]
152pub enum ExternalAgent {
153 Gemini,
154 ClaudeCode,
155 Codex,
156 NativeAgent,
157 Custom { name: SharedString },
158}
159
160impl ExternalAgent {
161 pub fn parse_built_in(server: &dyn agent_servers::AgentServer) -> Option<Self> {
162 match server.telemetry_id() {
163 "gemini-cli" => Some(Self::Gemini),
164 "claude-code" => Some(Self::ClaudeCode),
165 "codex" => Some(Self::Codex),
166 "zed" => Some(Self::NativeAgent),
167 _ => None,
168 }
169 }
170
171 pub fn server(
172 &self,
173 fs: Arc<dyn fs::Fs>,
174 history: Entity<agent::HistoryStore>,
175 ) -> Rc<dyn agent_servers::AgentServer> {
176 match self {
177 Self::Gemini => Rc::new(agent_servers::Gemini),
178 Self::ClaudeCode => Rc::new(agent_servers::ClaudeCode),
179 Self::Codex => Rc::new(agent_servers::Codex),
180 Self::NativeAgent => Rc::new(agent::NativeAgentServer::new(fs, history)),
181 Self::Custom { name } => Rc::new(agent_servers::CustomAgentServer::new(name.clone())),
182 }
183 }
184}
185
186/// Opens the profile management interface for configuring agent tools and settings.
187#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
188#[action(namespace = agent)]
189#[serde(deny_unknown_fields)]
190pub struct ManageProfiles {
191 #[serde(default)]
192 pub customize_tools: Option<AgentProfileId>,
193}
194
195impl ManageProfiles {
196 pub fn customize_tools(profile_id: AgentProfileId) -> Self {
197 Self {
198 customize_tools: Some(profile_id),
199 }
200 }
201}
202
203#[derive(Clone)]
204pub(crate) enum ModelUsageContext {
205 InlineAssistant,
206}
207
208impl ModelUsageContext {
209 pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
210 match self {
211 Self::InlineAssistant => {
212 LanguageModelRegistry::read_global(cx).inline_assistant_model()
213 }
214 }
215 }
216}
217
218/// Initializes the `agent` crate.
219pub fn init(
220 fs: Arc<dyn Fs>,
221 client: Arc<Client>,
222 prompt_builder: Arc<PromptBuilder>,
223 language_registry: Arc<LanguageRegistry>,
224 is_eval: bool,
225 cx: &mut App,
226) {
227 assistant_text_thread::init(client.clone(), cx);
228 rules_library::init(cx);
229 if !is_eval {
230 // Initializing the language model from the user settings messes with the eval, so we only initialize them when
231 // we're not running inside of the eval.
232 init_language_model_settings(cx);
233 }
234 assistant_slash_command::init(cx);
235 agent_panel::init(cx);
236 context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
237 TextThreadEditor::init(cx);
238
239 register_slash_commands(cx);
240 inline_assistant::init(
241 fs.clone(),
242 prompt_builder.clone(),
243 client.telemetry().clone(),
244 cx,
245 );
246 terminal_inline_assistant::init(fs.clone(), prompt_builder, client.telemetry().clone(), cx);
247 cx.observe_new(move |workspace, window, cx| {
248 ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
249 })
250 .detach();
251 cx.observe_new(ManageProfilesModal::register).detach();
252
253 // Update command palette filter based on AI settings
254 update_command_palette_filter(cx);
255
256 // Watch for settings changes
257 cx.observe_global::<SettingsStore>(|app_cx| {
258 // When settings change, update the command palette filter
259 update_command_palette_filter(app_cx);
260 })
261 .detach();
262}
263
264fn update_command_palette_filter(cx: &mut App) {
265 let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
266 let agent_enabled = AgentSettings::get_global(cx).enabled;
267 let edit_prediction_provider = AllLanguageSettings::get_global(cx)
268 .edit_predictions
269 .provider;
270
271 CommandPaletteFilter::update_global(cx, |filter, _| {
272 use editor::actions::{
273 AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
274 PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
275 };
276 let edit_prediction_actions = [
277 TypeId::of::<AcceptEditPrediction>(),
278 TypeId::of::<AcceptPartialEditPrediction>(),
279 TypeId::of::<ShowEditPrediction>(),
280 TypeId::of::<NextEditPrediction>(),
281 TypeId::of::<PreviousEditPrediction>(),
282 TypeId::of::<ToggleEditPrediction>(),
283 ];
284
285 if disable_ai {
286 filter.hide_namespace("agent");
287 filter.hide_namespace("assistant");
288 filter.hide_namespace("copilot");
289 filter.hide_namespace("supermaven");
290 filter.hide_namespace("zed_predict_onboarding");
291 filter.hide_namespace("edit_prediction");
292
293 filter.hide_action_types(&edit_prediction_actions);
294 filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
295 } else {
296 if agent_enabled {
297 filter.show_namespace("agent");
298 } else {
299 filter.hide_namespace("agent");
300 }
301
302 filter.show_namespace("assistant");
303
304 match edit_prediction_provider {
305 EditPredictionProvider::None => {
306 filter.hide_namespace("edit_prediction");
307 filter.hide_namespace("copilot");
308 filter.hide_namespace("supermaven");
309 filter.hide_action_types(&edit_prediction_actions);
310 }
311 EditPredictionProvider::Copilot => {
312 filter.show_namespace("edit_prediction");
313 filter.show_namespace("copilot");
314 filter.hide_namespace("supermaven");
315 filter.show_action_types(edit_prediction_actions.iter());
316 }
317 EditPredictionProvider::Supermaven => {
318 filter.show_namespace("edit_prediction");
319 filter.hide_namespace("copilot");
320 filter.show_namespace("supermaven");
321 filter.show_action_types(edit_prediction_actions.iter());
322 }
323 EditPredictionProvider::Zed
324 | EditPredictionProvider::Codestral
325 | EditPredictionProvider::Experimental(_) => {
326 filter.show_namespace("edit_prediction");
327 filter.hide_namespace("copilot");
328 filter.hide_namespace("supermaven");
329 filter.show_action_types(edit_prediction_actions.iter());
330 }
331 }
332
333 filter.show_namespace("zed_predict_onboarding");
334 filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
335 }
336 });
337}
338
339fn init_language_model_settings(cx: &mut App) {
340 update_active_language_model_from_settings(cx);
341
342 cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
343 .detach();
344 cx.subscribe(
345 &LanguageModelRegistry::global(cx),
346 |_, event: &language_model::Event, cx| match event {
347 language_model::Event::ProviderStateChanged(id) => {
348 let now = std::time::SystemTime::now()
349 .duration_since(std::time::UNIX_EPOCH)
350 .unwrap_or_default()
351 .as_millis();
352 eprintln!(
353 "[{}ms] agent_ui global subscription: ProviderStateChanged for {:?}",
354 now, id
355 );
356 update_active_language_model_from_settings(cx);
357 }
358 language_model::Event::AddedProvider(id) => {
359 let now = std::time::SystemTime::now()
360 .duration_since(std::time::UNIX_EPOCH)
361 .unwrap_or_default()
362 .as_millis();
363 eprintln!(
364 "[{}ms] agent_ui global subscription: AddedProvider for {:?}",
365 now, id
366 );
367 update_active_language_model_from_settings(cx);
368 }
369 language_model::Event::RemovedProvider(id) => {
370 let now = std::time::SystemTime::now()
371 .duration_since(std::time::UNIX_EPOCH)
372 .unwrap_or_default()
373 .as_millis();
374 eprintln!(
375 "[{}ms] agent_ui global subscription: RemovedProvider for {:?}",
376 now, id
377 );
378 update_active_language_model_from_settings(cx);
379 }
380 _ => {}
381 },
382 )
383 .detach();
384}
385
386fn update_active_language_model_from_settings(cx: &mut App) {
387 let settings = AgentSettings::get_global(cx);
388
389 fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
390 language_model::SelectedModel {
391 provider: LanguageModelProviderId::from(selection.provider.0.clone()),
392 model: LanguageModelId::from(selection.model.clone()),
393 }
394 }
395
396 let default = settings.default_model.as_ref().map(to_selected_model);
397 let inline_assistant = settings
398 .inline_assistant_model
399 .as_ref()
400 .map(to_selected_model);
401 let commit_message = settings
402 .commit_message_model
403 .as_ref()
404 .map(to_selected_model);
405 let thread_summary = settings
406 .thread_summary_model
407 .as_ref()
408 .map(to_selected_model);
409 let inline_alternatives = settings
410 .inline_alternatives
411 .iter()
412 .map(to_selected_model)
413 .collect::<Vec<_>>();
414
415 LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
416 registry.select_default_model(default.as_ref(), cx);
417 registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
418 registry.select_commit_message_model(commit_message.as_ref(), cx);
419 registry.select_thread_summary_model(thread_summary.as_ref(), cx);
420 registry.select_inline_alternative_models(inline_alternatives, cx);
421 });
422}
423
424fn register_slash_commands(cx: &mut App) {
425 let slash_command_registry = SlashCommandRegistry::global(cx);
426
427 slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
428 slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
429 slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
430 slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
431 slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
432 slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
433 slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
434 slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
435 slash_command_registry
436 .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
437 slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
438
439 cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
440 move |is_enabled, _cx| {
441 if is_enabled {
442 slash_command_registry.register_command(
443 assistant_slash_commands::StreamingExampleSlashCommand,
444 false,
445 );
446 }
447 }
448 })
449 .detach();
450}
451
452#[cfg(test)]
453mod tests {
454 use super::*;
455 use agent_settings::{AgentProfileId, AgentSettings, CompletionMode};
456 use command_palette_hooks::CommandPaletteFilter;
457 use editor::actions::AcceptEditPrediction;
458 use gpui::{BorrowAppContext, TestAppContext, px};
459 use project::DisableAiSettings;
460 use settings::{
461 DefaultAgentView, DockPosition, NotifyWhenAgentWaiting, Settings, SettingsStore,
462 };
463
464 #[gpui::test]
465 fn test_agent_command_palette_visibility(cx: &mut TestAppContext) {
466 // Init settings
467 cx.update(|cx| {
468 let store = SettingsStore::test(cx);
469 cx.set_global(store);
470 command_palette_hooks::init(cx);
471 AgentSettings::register(cx);
472 DisableAiSettings::register(cx);
473 AllLanguageSettings::register(cx);
474 });
475
476 let agent_settings = AgentSettings {
477 enabled: true,
478 button: true,
479 dock: DockPosition::Right,
480 default_width: px(300.),
481 default_height: px(600.),
482 default_model: None,
483 inline_assistant_model: None,
484 commit_message_model: None,
485 thread_summary_model: None,
486 inline_alternatives: vec![],
487 default_profile: AgentProfileId::default(),
488 default_view: DefaultAgentView::Thread,
489 profiles: Default::default(),
490 always_allow_tool_actions: false,
491 notify_when_agent_waiting: NotifyWhenAgentWaiting::default(),
492 play_sound_when_agent_done: false,
493 single_file_review: false,
494 model_parameters: vec![],
495 preferred_completion_mode: CompletionMode::Normal,
496 enable_feedback: false,
497 expand_edit_card: true,
498 expand_terminal_card: true,
499 use_modifier_to_send: true,
500 message_editor_min_lines: 1,
501 };
502
503 cx.update(|cx| {
504 AgentSettings::override_global(agent_settings.clone(), cx);
505 DisableAiSettings::override_global(DisableAiSettings { disable_ai: false }, cx);
506
507 // Initial update
508 update_command_palette_filter(cx);
509 });
510
511 // Assert visible
512 cx.update(|cx| {
513 let filter = CommandPaletteFilter::try_global(cx).unwrap();
514 assert!(
515 !filter.is_hidden(&NewThread),
516 "NewThread should be visible by default"
517 );
518 });
519
520 // Disable agent
521 cx.update(|cx| {
522 let mut new_settings = agent_settings.clone();
523 new_settings.enabled = false;
524 AgentSettings::override_global(new_settings, cx);
525
526 // Trigger update
527 update_command_palette_filter(cx);
528 });
529
530 // Assert hidden
531 cx.update(|cx| {
532 let filter = CommandPaletteFilter::try_global(cx).unwrap();
533 assert!(
534 filter.is_hidden(&NewThread),
535 "NewThread should be hidden when agent is disabled"
536 );
537 });
538
539 // Test EditPredictionProvider
540 // Enable EditPredictionProvider::Copilot
541 cx.update(|cx| {
542 cx.update_global::<SettingsStore, _>(|store, cx| {
543 store.update_user_settings(cx, |s| {
544 s.project
545 .all_languages
546 .features
547 .get_or_insert(Default::default())
548 .edit_prediction_provider = Some(EditPredictionProvider::Copilot);
549 });
550 });
551 update_command_palette_filter(cx);
552 });
553
554 cx.update(|cx| {
555 let filter = CommandPaletteFilter::try_global(cx).unwrap();
556 assert!(
557 !filter.is_hidden(&AcceptEditPrediction),
558 "EditPrediction should be visible when provider is Copilot"
559 );
560 });
561
562 // Disable EditPredictionProvider (None)
563 cx.update(|cx| {
564 cx.update_global::<SettingsStore, _>(|store, cx| {
565 store.update_user_settings(cx, |s| {
566 s.project
567 .all_languages
568 .features
569 .get_or_insert(Default::default())
570 .edit_prediction_provider = Some(EditPredictionProvider::None);
571 });
572 });
573 update_command_palette_filter(cx);
574 });
575
576 cx.update(|cx| {
577 let filter = CommandPaletteFilter::try_global(cx).unwrap();
578 assert!(
579 filter.is_hidden(&AcceptEditPrediction),
580 "EditPrediction should be hidden when provider is None"
581 );
582 });
583 }
584}