1mod acp;
2mod active_thread;
3mod agent_configuration;
4mod agent_diff;
5mod agent_model_selector;
6mod agent_panel;
7mod buffer_codegen;
8mod burn_mode_tooltip;
9mod context_picker;
10mod context_server_configuration;
11mod context_strip;
12mod debug;
13mod inline_assistant;
14mod inline_prompt_editor;
15mod language_model_selector;
16mod message_editor;
17mod profile_selector;
18mod slash_command;
19mod slash_command_picker;
20mod slash_command_settings;
21mod terminal_codegen;
22mod terminal_inline_assistant;
23mod text_thread_editor;
24mod thread_history;
25mod tool_compatibility;
26mod ui;
27
28use std::rc::Rc;
29use std::sync::Arc;
30
31use agent::{Thread, ThreadId};
32use agent_settings::{AgentProfileId, AgentSettings, LanguageModelSelection};
33use assistant_slash_command::SlashCommandRegistry;
34use client::{Client, DisableAiSettings};
35use command_palette_hooks::CommandPaletteFilter;
36use feature_flags::FeatureFlagAppExt as _;
37use fs::Fs;
38use gpui::{Action, App, Entity, actions};
39use language::LanguageRegistry;
40use language_model::{
41 ConfiguredModel, LanguageModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
42};
43use prompt_store::PromptBuilder;
44use schemars::JsonSchema;
45use serde::{Deserialize, Serialize};
46use settings::{Settings as _, SettingsStore};
47use std::any::TypeId;
48
49pub use crate::active_thread::ActiveThread;
50use crate::agent_configuration::{ConfigureContextServerModal, ManageProfilesModal};
51pub use crate::agent_panel::{AgentPanel, ConcreteAssistantPanelDelegate};
52pub use crate::inline_assistant::InlineAssistant;
53use crate::slash_command_settings::SlashCommandSettings;
54pub use agent_diff::{AgentDiffPane, AgentDiffToolbar};
55pub use text_thread_editor::{AgentPanelDelegate, TextThreadEditor};
56pub use ui::preview::{all_agent_previews, get_agent_preview};
57use zed_actions;
58
59actions!(
60 agent,
61 [
62 /// Creates a new text-based conversation thread.
63 NewTextThread,
64 /// Toggles the context picker interface for adding files, symbols, or other context.
65 ToggleContextPicker,
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 /// Deletes the recently opened thread from history.
71 DeleteRecentlyOpenThread,
72 /// Toggles the profile selector for switching between agent profiles.
73 ToggleProfileSelector,
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 /// Follows the agent's suggestions.
115 Follow,
116 /// Resets the trial upsell notification.
117 ResetTrialUpsell,
118 /// Resets the trial end upsell notification.
119 ResetTrialEndUpsell,
120 /// Continues the current thread.
121 ContinueThread,
122 /// Continues the thread with burn mode enabled.
123 ContinueWithBurnMode,
124 /// Toggles burn mode for faster responses.
125 ToggleBurnMode,
126 ]
127);
128
129/// Creates a new conversation thread, optionally based on an existing thread.
130#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
131#[action(namespace = agent)]
132#[serde(deny_unknown_fields)]
133pub struct NewThread {
134 #[serde(default)]
135 from_thread_id: Option<ThreadId>,
136}
137
138/// Creates a new external agent conversation thread.
139#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
140#[action(namespace = agent)]
141#[serde(deny_unknown_fields)]
142pub struct NewExternalAgentThread {
143 /// Which agent to use for the conversation.
144 agent: Option<ExternalAgent>,
145}
146
147#[derive(Default, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
148#[serde(rename_all = "snake_case")]
149enum ExternalAgent {
150 #[default]
151 Gemini,
152 ClaudeCode,
153}
154
155impl ExternalAgent {
156 pub fn server(&self) -> Rc<dyn agent_servers::AgentServer> {
157 match self {
158 ExternalAgent::Gemini => Rc::new(agent_servers::Gemini),
159 ExternalAgent::ClaudeCode => Rc::new(agent_servers::ClaudeCode),
160 }
161 }
162}
163
164/// Opens the profile management interface for configuring agent tools and settings.
165#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
166#[action(namespace = agent)]
167#[serde(deny_unknown_fields)]
168pub struct ManageProfiles {
169 #[serde(default)]
170 pub customize_tools: Option<AgentProfileId>,
171}
172
173impl ManageProfiles {
174 pub fn customize_tools(profile_id: AgentProfileId) -> Self {
175 Self {
176 customize_tools: Some(profile_id),
177 }
178 }
179}
180
181#[derive(Clone)]
182pub(crate) enum ModelUsageContext {
183 Thread(Entity<Thread>),
184 InlineAssistant,
185}
186
187impl ModelUsageContext {
188 pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
189 match self {
190 Self::Thread(thread) => thread.read(cx).configured_model(),
191 Self::InlineAssistant => {
192 LanguageModelRegistry::read_global(cx).inline_assistant_model()
193 }
194 }
195 }
196
197 pub fn language_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
198 self.configured_model(cx)
199 .map(|configured_model| configured_model.model)
200 }
201}
202
203/// Initializes the `agent` crate.
204pub fn init(
205 fs: Arc<dyn Fs>,
206 client: Arc<Client>,
207 prompt_builder: Arc<PromptBuilder>,
208 language_registry: Arc<LanguageRegistry>,
209 is_eval: bool,
210 cx: &mut App,
211) {
212 AgentSettings::register(cx);
213 SlashCommandSettings::register(cx);
214
215 assistant_context::init(client.clone(), cx);
216 rules_library::init(cx);
217 if !is_eval {
218 // Initializing the language model from the user settings messes with the eval, so we only initialize them when
219 // we're not running inside of the eval.
220 init_language_model_settings(cx);
221 }
222 assistant_slash_command::init(cx);
223 agent::init(cx);
224 agent_panel::init(cx);
225 context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
226 TextThreadEditor::init(cx);
227
228 register_slash_commands(cx);
229 inline_assistant::init(
230 fs.clone(),
231 prompt_builder.clone(),
232 client.telemetry().clone(),
233 cx,
234 );
235 terminal_inline_assistant::init(
236 fs.clone(),
237 prompt_builder.clone(),
238 client.telemetry().clone(),
239 cx,
240 );
241 indexed_docs::init(cx);
242 cx.observe_new(move |workspace, window, cx| {
243 ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
244 })
245 .detach();
246 cx.observe_new(ManageProfilesModal::register).detach();
247
248 // Update command palette filter based on AI settings
249 update_command_palette_filter(cx);
250
251 // Watch for settings changes
252 cx.observe_global::<SettingsStore>(|app_cx| {
253 // When settings change, update the command palette filter
254 update_command_palette_filter(app_cx);
255 })
256 .detach();
257}
258
259fn update_command_palette_filter(cx: &mut App) {
260 let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
261 CommandPaletteFilter::update_global(cx, |filter, _| {
262 if disable_ai {
263 filter.hide_namespace("agent");
264 filter.hide_namespace("assistant");
265 filter.hide_namespace("copilot");
266 filter.hide_namespace("supermaven");
267 filter.hide_namespace("zed_predict_onboarding");
268 filter.hide_namespace("edit_prediction");
269
270 use editor::actions::{
271 AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
272 PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
273 };
274 let edit_prediction_actions = [
275 TypeId::of::<AcceptEditPrediction>(),
276 TypeId::of::<AcceptPartialEditPrediction>(),
277 TypeId::of::<ShowEditPrediction>(),
278 TypeId::of::<NextEditPrediction>(),
279 TypeId::of::<PreviousEditPrediction>(),
280 TypeId::of::<ToggleEditPrediction>(),
281 ];
282 filter.hide_action_types(&edit_prediction_actions);
283 filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
284 } else {
285 filter.show_namespace("agent");
286 filter.show_namespace("assistant");
287 filter.show_namespace("copilot");
288 filter.show_namespace("zed_predict_onboarding");
289
290 filter.show_namespace("edit_prediction");
291
292 use editor::actions::{
293 AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
294 PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
295 };
296 let edit_prediction_actions = [
297 TypeId::of::<AcceptEditPrediction>(),
298 TypeId::of::<AcceptPartialEditPrediction>(),
299 TypeId::of::<ShowEditPrediction>(),
300 TypeId::of::<NextEditPrediction>(),
301 TypeId::of::<PreviousEditPrediction>(),
302 TypeId::of::<ToggleEditPrediction>(),
303 ];
304 filter.show_action_types(edit_prediction_actions.iter());
305
306 filter
307 .show_action_types([TypeId::of::<zed_actions::OpenZedPredictOnboarding>()].iter());
308 }
309 });
310}
311
312fn init_language_model_settings(cx: &mut App) {
313 update_active_language_model_from_settings(cx);
314
315 cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
316 .detach();
317 cx.subscribe(
318 &LanguageModelRegistry::global(cx),
319 |_, event: &language_model::Event, cx| match event {
320 language_model::Event::ProviderStateChanged
321 | language_model::Event::AddedProvider(_)
322 | language_model::Event::RemovedProvider(_) => {
323 update_active_language_model_from_settings(cx);
324 }
325 _ => {}
326 },
327 )
328 .detach();
329}
330
331fn update_active_language_model_from_settings(cx: &mut App) {
332 let settings = AgentSettings::get_global(cx);
333
334 fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
335 language_model::SelectedModel {
336 provider: LanguageModelProviderId::from(selection.provider.0.clone()),
337 model: LanguageModelId::from(selection.model.clone()),
338 }
339 }
340
341 let default = settings.default_model.as_ref().map(to_selected_model);
342 let inline_assistant = settings
343 .inline_assistant_model
344 .as_ref()
345 .map(to_selected_model);
346 let commit_message = settings
347 .commit_message_model
348 .as_ref()
349 .map(to_selected_model);
350 let thread_summary = settings
351 .thread_summary_model
352 .as_ref()
353 .map(to_selected_model);
354 let inline_alternatives = settings
355 .inline_alternatives
356 .iter()
357 .map(to_selected_model)
358 .collect::<Vec<_>>();
359
360 LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
361 registry.select_default_model(default.as_ref(), cx);
362 registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
363 registry.select_commit_message_model(commit_message.as_ref(), cx);
364 registry.select_thread_summary_model(thread_summary.as_ref(), cx);
365 registry.select_inline_alternative_models(inline_alternatives, cx);
366 });
367}
368
369fn register_slash_commands(cx: &mut App) {
370 let slash_command_registry = SlashCommandRegistry::global(cx);
371
372 slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
373 slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
374 slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
375 slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
376 slash_command_registry
377 .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
378 slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
379 slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
380 slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
381 slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
382 slash_command_registry
383 .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
384 slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
385
386 cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
387 let slash_command_registry = slash_command_registry.clone();
388 move |is_enabled, _cx| {
389 if is_enabled {
390 slash_command_registry.register_command(
391 assistant_slash_commands::StreamingExampleSlashCommand,
392 false,
393 );
394 }
395 }
396 })
397 .detach();
398
399 update_slash_commands_from_settings(cx);
400 cx.observe_global::<SettingsStore>(update_slash_commands_from_settings)
401 .detach();
402}
403
404fn update_slash_commands_from_settings(cx: &mut App) {
405 let slash_command_registry = SlashCommandRegistry::global(cx);
406 let settings = SlashCommandSettings::get_global(cx);
407
408 if settings.docs.enabled {
409 slash_command_registry.register_command(assistant_slash_commands::DocsSlashCommand, true);
410 } else {
411 slash_command_registry.unregister_command(assistant_slash_commands::DocsSlashCommand);
412 }
413
414 if settings.cargo_workspace.enabled {
415 slash_command_registry
416 .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
417 } else {
418 slash_command_registry
419 .unregister_command(assistant_slash_commands::CargoWorkspaceSlashCommand);
420 }
421}