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