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_settings::{AgentProfileId, AgentSettings, LanguageModelSelection};
32use assistant_slash_command::SlashCommandRegistry;
33use client::Client;
34use command_palette_hooks::CommandPaletteFilter;
35use feature_flags::FeatureFlagAppExt as _;
36use fs::Fs;
37use gpui::{Action, App, Entity, SharedString, actions};
38use language::LanguageRegistry;
39use language_model::{
40 ConfiguredModel, LanguageModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
41};
42use project::DisableAiSettings;
43use project::agent_server_store::AgentServerCommand;
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// TODO unify this with AgentType
164#[derive(Default, Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
165#[serde(rename_all = "snake_case")]
166enum ExternalAgent {
167 #[default]
168 Gemini,
169 ClaudeCode,
170 NativeAgent,
171 Custom {
172 name: SharedString,
173 command: AgentServerCommand,
174 },
175}
176
177fn placeholder_command() -> AgentServerCommand {
178 AgentServerCommand {
179 path: "/placeholder".into(),
180 args: vec![],
181 env: None,
182 }
183}
184
185impl ExternalAgent {
186 fn name(&self) -> &'static str {
187 match self {
188 Self::NativeAgent => "zed",
189 Self::Gemini => "gemini-cli",
190 Self::ClaudeCode => "claude-code",
191 Self::Custom { .. } => "custom",
192 }
193 }
194
195 pub fn server(
196 &self,
197 fs: Arc<dyn fs::Fs>,
198 history: Entity<agent2::HistoryStore>,
199 ) -> Rc<dyn agent_servers::AgentServer> {
200 match self {
201 Self::Gemini => Rc::new(agent_servers::Gemini),
202 Self::ClaudeCode => Rc::new(agent_servers::ClaudeCode),
203 Self::NativeAgent => Rc::new(agent2::NativeAgentServer::new(fs, history)),
204 Self::Custom { name, command: _ } => {
205 Rc::new(agent_servers::CustomAgentServer::new(name.clone()))
206 }
207 }
208 }
209}
210
211/// Opens the profile management interface for configuring agent tools and settings.
212#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
213#[action(namespace = agent)]
214#[serde(deny_unknown_fields)]
215pub struct ManageProfiles {
216 #[serde(default)]
217 pub customize_tools: Option<AgentProfileId>,
218}
219
220impl ManageProfiles {
221 pub fn customize_tools(profile_id: AgentProfileId) -> Self {
222 Self {
223 customize_tools: Some(profile_id),
224 }
225 }
226}
227
228#[derive(Clone)]
229pub(crate) enum ModelUsageContext {
230 Thread(Entity<Thread>),
231 InlineAssistant,
232}
233
234impl ModelUsageContext {
235 pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
236 match self {
237 Self::Thread(thread) => thread.read(cx).configured_model(),
238 Self::InlineAssistant => {
239 LanguageModelRegistry::read_global(cx).inline_assistant_model()
240 }
241 }
242 }
243
244 pub fn language_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
245 self.configured_model(cx)
246 .map(|configured_model| configured_model.model)
247 }
248}
249
250/// Initializes the `agent` crate.
251pub fn init(
252 fs: Arc<dyn Fs>,
253 client: Arc<Client>,
254 prompt_builder: Arc<PromptBuilder>,
255 language_registry: Arc<LanguageRegistry>,
256 is_eval: bool,
257 cx: &mut App,
258) {
259 AgentSettings::register(cx);
260 SlashCommandSettings::register(cx);
261
262 assistant_context::init(client.clone(), cx);
263 rules_library::init(cx);
264 if !is_eval {
265 // Initializing the language model from the user settings messes with the eval, so we only initialize them when
266 // we're not running inside of the eval.
267 init_language_model_settings(cx);
268 }
269 assistant_slash_command::init(cx);
270 agent::init(cx);
271 agent_panel::init(cx);
272 context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
273 TextThreadEditor::init(cx);
274
275 register_slash_commands(cx);
276 inline_assistant::init(
277 fs.clone(),
278 prompt_builder.clone(),
279 client.telemetry().clone(),
280 cx,
281 );
282 terminal_inline_assistant::init(fs.clone(), prompt_builder, client.telemetry().clone(), cx);
283 cx.observe_new(move |workspace, window, cx| {
284 ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
285 })
286 .detach();
287 cx.observe_new(ManageProfilesModal::register).detach();
288
289 // Update command palette filter based on AI settings
290 update_command_palette_filter(cx);
291
292 // Watch for settings changes
293 cx.observe_global::<SettingsStore>(|app_cx| {
294 // When settings change, update the command palette filter
295 update_command_palette_filter(app_cx);
296 })
297 .detach();
298}
299
300fn update_command_palette_filter(cx: &mut App) {
301 let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
302 CommandPaletteFilter::update_global(cx, |filter, _| {
303 if disable_ai {
304 filter.hide_namespace("agent");
305 filter.hide_namespace("assistant");
306 filter.hide_namespace("copilot");
307 filter.hide_namespace("supermaven");
308 filter.hide_namespace("zed_predict_onboarding");
309 filter.hide_namespace("edit_prediction");
310
311 use editor::actions::{
312 AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
313 PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
314 };
315 let edit_prediction_actions = [
316 TypeId::of::<AcceptEditPrediction>(),
317 TypeId::of::<AcceptPartialEditPrediction>(),
318 TypeId::of::<ShowEditPrediction>(),
319 TypeId::of::<NextEditPrediction>(),
320 TypeId::of::<PreviousEditPrediction>(),
321 TypeId::of::<ToggleEditPrediction>(),
322 ];
323 filter.hide_action_types(&edit_prediction_actions);
324 filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
325 } else {
326 filter.show_namespace("agent");
327 filter.show_namespace("assistant");
328 filter.show_namespace("copilot");
329 filter.show_namespace("zed_predict_onboarding");
330
331 filter.show_namespace("edit_prediction");
332
333 use editor::actions::{
334 AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
335 PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
336 };
337 let edit_prediction_actions = [
338 TypeId::of::<AcceptEditPrediction>(),
339 TypeId::of::<AcceptPartialEditPrediction>(),
340 TypeId::of::<ShowEditPrediction>(),
341 TypeId::of::<NextEditPrediction>(),
342 TypeId::of::<PreviousEditPrediction>(),
343 TypeId::of::<ToggleEditPrediction>(),
344 ];
345 filter.show_action_types(edit_prediction_actions.iter());
346
347 filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
348 }
349 });
350}
351
352fn init_language_model_settings(cx: &mut App) {
353 update_active_language_model_from_settings(cx);
354
355 cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
356 .detach();
357 cx.subscribe(
358 &LanguageModelRegistry::global(cx),
359 |_, event: &language_model::Event, cx| match event {
360 language_model::Event::ProviderStateChanged(_)
361 | language_model::Event::AddedProvider(_)
362 | language_model::Event::RemovedProvider(_) => {
363 update_active_language_model_from_settings(cx);
364 }
365 _ => {}
366 },
367 )
368 .detach();
369}
370
371fn update_active_language_model_from_settings(cx: &mut App) {
372 let settings = AgentSettings::get_global(cx);
373
374 fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
375 language_model::SelectedModel {
376 provider: LanguageModelProviderId::from(selection.provider.0.clone()),
377 model: LanguageModelId::from(selection.model.clone()),
378 }
379 }
380
381 let default = settings.default_model.as_ref().map(to_selected_model);
382 let inline_assistant = settings
383 .inline_assistant_model
384 .as_ref()
385 .map(to_selected_model);
386 let commit_message = settings
387 .commit_message_model
388 .as_ref()
389 .map(to_selected_model);
390 let thread_summary = settings
391 .thread_summary_model
392 .as_ref()
393 .map(to_selected_model);
394 let inline_alternatives = settings
395 .inline_alternatives
396 .iter()
397 .map(to_selected_model)
398 .collect::<Vec<_>>();
399
400 LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
401 registry.select_default_model(default.as_ref(), cx);
402 registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
403 registry.select_commit_message_model(commit_message.as_ref(), cx);
404 registry.select_thread_summary_model(thread_summary.as_ref(), cx);
405 registry.select_inline_alternative_models(inline_alternatives, cx);
406 });
407}
408
409fn register_slash_commands(cx: &mut App) {
410 let slash_command_registry = SlashCommandRegistry::global(cx);
411
412 slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
413 slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
414 slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
415 slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
416 slash_command_registry
417 .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
418 slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
419 slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
420 slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
421 slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
422 slash_command_registry
423 .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
424 slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
425
426 cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
427 move |is_enabled, _cx| {
428 if is_enabled {
429 slash_command_registry.register_command(
430 assistant_slash_commands::StreamingExampleSlashCommand,
431 false,
432 );
433 }
434 }
435 })
436 .detach();
437
438 update_slash_commands_from_settings(cx);
439 cx.observe_global::<SettingsStore>(update_slash_commands_from_settings)
440 .detach();
441}
442
443fn update_slash_commands_from_settings(cx: &mut App) {
444 let slash_command_registry = SlashCommandRegistry::global(cx);
445 let settings = SlashCommandSettings::get_global(cx);
446
447 if settings.cargo_workspace.enabled {
448 slash_command_registry
449 .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
450 } else {
451 slash_command_registry
452 .unregister_command(assistant_slash_commands::CargoWorkspaceSlashCommand);
453 }
454}