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