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
28// Another comment
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, AgentPanelEvent, 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 /// Cycles through available thinking effort levels for the current model.
147 CycleThinkingEffort,
148 /// Toggles the thinking effort selector menu open or closed.
149 ToggleThinkingEffortMenu,
150 ]
151);
152
153/// Action to authorize a tool call with a specific permission option.
154/// This is used by the permission granularity dropdown to authorize tool calls.
155#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
156#[action(namespace = agent)]
157#[serde(deny_unknown_fields)]
158pub struct AuthorizeToolCall {
159 /// The tool call ID to authorize.
160 pub tool_call_id: String,
161 /// The permission option ID to use.
162 pub option_id: String,
163 /// The kind of permission option (serialized as string).
164 pub option_kind: String,
165}
166
167/// Action to select a permission granularity option from the dropdown.
168/// This updates the selected granularity without triggering authorization.
169#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
170#[action(namespace = agent)]
171#[serde(deny_unknown_fields)]
172pub struct SelectPermissionGranularity {
173 /// The tool call ID for which to select the granularity.
174 pub tool_call_id: String,
175 /// The index of the selected granularity option.
176 pub index: usize,
177}
178
179/// Creates a new conversation thread, optionally based on an existing thread.
180#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
181#[action(namespace = agent)]
182#[serde(deny_unknown_fields)]
183pub struct NewThread;
184
185/// Creates a new external agent conversation thread.
186#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
187#[action(namespace = agent)]
188#[serde(deny_unknown_fields)]
189pub struct NewExternalAgentThread {
190 /// Which agent to use for the conversation.
191 agent: Option<ExternalAgent>,
192}
193
194#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
195#[action(namespace = agent)]
196#[serde(deny_unknown_fields)]
197pub struct NewNativeAgentThreadFromSummary {
198 from_session_id: agent_client_protocol::SessionId,
199}
200
201// TODO unify this with AgentType
202#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
203#[serde(rename_all = "snake_case")]
204pub enum ExternalAgent {
205 Gemini,
206 ClaudeCode,
207 Codex,
208 NativeAgent,
209 Custom { name: SharedString },
210}
211
212impl ExternalAgent {
213 pub fn server(
214 &self,
215 fs: Arc<dyn fs::Fs>,
216 thread_store: Entity<agent::ThreadStore>,
217 ) -> Rc<dyn agent_servers::AgentServer> {
218 match self {
219 Self::Gemini => Rc::new(agent_servers::Gemini),
220 Self::ClaudeCode => Rc::new(agent_servers::ClaudeCode),
221 Self::Codex => Rc::new(agent_servers::Codex),
222 Self::NativeAgent => Rc::new(agent::NativeAgentServer::new(fs, thread_store)),
223 Self::Custom { name } => Rc::new(agent_servers::CustomAgentServer::new(name.clone())),
224 }
225 }
226}
227
228/// Content to initialize new external agent with.
229pub enum ExternalAgentInitialContent {
230 ThreadSummary(acp_thread::AgentSessionInfo),
231 Text(String),
232}
233
234/// Opens the profile management interface for configuring agent tools and settings.
235#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
236#[action(namespace = agent)]
237#[serde(deny_unknown_fields)]
238pub struct ManageProfiles {
239 #[serde(default)]
240 pub customize_tools: Option<AgentProfileId>,
241}
242
243impl ManageProfiles {
244 pub fn customize_tools(profile_id: AgentProfileId) -> Self {
245 Self {
246 customize_tools: Some(profile_id),
247 }
248 }
249}
250
251#[derive(Clone)]
252pub(crate) enum ModelUsageContext {
253 InlineAssistant,
254}
255
256impl ModelUsageContext {
257 pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
258 match self {
259 Self::InlineAssistant => {
260 LanguageModelRegistry::read_global(cx).inline_assistant_model()
261 }
262 }
263 }
264}
265
266/// Initializes the `agent` crate.
267pub fn init(
268 fs: Arc<dyn Fs>,
269 client: Arc<Client>,
270 prompt_builder: Arc<PromptBuilder>,
271 language_registry: Arc<LanguageRegistry>,
272 is_eval: bool,
273 cx: &mut App,
274) {
275 agent::ThreadStore::init_global(cx);
276 assistant_text_thread::init(client, cx);
277 rules_library::init(cx);
278 if !is_eval {
279 // Initializing the language model from the user settings messes with the eval, so we only initialize them when
280 // we're not running inside of the eval.
281 init_language_model_settings(cx);
282 }
283 assistant_slash_command::init(cx);
284 agent_panel::init(cx);
285 context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
286 TextThreadEditor::init(cx);
287
288 register_slash_commands(cx);
289 inline_assistant::init(fs.clone(), prompt_builder.clone(), cx);
290 terminal_inline_assistant::init(fs.clone(), prompt_builder, cx);
291 cx.observe_new(move |workspace, window, cx| {
292 ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
293 })
294 .detach();
295 cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
296 workspace.register_action(
297 move |workspace: &mut Workspace,
298 _: &zed_actions::AcpRegistry,
299 window: &mut Window,
300 cx: &mut Context<Workspace>| {
301 let existing = workspace
302 .active_pane()
303 .read(cx)
304 .items()
305 .find_map(|item| item.downcast::<AgentRegistryPage>());
306
307 if let Some(existing) = existing {
308 workspace.activate_item(&existing, true, true, window, cx);
309 } else {
310 let registry_page = AgentRegistryPage::new(workspace, window, cx);
311 workspace.add_item_to_active_pane(
312 Box::new(registry_page),
313 None,
314 true,
315 window,
316 cx,
317 );
318 }
319 },
320 );
321 })
322 .detach();
323 cx.observe_new(ManageProfilesModal::register).detach();
324
325 // Update command palette filter based on AI settings
326 update_command_palette_filter(cx);
327
328 // Watch for settings changes
329 cx.observe_global::<SettingsStore>(|app_cx| {
330 // When settings change, update the command palette filter
331 update_command_palette_filter(app_cx);
332 })
333 .detach();
334
335 cx.on_flags_ready(|_, cx| {
336 update_command_palette_filter(cx);
337 })
338 .detach();
339}
340
341fn update_command_palette_filter(cx: &mut App) {
342 let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
343 let agent_enabled = AgentSettings::get_global(cx).enabled;
344 let agent_v2_enabled = cx.has_flag::<AgentV2FeatureFlag>();
345 let edit_prediction_provider = AllLanguageSettings::get_global(cx)
346 .edit_predictions
347 .provider;
348
349 CommandPaletteFilter::update_global(cx, |filter, _| {
350 use editor::actions::{
351 AcceptEditPrediction, AcceptNextLineEditPrediction, AcceptNextWordEditPrediction,
352 NextEditPrediction, PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
353 };
354 let edit_prediction_actions = [
355 TypeId::of::<AcceptEditPrediction>(),
356 TypeId::of::<AcceptNextWordEditPrediction>(),
357 TypeId::of::<AcceptNextLineEditPrediction>(),
358 TypeId::of::<AcceptEditPrediction>(),
359 TypeId::of::<ShowEditPrediction>(),
360 TypeId::of::<NextEditPrediction>(),
361 TypeId::of::<PreviousEditPrediction>(),
362 TypeId::of::<ToggleEditPrediction>(),
363 ];
364
365 if disable_ai {
366 filter.hide_namespace("agent");
367 filter.hide_namespace("agents");
368 filter.hide_namespace("assistant");
369 filter.hide_namespace("copilot");
370 filter.hide_namespace("supermaven");
371 filter.hide_namespace("zed_predict_onboarding");
372 filter.hide_namespace("edit_prediction");
373
374 filter.hide_action_types(&edit_prediction_actions);
375 filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
376 } else {
377 if agent_enabled {
378 filter.show_namespace("agent");
379 filter.show_namespace("agents");
380 filter.show_namespace("assistant");
381 } else {
382 filter.hide_namespace("agent");
383 filter.hide_namespace("agents");
384 filter.hide_namespace("assistant");
385 }
386
387 match edit_prediction_provider {
388 EditPredictionProvider::None => {
389 filter.hide_namespace("edit_prediction");
390 filter.hide_namespace("copilot");
391 filter.hide_namespace("supermaven");
392 filter.hide_action_types(&edit_prediction_actions);
393 }
394 EditPredictionProvider::Copilot => {
395 filter.show_namespace("edit_prediction");
396 filter.show_namespace("copilot");
397 filter.hide_namespace("supermaven");
398 filter.show_action_types(edit_prediction_actions.iter());
399 }
400 EditPredictionProvider::Supermaven => {
401 filter.show_namespace("edit_prediction");
402 filter.hide_namespace("copilot");
403 filter.show_namespace("supermaven");
404 filter.show_action_types(edit_prediction_actions.iter());
405 }
406 EditPredictionProvider::Zed
407 | EditPredictionProvider::Codestral
408 | EditPredictionProvider::Ollama
409 | EditPredictionProvider::Sweep
410 | EditPredictionProvider::Mercury
411 | EditPredictionProvider::Experimental(_) => {
412 filter.show_namespace("edit_prediction");
413 filter.hide_namespace("copilot");
414 filter.hide_namespace("supermaven");
415 filter.show_action_types(edit_prediction_actions.iter());
416 }
417 }
418
419 filter.show_namespace("zed_predict_onboarding");
420 filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
421 if !agent_v2_enabled {
422 filter.hide_action_types(&[TypeId::of::<zed_actions::agent::ToggleAgentPane>()]);
423 }
424 }
425
426 if agent_v2_enabled {
427 filter.show_namespace("multi_workspace");
428 } else {
429 filter.hide_namespace("multi_workspace");
430 }
431 });
432}
433
434fn init_language_model_settings(cx: &mut App) {
435 update_active_language_model_from_settings(cx);
436
437 cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
438 .detach();
439 cx.subscribe(
440 &LanguageModelRegistry::global(cx),
441 |_, event: &language_model::Event, cx| match event {
442 language_model::Event::ProviderStateChanged(_)
443 | language_model::Event::AddedProvider(_)
444 | language_model::Event::RemovedProvider(_)
445 | language_model::Event::ProvidersChanged => {
446 update_active_language_model_from_settings(cx);
447 }
448 _ => {}
449 },
450 )
451 .detach();
452}
453
454fn update_active_language_model_from_settings(cx: &mut App) {
455 let settings = AgentSettings::get_global(cx);
456
457 fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
458 language_model::SelectedModel {
459 provider: LanguageModelProviderId::from(selection.provider.0.clone()),
460 model: LanguageModelId::from(selection.model.clone()),
461 }
462 }
463
464 let default = settings.default_model.as_ref().map(to_selected_model);
465 let inline_assistant = settings
466 .inline_assistant_model
467 .as_ref()
468 .map(to_selected_model);
469 let commit_message = settings
470 .commit_message_model
471 .as_ref()
472 .map(to_selected_model);
473 let thread_summary = settings
474 .thread_summary_model
475 .as_ref()
476 .map(to_selected_model);
477 let inline_alternatives = settings
478 .inline_alternatives
479 .iter()
480 .map(to_selected_model)
481 .collect::<Vec<_>>();
482
483 LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
484 registry.select_default_model(default.as_ref(), cx);
485 registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
486 registry.select_commit_message_model(commit_message.as_ref(), cx);
487 registry.select_thread_summary_model(thread_summary.as_ref(), cx);
488 registry.select_inline_alternative_models(inline_alternatives, cx);
489 });
490}
491
492fn register_slash_commands(cx: &mut App) {
493 let slash_command_registry = SlashCommandRegistry::global(cx);
494
495 slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
496 slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
497 slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
498 slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
499 slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
500 slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
501 slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
502 slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
503 slash_command_registry
504 .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
505 slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
506
507 cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
508 move |is_enabled, _cx| {
509 if is_enabled {
510 slash_command_registry.register_command(
511 assistant_slash_commands::StreamingExampleSlashCommand,
512 false,
513 );
514 }
515 }
516 })
517 .detach();
518}
519
520#[cfg(test)]
521mod tests {
522 use super::*;
523 use agent_settings::{AgentProfileId, AgentSettings};
524 use command_palette_hooks::CommandPaletteFilter;
525 use editor::actions::AcceptEditPrediction;
526 use gpui::{BorrowAppContext, TestAppContext, px};
527 use project::DisableAiSettings;
528 use settings::{
529 DefaultAgentView, DockPosition, DockSide, NotifyWhenAgentWaiting, Settings, SettingsStore,
530 };
531
532 #[gpui::test]
533 fn test_agent_command_palette_visibility(cx: &mut TestAppContext) {
534 // Init settings
535 cx.update(|cx| {
536 let store = SettingsStore::test(cx);
537 cx.set_global(store);
538 command_palette_hooks::init(cx);
539 AgentSettings::register(cx);
540 DisableAiSettings::register(cx);
541 AllLanguageSettings::register(cx);
542 });
543
544 let agent_settings = AgentSettings {
545 enabled: true,
546 button: true,
547 dock: DockPosition::Right,
548 agents_panel_dock: DockSide::Left,
549 default_width: px(300.),
550 default_height: px(600.),
551 default_model: None,
552 inline_assistant_model: None,
553 inline_assistant_use_streaming_tools: false,
554 commit_message_model: None,
555 thread_summary_model: None,
556 inline_alternatives: vec![],
557 favorite_models: vec![],
558 default_profile: AgentProfileId::default(),
559 default_view: DefaultAgentView::Thread,
560 profiles: Default::default(),
561
562 notify_when_agent_waiting: NotifyWhenAgentWaiting::default(),
563 play_sound_when_agent_done: false,
564 single_file_review: false,
565 model_parameters: vec![],
566 enable_feedback: false,
567 expand_edit_card: true,
568 expand_terminal_card: true,
569 cancel_generation_on_terminal_stop: true,
570 use_modifier_to_send: true,
571 message_editor_min_lines: 1,
572 tool_permissions: Default::default(),
573 show_turn_stats: false,
574 };
575
576 cx.update(|cx| {
577 AgentSettings::override_global(agent_settings.clone(), cx);
578 DisableAiSettings::override_global(DisableAiSettings { disable_ai: false }, cx);
579
580 // Initial update
581 update_command_palette_filter(cx);
582 });
583
584 // Assert visible
585 cx.update(|cx| {
586 let filter = CommandPaletteFilter::try_global(cx).unwrap();
587 assert!(
588 !filter.is_hidden(&NewThread),
589 "NewThread should be visible by default"
590 );
591 assert!(
592 !filter.is_hidden(&text_thread_editor::CopyCode),
593 "CopyCode should be visible when agent is enabled"
594 );
595 });
596
597 // Disable agent
598 cx.update(|cx| {
599 let mut new_settings = agent_settings.clone();
600 new_settings.enabled = false;
601 AgentSettings::override_global(new_settings, cx);
602
603 // Trigger update
604 update_command_palette_filter(cx);
605 });
606
607 // Assert hidden
608 cx.update(|cx| {
609 let filter = CommandPaletteFilter::try_global(cx).unwrap();
610 assert!(
611 filter.is_hidden(&NewThread),
612 "NewThread should be hidden when agent is disabled"
613 );
614 assert!(
615 filter.is_hidden(&text_thread_editor::CopyCode),
616 "CopyCode should be hidden when agent is disabled"
617 );
618 });
619
620 // Test EditPredictionProvider
621 // Enable EditPredictionProvider::Copilot
622 cx.update(|cx| {
623 cx.update_global::<SettingsStore, _>(|store, cx| {
624 store.update_user_settings(cx, |s| {
625 s.project
626 .all_languages
627 .edit_predictions
628 .get_or_insert(Default::default())
629 .provider = Some(EditPredictionProvider::Copilot);
630 });
631 });
632 update_command_palette_filter(cx);
633 });
634
635 cx.update(|cx| {
636 let filter = CommandPaletteFilter::try_global(cx).unwrap();
637 assert!(
638 !filter.is_hidden(&AcceptEditPrediction),
639 "EditPrediction should be visible when provider is Copilot"
640 );
641 });
642
643 // Disable EditPredictionProvider (None)
644 cx.update(|cx| {
645 cx.update_global::<SettingsStore, _>(|store, cx| {
646 store.update_user_settings(cx, |s| {
647 s.project
648 .all_languages
649 .edit_predictions
650 .get_or_insert(Default::default())
651 .provider = Some(EditPredictionProvider::None);
652 });
653 });
654 update_command_palette_filter(cx);
655 });
656
657 cx.update(|cx| {
658 let filter = CommandPaletteFilter::try_global(cx).unwrap();
659 assert!(
660 filter.is_hidden(&AcceptEditPrediction),
661 "EditPrediction should be hidden when provider is None"
662 );
663 });
664 }
665}