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 workspace.activate_item(&existing, true, true, window, cx);
314 } else {
315 let registry_page = AgentRegistryPage::new(workspace, window, cx);
316 workspace.add_item_to_active_pane(
317 Box::new(registry_page),
318 None,
319 true,
320 window,
321 cx,
322 );
323 }
324 },
325 );
326 })
327 .detach();
328 cx.observe_new(ManageProfilesModal::register).detach();
329
330 // Update command palette filter based on AI settings
331 update_command_palette_filter(cx);
332
333 // Watch for settings changes
334 cx.observe_global::<SettingsStore>(|app_cx| {
335 // When settings change, update the command palette filter
336 update_command_palette_filter(app_cx);
337 })
338 .detach();
339
340 cx.on_flags_ready(|_, cx| {
341 update_command_palette_filter(cx);
342 })
343 .detach();
344}
345
346fn update_command_palette_filter(cx: &mut App) {
347 let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
348 let agent_enabled = AgentSettings::get_global(cx).enabled;
349 let agent_v2_enabled = cx.has_flag::<AgentV2FeatureFlag>();
350 let edit_prediction_provider = AllLanguageSettings::get_global(cx)
351 .edit_predictions
352 .provider;
353
354 CommandPaletteFilter::update_global(cx, |filter, _| {
355 use editor::actions::{
356 AcceptEditPrediction, AcceptNextLineEditPrediction, AcceptNextWordEditPrediction,
357 NextEditPrediction, PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
358 };
359 let edit_prediction_actions = [
360 TypeId::of::<AcceptEditPrediction>(),
361 TypeId::of::<AcceptNextWordEditPrediction>(),
362 TypeId::of::<AcceptNextLineEditPrediction>(),
363 TypeId::of::<AcceptEditPrediction>(),
364 TypeId::of::<ShowEditPrediction>(),
365 TypeId::of::<NextEditPrediction>(),
366 TypeId::of::<PreviousEditPrediction>(),
367 TypeId::of::<ToggleEditPrediction>(),
368 ];
369
370 if disable_ai {
371 filter.hide_namespace("agent");
372 filter.hide_namespace("agents");
373 filter.hide_namespace("assistant");
374 filter.hide_namespace("copilot");
375 filter.hide_namespace("supermaven");
376 filter.hide_namespace("zed_predict_onboarding");
377 filter.hide_namespace("edit_prediction");
378
379 filter.hide_action_types(&edit_prediction_actions);
380 filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
381 } else {
382 if agent_enabled {
383 filter.show_namespace("agent");
384 filter.show_namespace("agents");
385 filter.show_namespace("assistant");
386 } else {
387 filter.hide_namespace("agent");
388 filter.hide_namespace("agents");
389 filter.hide_namespace("assistant");
390 }
391
392 match edit_prediction_provider {
393 EditPredictionProvider::None => {
394 filter.hide_namespace("edit_prediction");
395 filter.hide_namespace("copilot");
396 filter.hide_namespace("supermaven");
397 filter.hide_action_types(&edit_prediction_actions);
398 }
399 EditPredictionProvider::Copilot => {
400 filter.show_namespace("edit_prediction");
401 filter.show_namespace("copilot");
402 filter.hide_namespace("supermaven");
403 filter.show_action_types(edit_prediction_actions.iter());
404 }
405 EditPredictionProvider::Supermaven => {
406 filter.show_namespace("edit_prediction");
407 filter.hide_namespace("copilot");
408 filter.show_namespace("supermaven");
409 filter.show_action_types(edit_prediction_actions.iter());
410 }
411 EditPredictionProvider::Zed
412 | EditPredictionProvider::Codestral
413 | EditPredictionProvider::Ollama
414 | EditPredictionProvider::OpenAiCompatibleApi
415 | EditPredictionProvider::Sweep
416 | EditPredictionProvider::Mercury
417 | EditPredictionProvider::Experimental(_) => {
418 filter.show_namespace("edit_prediction");
419 filter.hide_namespace("copilot");
420 filter.hide_namespace("supermaven");
421 filter.show_action_types(edit_prediction_actions.iter());
422 }
423 }
424
425 filter.show_namespace("zed_predict_onboarding");
426 filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
427 }
428
429 if agent_v2_enabled {
430 filter.show_namespace("multi_workspace");
431 } else {
432 filter.hide_namespace("multi_workspace");
433 }
434 });
435}
436
437fn init_language_model_settings(cx: &mut App) {
438 update_active_language_model_from_settings(cx);
439
440 cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
441 .detach();
442 cx.subscribe(
443 &LanguageModelRegistry::global(cx),
444 |_, event: &language_model::Event, cx| match event {
445 language_model::Event::ProviderStateChanged(_)
446 | language_model::Event::AddedProvider(_)
447 | language_model::Event::RemovedProvider(_)
448 | language_model::Event::ProvidersChanged => {
449 update_active_language_model_from_settings(cx);
450 }
451 _ => {}
452 },
453 )
454 .detach();
455}
456
457fn update_active_language_model_from_settings(cx: &mut App) {
458 let settings = AgentSettings::get_global(cx);
459
460 fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
461 language_model::SelectedModel {
462 provider: LanguageModelProviderId::from(selection.provider.0.clone()),
463 model: LanguageModelId::from(selection.model.clone()),
464 }
465 }
466
467 let default = settings.default_model.as_ref().map(to_selected_model);
468 let inline_assistant = settings
469 .inline_assistant_model
470 .as_ref()
471 .map(to_selected_model);
472 let commit_message = settings
473 .commit_message_model
474 .as_ref()
475 .map(to_selected_model);
476 let thread_summary = settings
477 .thread_summary_model
478 .as_ref()
479 .map(to_selected_model);
480 let inline_alternatives = settings
481 .inline_alternatives
482 .iter()
483 .map(to_selected_model)
484 .collect::<Vec<_>>();
485
486 LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
487 registry.select_default_model(default.as_ref(), cx);
488 registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
489 registry.select_commit_message_model(commit_message.as_ref(), cx);
490 registry.select_thread_summary_model(thread_summary.as_ref(), cx);
491 registry.select_inline_alternative_models(inline_alternatives, cx);
492 });
493}
494
495fn register_slash_commands(cx: &mut App) {
496 let slash_command_registry = SlashCommandRegistry::global(cx);
497
498 slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
499 slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
500 slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
501 slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
502 slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
503 slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
504 slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
505 slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
506 slash_command_registry
507 .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
508 slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
509
510 cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
511 move |is_enabled, _cx| {
512 if is_enabled {
513 slash_command_registry.register_command(
514 assistant_slash_commands::StreamingExampleSlashCommand,
515 false,
516 );
517 }
518 }
519 })
520 .detach();
521}
522
523#[cfg(test)]
524mod tests {
525 use super::*;
526 use agent_settings::{AgentProfileId, AgentSettings};
527 use command_palette_hooks::CommandPaletteFilter;
528 use editor::actions::AcceptEditPrediction;
529 use gpui::{BorrowAppContext, TestAppContext, px};
530 use project::DisableAiSettings;
531 use settings::{
532 DefaultAgentView, DockPosition, NotifyWhenAgentWaiting, Settings, SettingsStore,
533 };
534
535 #[gpui::test]
536 fn test_agent_command_palette_visibility(cx: &mut TestAppContext) {
537 // Init settings
538 cx.update(|cx| {
539 let store = SettingsStore::test(cx);
540 cx.set_global(store);
541 command_palette_hooks::init(cx);
542 AgentSettings::register(cx);
543 DisableAiSettings::register(cx);
544 AllLanguageSettings::register(cx);
545 });
546
547 let agent_settings = AgentSettings {
548 enabled: true,
549 button: true,
550 dock: DockPosition::Right,
551 default_width: px(300.),
552 default_height: px(600.),
553 default_model: None,
554 inline_assistant_model: None,
555 inline_assistant_use_streaming_tools: false,
556 commit_message_model: None,
557 thread_summary_model: None,
558 inline_alternatives: vec![],
559 favorite_models: vec![],
560 default_profile: AgentProfileId::default(),
561 default_view: DefaultAgentView::Thread,
562 profiles: Default::default(),
563
564 notify_when_agent_waiting: NotifyWhenAgentWaiting::default(),
565 play_sound_when_agent_done: false,
566 single_file_review: false,
567 model_parameters: vec![],
568 enable_feedback: false,
569 expand_edit_card: true,
570 expand_terminal_card: true,
571 cancel_generation_on_terminal_stop: true,
572 use_modifier_to_send: true,
573 message_editor_min_lines: 1,
574 tool_permissions: Default::default(),
575 show_turn_stats: false,
576 };
577
578 cx.update(|cx| {
579 AgentSettings::override_global(agent_settings.clone(), cx);
580 DisableAiSettings::override_global(DisableAiSettings { disable_ai: false }, cx);
581
582 // Initial update
583 update_command_palette_filter(cx);
584 });
585
586 // Assert visible
587 cx.update(|cx| {
588 let filter = CommandPaletteFilter::try_global(cx).unwrap();
589 assert!(
590 !filter.is_hidden(&NewThread),
591 "NewThread should be visible by default"
592 );
593 assert!(
594 !filter.is_hidden(&text_thread_editor::CopyCode),
595 "CopyCode should be visible when agent is enabled"
596 );
597 });
598
599 // Disable agent
600 cx.update(|cx| {
601 let mut new_settings = agent_settings.clone();
602 new_settings.enabled = false;
603 AgentSettings::override_global(new_settings, cx);
604
605 // Trigger update
606 update_command_palette_filter(cx);
607 });
608
609 // Assert hidden
610 cx.update(|cx| {
611 let filter = CommandPaletteFilter::try_global(cx).unwrap();
612 assert!(
613 filter.is_hidden(&NewThread),
614 "NewThread should be hidden when agent is disabled"
615 );
616 assert!(
617 filter.is_hidden(&text_thread_editor::CopyCode),
618 "CopyCode should be hidden when agent is disabled"
619 );
620 });
621
622 // Test EditPredictionProvider
623 // Enable EditPredictionProvider::Copilot
624 cx.update(|cx| {
625 cx.update_global::<SettingsStore, _>(|store, cx| {
626 store.update_user_settings(cx, |s| {
627 s.project
628 .all_languages
629 .edit_predictions
630 .get_or_insert(Default::default())
631 .provider = Some(EditPredictionProvider::Copilot);
632 });
633 });
634 update_command_palette_filter(cx);
635 });
636
637 cx.update(|cx| {
638 let filter = CommandPaletteFilter::try_global(cx).unwrap();
639 assert!(
640 !filter.is_hidden(&AcceptEditPrediction),
641 "EditPrediction should be visible when provider is Copilot"
642 );
643 });
644
645 // Disable EditPredictionProvider (None)
646 cx.update(|cx| {
647 cx.update_global::<SettingsStore, _>(|store, cx| {
648 store.update_user_settings(cx, |s| {
649 s.project
650 .all_languages
651 .edit_predictions
652 .get_or_insert(Default::default())
653 .provider = Some(EditPredictionProvider::None);
654 });
655 });
656 update_command_palette_filter(cx);
657 });
658
659 cx.update(|cx| {
660 let filter = CommandPaletteFilter::try_global(cx).unwrap();
661 assert!(
662 filter.is_hidden(&AcceptEditPrediction),
663 "EditPrediction should be hidden when provider is None"
664 );
665 });
666 }
667}