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