1mod acp;
2mod agent_configuration;
3mod agent_diff;
4mod agent_model_selector;
5mod agent_panel;
6mod buffer_codegen;
7mod context;
8mod context_picker;
9mod context_server_configuration;
10mod context_store;
11mod context_strip;
12mod inline_assistant;
13mod inline_prompt_editor;
14mod language_model_selector;
15mod profile_selector;
16mod slash_command;
17mod slash_command_picker;
18mod terminal_codegen;
19mod terminal_inline_assistant;
20mod text_thread_editor;
21mod ui;
22
23use std::rc::Rc;
24use std::sync::Arc;
25
26use agent_settings::{AgentProfileId, AgentSettings};
27use assistant_slash_command::SlashCommandRegistry;
28use client::Client;
29use command_palette_hooks::CommandPaletteFilter;
30use feature_flags::FeatureFlagAppExt as _;
31use fs::Fs;
32use gpui::{Action, App, Entity, SharedString, actions};
33use language::{
34 LanguageRegistry,
35 language_settings::{AllLanguageSettings, EditPredictionProvider},
36};
37use language_model::{
38 ConfiguredModel, LanguageModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
39};
40use project::DisableAiSettings;
41use project::agent_server_store::AgentServerCommand;
42use prompt_store::PromptBuilder;
43use schemars::JsonSchema;
44use serde::{Deserialize, Serialize};
45use settings::{LanguageModelSelection, Settings as _, SettingsStore};
46use std::any::TypeId;
47
48use crate::agent_configuration::{ConfigureContextServerModal, ManageProfilesModal};
49pub use crate::agent_panel::{AgentPanel, ConcreteAssistantPanelDelegate};
50pub use crate::inline_assistant::InlineAssistant;
51pub use agent_diff::{AgentDiffPane, AgentDiffToolbar};
52pub use text_thread_editor::{AgentPanelDelegate, TextThreadEditor};
53use zed_actions;
54
55actions!(
56 agent,
57 [
58 /// Creates a new text-based conversation thread.
59 NewTextThread,
60 /// Toggles the context picker interface for adding files, symbols, or other context.
61 ToggleContextPicker,
62 /// Toggles the menu to create new agent threads.
63 ToggleNewThreadMenu,
64 /// Toggles the navigation menu for switching between threads and views.
65 ToggleNavigationMenu,
66 /// Toggles the options menu for agent settings and preferences.
67 ToggleOptionsMenu,
68 /// Deletes the recently opened thread from history.
69 DeleteRecentlyOpenThread,
70 /// Toggles the profile or mode selector for switching between agent profiles.
71 ToggleProfileSelector,
72 /// Cycles through available session modes.
73 CycleModeSelector,
74 /// Removes all added context from the current conversation.
75 RemoveAllContext,
76 /// Expands the message editor to full size.
77 ExpandMessageEditor,
78 /// Opens the conversation history view.
79 OpenHistory,
80 /// Adds a context server to the configuration.
81 AddContextServer,
82 /// Removes the currently selected thread.
83 RemoveSelectedThread,
84 /// Starts a chat conversation with follow-up enabled.
85 ChatWithFollow,
86 /// Cycles to the next inline assist suggestion.
87 CycleNextInlineAssist,
88 /// Cycles to the previous inline assist suggestion.
89 CyclePreviousInlineAssist,
90 /// Moves focus up in the interface.
91 FocusUp,
92 /// Moves focus down in the interface.
93 FocusDown,
94 /// Moves focus left in the interface.
95 FocusLeft,
96 /// Moves focus right in the interface.
97 FocusRight,
98 /// Removes the currently focused context item.
99 RemoveFocusedContext,
100 /// Accepts the suggested context item.
101 AcceptSuggestedContext,
102 /// Opens the active thread as a markdown file.
103 OpenActiveThreadAsMarkdown,
104 /// Opens the agent diff view to review changes.
105 OpenAgentDiff,
106 /// Keeps the current suggestion or change.
107 Keep,
108 /// Rejects the current suggestion or change.
109 Reject,
110 /// Rejects all suggestions or changes.
111 RejectAll,
112 /// Keeps all suggestions or changes.
113 KeepAll,
114 /// Allow this operation only this time.
115 AllowOnce,
116 /// Allow this operation and remember the choice.
117 AllowAlways,
118 /// Reject this operation only this time.
119 RejectOnce,
120 /// Follows the agent's suggestions.
121 Follow,
122 /// Resets the trial upsell notification.
123 ResetTrialUpsell,
124 /// Resets the trial end upsell notification.
125 ResetTrialEndUpsell,
126 /// Continues the current thread.
127 ContinueThread,
128 /// Continues the thread with burn mode enabled.
129 ContinueWithBurnMode,
130 /// Toggles burn mode for faster responses.
131 ToggleBurnMode,
132 ]
133);
134
135/// Creates a new conversation thread, optionally based on an existing thread.
136#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
137#[action(namespace = agent)]
138#[serde(deny_unknown_fields)]
139pub struct NewThread;
140
141/// Creates a new external agent conversation thread.
142#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
143#[action(namespace = agent)]
144#[serde(deny_unknown_fields)]
145pub struct NewExternalAgentThread {
146 /// Which agent to use for the conversation.
147 agent: Option<ExternalAgent>,
148}
149
150#[derive(Clone, PartialEq, Deserialize, JsonSchema, Action)]
151#[action(namespace = agent)]
152#[serde(deny_unknown_fields)]
153pub struct NewNativeAgentThreadFromSummary {
154 from_session_id: agent_client_protocol::SessionId,
155}
156
157// TODO unify this with AgentType
158#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
159#[serde(rename_all = "snake_case")]
160pub enum ExternalAgent {
161 Gemini,
162 ClaudeCode,
163 Codex,
164 NativeAgent,
165 Custom {
166 name: SharedString,
167 command: AgentServerCommand,
168 },
169}
170
171fn placeholder_command() -> AgentServerCommand {
172 AgentServerCommand {
173 path: "/placeholder".into(),
174 args: vec![],
175 env: None,
176 }
177}
178
179impl ExternalAgent {
180 pub fn parse_built_in(server: &dyn agent_servers::AgentServer) -> Option<Self> {
181 match server.telemetry_id() {
182 "gemini-cli" => Some(Self::Gemini),
183 "claude-code" => Some(Self::ClaudeCode),
184 "codex" => Some(Self::Codex),
185 "zed" => Some(Self::NativeAgent),
186 _ => None,
187 }
188 }
189
190 pub fn server(
191 &self,
192 fs: Arc<dyn fs::Fs>,
193 history: Entity<agent::HistoryStore>,
194 ) -> Rc<dyn agent_servers::AgentServer> {
195 match self {
196 Self::Gemini => Rc::new(agent_servers::Gemini),
197 Self::ClaudeCode => Rc::new(agent_servers::ClaudeCode),
198 Self::Codex => Rc::new(agent_servers::Codex),
199 Self::NativeAgent => Rc::new(agent::NativeAgentServer::new(fs, history)),
200 Self::Custom { name, command: _ } => {
201 Rc::new(agent_servers::CustomAgentServer::new(name.clone()))
202 }
203 }
204 }
205}
206
207/// Opens the profile management interface for configuring agent tools and settings.
208#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
209#[action(namespace = agent)]
210#[serde(deny_unknown_fields)]
211pub struct ManageProfiles {
212 #[serde(default)]
213 pub customize_tools: Option<AgentProfileId>,
214}
215
216impl ManageProfiles {
217 pub fn customize_tools(profile_id: AgentProfileId) -> Self {
218 Self {
219 customize_tools: Some(profile_id),
220 }
221 }
222}
223
224#[derive(Clone)]
225pub(crate) enum ModelUsageContext {
226 InlineAssistant,
227}
228
229impl ModelUsageContext {
230 pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
231 match self {
232 Self::InlineAssistant => {
233 LanguageModelRegistry::read_global(cx).inline_assistant_model()
234 }
235 }
236 }
237
238 pub fn language_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
239 self.configured_model(cx)
240 .map(|configured_model| configured_model.model)
241 }
242}
243
244/// Initializes the `agent` crate.
245pub fn init(
246 fs: Arc<dyn Fs>,
247 client: Arc<Client>,
248 prompt_builder: Arc<PromptBuilder>,
249 language_registry: Arc<LanguageRegistry>,
250 is_eval: bool,
251 cx: &mut App,
252) {
253 assistant_text_thread::init(client.clone(), cx);
254 rules_library::init(cx);
255 if !is_eval {
256 // Initializing the language model from the user settings messes with the eval, so we only initialize them when
257 // we're not running inside of the eval.
258 init_language_model_settings(cx);
259 }
260 assistant_slash_command::init(cx);
261 agent_panel::init(cx);
262 context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
263 TextThreadEditor::init(cx);
264
265 register_slash_commands(cx);
266 inline_assistant::init(
267 fs.clone(),
268 prompt_builder.clone(),
269 client.telemetry().clone(),
270 cx,
271 );
272 terminal_inline_assistant::init(fs.clone(), prompt_builder, client.telemetry().clone(), cx);
273 cx.observe_new(move |workspace, window, cx| {
274 ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
275 })
276 .detach();
277 cx.observe_new(ManageProfilesModal::register).detach();
278
279 // Update command palette filter based on AI settings
280 update_command_palette_filter(cx);
281
282 // Watch for settings changes
283 cx.observe_global::<SettingsStore>(|app_cx| {
284 // When settings change, update the command palette filter
285 update_command_palette_filter(app_cx);
286 })
287 .detach();
288}
289
290fn update_command_palette_filter(cx: &mut App) {
291 let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
292 let agent_enabled = AgentSettings::get_global(cx).enabled;
293 let edit_prediction_provider = AllLanguageSettings::get_global(cx)
294 .edit_predictions
295 .provider;
296
297 CommandPaletteFilter::update_global(cx, |filter, _| {
298 use editor::actions::{
299 AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
300 PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
301 };
302 let edit_prediction_actions = [
303 TypeId::of::<AcceptEditPrediction>(),
304 TypeId::of::<AcceptPartialEditPrediction>(),
305 TypeId::of::<ShowEditPrediction>(),
306 TypeId::of::<NextEditPrediction>(),
307 TypeId::of::<PreviousEditPrediction>(),
308 TypeId::of::<ToggleEditPrediction>(),
309 ];
310
311 if disable_ai {
312 filter.hide_namespace("agent");
313 filter.hide_namespace("assistant");
314 filter.hide_namespace("copilot");
315 filter.hide_namespace("supermaven");
316 filter.hide_namespace("zed_predict_onboarding");
317 filter.hide_namespace("edit_prediction");
318
319 filter.hide_action_types(&edit_prediction_actions);
320 filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
321 } else {
322 if agent_enabled {
323 filter.show_namespace("agent");
324 } else {
325 filter.hide_namespace("agent");
326 }
327
328 filter.show_namespace("assistant");
329
330 match edit_prediction_provider {
331 EditPredictionProvider::None => {
332 filter.hide_namespace("edit_prediction");
333 filter.hide_namespace("copilot");
334 filter.hide_namespace("supermaven");
335 filter.hide_action_types(&edit_prediction_actions);
336 }
337 EditPredictionProvider::Copilot => {
338 filter.show_namespace("edit_prediction");
339 filter.show_namespace("copilot");
340 filter.hide_namespace("supermaven");
341 filter.show_action_types(edit_prediction_actions.iter());
342 }
343 EditPredictionProvider::Supermaven => {
344 filter.show_namespace("edit_prediction");
345 filter.hide_namespace("copilot");
346 filter.show_namespace("supermaven");
347 filter.show_action_types(edit_prediction_actions.iter());
348 }
349 EditPredictionProvider::Zed | EditPredictionProvider::Codestral => {
350 filter.show_namespace("edit_prediction");
351 filter.hide_namespace("copilot");
352 filter.hide_namespace("supermaven");
353 filter.show_action_types(edit_prediction_actions.iter());
354 }
355 }
356
357 filter.show_namespace("zed_predict_onboarding");
358 filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
359 }
360 });
361}
362
363fn init_language_model_settings(cx: &mut App) {
364 update_active_language_model_from_settings(cx);
365
366 cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
367 .detach();
368 cx.subscribe(
369 &LanguageModelRegistry::global(cx),
370 |_, event: &language_model::Event, cx| match event {
371 language_model::Event::ProviderStateChanged(_)
372 | language_model::Event::AddedProvider(_)
373 | language_model::Event::RemovedProvider(_) => {
374 update_active_language_model_from_settings(cx);
375 }
376 _ => {}
377 },
378 )
379 .detach();
380}
381
382fn update_active_language_model_from_settings(cx: &mut App) {
383 let settings = AgentSettings::get_global(cx);
384
385 fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
386 language_model::SelectedModel {
387 provider: LanguageModelProviderId::from(selection.provider.0.clone()),
388 model: LanguageModelId::from(selection.model.clone()),
389 }
390 }
391
392 let default = settings.default_model.as_ref().map(to_selected_model);
393 let inline_assistant = settings
394 .inline_assistant_model
395 .as_ref()
396 .map(to_selected_model);
397 let commit_message = settings
398 .commit_message_model
399 .as_ref()
400 .map(to_selected_model);
401 let thread_summary = settings
402 .thread_summary_model
403 .as_ref()
404 .map(to_selected_model);
405 let inline_alternatives = settings
406 .inline_alternatives
407 .iter()
408 .map(to_selected_model)
409 .collect::<Vec<_>>();
410
411 LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
412 registry.select_default_model(default.as_ref(), cx);
413 registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
414 registry.select_commit_message_model(commit_message.as_ref(), cx);
415 registry.select_thread_summary_model(thread_summary.as_ref(), cx);
416 registry.select_inline_alternative_models(inline_alternatives, cx);
417 });
418}
419
420fn register_slash_commands(cx: &mut App) {
421 let slash_command_registry = SlashCommandRegistry::global(cx);
422
423 slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
424 slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
425 slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
426 slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
427 slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
428 slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
429 slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
430 slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
431 slash_command_registry
432 .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
433 slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
434
435 cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
436 move |is_enabled, _cx| {
437 if is_enabled {
438 slash_command_registry.register_command(
439 assistant_slash_commands::StreamingExampleSlashCommand,
440 false,
441 );
442 }
443 }
444 })
445 .detach();
446}
447
448#[cfg(test)]
449mod tests {
450 use super::*;
451 use agent_settings::{AgentProfileId, AgentSettings, CompletionMode};
452 use command_palette_hooks::CommandPaletteFilter;
453 use editor::actions::AcceptEditPrediction;
454 use gpui::{BorrowAppContext, TestAppContext, px};
455 use project::DisableAiSettings;
456 use settings::{
457 DefaultAgentView, DockPosition, NotifyWhenAgentWaiting, Settings, SettingsStore,
458 };
459
460 #[gpui::test]
461 fn test_agent_command_palette_visibility(cx: &mut TestAppContext) {
462 // Init settings
463 cx.update(|cx| {
464 let store = SettingsStore::test(cx);
465 cx.set_global(store);
466 command_palette_hooks::init(cx);
467 AgentSettings::register(cx);
468 DisableAiSettings::register(cx);
469 AllLanguageSettings::register(cx);
470 });
471
472 let agent_settings = AgentSettings {
473 enabled: true,
474 button: true,
475 dock: DockPosition::Right,
476 default_width: px(300.),
477 default_height: px(600.),
478 default_model: None,
479 inline_assistant_model: None,
480 commit_message_model: None,
481 thread_summary_model: None,
482 inline_alternatives: vec![],
483 default_profile: AgentProfileId::default(),
484 default_view: DefaultAgentView::Thread,
485 profiles: Default::default(),
486 always_allow_tool_actions: false,
487 notify_when_agent_waiting: NotifyWhenAgentWaiting::default(),
488 play_sound_when_agent_done: false,
489 single_file_review: false,
490 model_parameters: vec![],
491 preferred_completion_mode: CompletionMode::Normal,
492 enable_feedback: false,
493 expand_edit_card: true,
494 expand_terminal_card: true,
495 use_modifier_to_send: true,
496 message_editor_min_lines: 1,
497 };
498
499 cx.update(|cx| {
500 AgentSettings::override_global(agent_settings.clone(), cx);
501 DisableAiSettings::override_global(DisableAiSettings { disable_ai: false }, cx);
502
503 // Initial update
504 update_command_palette_filter(cx);
505 });
506
507 // Assert visible
508 cx.update(|cx| {
509 let filter = CommandPaletteFilter::try_global(cx).unwrap();
510 assert!(
511 !filter.is_hidden(&NewThread),
512 "NewThread should be visible by default"
513 );
514 });
515
516 // Disable agent
517 cx.update(|cx| {
518 let mut new_settings = agent_settings.clone();
519 new_settings.enabled = false;
520 AgentSettings::override_global(new_settings, cx);
521
522 // Trigger update
523 update_command_palette_filter(cx);
524 });
525
526 // Assert hidden
527 cx.update(|cx| {
528 let filter = CommandPaletteFilter::try_global(cx).unwrap();
529 assert!(
530 filter.is_hidden(&NewThread),
531 "NewThread should be hidden when agent is disabled"
532 );
533 });
534
535 // Test EditPredictionProvider
536 // Enable EditPredictionProvider::Copilot
537 cx.update(|cx| {
538 cx.update_global::<SettingsStore, _>(|store, cx| {
539 store.update_user_settings(cx, |s| {
540 s.project
541 .all_languages
542 .features
543 .get_or_insert(Default::default())
544 .edit_prediction_provider = Some(EditPredictionProvider::Copilot);
545 });
546 });
547 update_command_palette_filter(cx);
548 });
549
550 cx.update(|cx| {
551 let filter = CommandPaletteFilter::try_global(cx).unwrap();
552 assert!(
553 !filter.is_hidden(&AcceptEditPrediction),
554 "EditPrediction should be visible when provider is Copilot"
555 );
556 });
557
558 // Disable EditPredictionProvider (None)
559 cx.update(|cx| {
560 cx.update_global::<SettingsStore, _>(|store, cx| {
561 store.update_user_settings(cx, |s| {
562 s.project
563 .all_languages
564 .features
565 .get_or_insert(Default::default())
566 .edit_prediction_provider = Some(EditPredictionProvider::None);
567 });
568 });
569 update_command_palette_filter(cx);
570 });
571
572 cx.update(|cx| {
573 let filter = CommandPaletteFilter::try_global(cx).unwrap();
574 assert!(
575 filter.is_hidden(&AcceptEditPrediction),
576 "EditPrediction should be hidden when provider is None"
577 );
578 });
579 }
580}