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