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