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