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("zed_predict_onboarding");
266 filter.hide_namespace("edit_prediction");
267
268 use editor::actions::{
269 AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
270 PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
271 };
272 let edit_prediction_actions = [
273 TypeId::of::<AcceptEditPrediction>(),
274 TypeId::of::<AcceptPartialEditPrediction>(),
275 TypeId::of::<ShowEditPrediction>(),
276 TypeId::of::<NextEditPrediction>(),
277 TypeId::of::<PreviousEditPrediction>(),
278 TypeId::of::<ToggleEditPrediction>(),
279 ];
280 filter.hide_action_types(&edit_prediction_actions);
281 filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
282 } else {
283 filter.show_namespace("agent");
284 filter.show_namespace("assistant");
285 filter.show_namespace("zed_predict_onboarding");
286
287 filter.show_namespace("edit_prediction");
288
289 use editor::actions::{
290 AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
291 PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
292 };
293 let edit_prediction_actions = [
294 TypeId::of::<AcceptEditPrediction>(),
295 TypeId::of::<AcceptPartialEditPrediction>(),
296 TypeId::of::<ShowEditPrediction>(),
297 TypeId::of::<NextEditPrediction>(),
298 TypeId::of::<PreviousEditPrediction>(),
299 TypeId::of::<ToggleEditPrediction>(),
300 ];
301 filter.show_action_types(edit_prediction_actions.iter());
302
303 filter
304 .show_action_types([TypeId::of::<zed_actions::OpenZedPredictOnboarding>()].iter());
305 }
306 });
307}
308
309fn init_language_model_settings(cx: &mut App) {
310 update_active_language_model_from_settings(cx);
311
312 cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
313 .detach();
314 cx.subscribe(
315 &LanguageModelRegistry::global(cx),
316 |_, event: &language_model::Event, cx| match event {
317 language_model::Event::ProviderStateChanged
318 | language_model::Event::AddedProvider(_)
319 | language_model::Event::RemovedProvider(_) => {
320 update_active_language_model_from_settings(cx);
321 }
322 _ => {}
323 },
324 )
325 .detach();
326}
327
328fn update_active_language_model_from_settings(cx: &mut App) {
329 let settings = AgentSettings::get_global(cx);
330
331 fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
332 language_model::SelectedModel {
333 provider: LanguageModelProviderId::from(selection.provider.0.clone()),
334 model: LanguageModelId::from(selection.model.clone()),
335 }
336 }
337
338 let default = settings.default_model.as_ref().map(to_selected_model);
339 let inline_assistant = settings
340 .inline_assistant_model
341 .as_ref()
342 .map(to_selected_model);
343 let commit_message = settings
344 .commit_message_model
345 .as_ref()
346 .map(to_selected_model);
347 let thread_summary = settings
348 .thread_summary_model
349 .as_ref()
350 .map(to_selected_model);
351 let inline_alternatives = settings
352 .inline_alternatives
353 .iter()
354 .map(to_selected_model)
355 .collect::<Vec<_>>();
356
357 LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
358 registry.select_default_model(default.as_ref(), cx);
359 registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
360 registry.select_commit_message_model(commit_message.as_ref(), cx);
361 registry.select_thread_summary_model(thread_summary.as_ref(), cx);
362 registry.select_inline_alternative_models(inline_alternatives, cx);
363 });
364}
365
366fn register_slash_commands(cx: &mut App) {
367 let slash_command_registry = SlashCommandRegistry::global(cx);
368
369 slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
370 slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
371 slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
372 slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
373 slash_command_registry
374 .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
375 slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
376 slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
377 slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
378 slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
379 slash_command_registry
380 .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
381 slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
382
383 cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
384 let slash_command_registry = slash_command_registry.clone();
385 move |is_enabled, _cx| {
386 if is_enabled {
387 slash_command_registry.register_command(
388 assistant_slash_commands::StreamingExampleSlashCommand,
389 false,
390 );
391 }
392 }
393 })
394 .detach();
395
396 update_slash_commands_from_settings(cx);
397 cx.observe_global::<SettingsStore>(update_slash_commands_from_settings)
398 .detach();
399}
400
401fn update_slash_commands_from_settings(cx: &mut App) {
402 let slash_command_registry = SlashCommandRegistry::global(cx);
403 let settings = SlashCommandSettings::get_global(cx);
404
405 if settings.docs.enabled {
406 slash_command_registry.register_command(assistant_slash_commands::DocsSlashCommand, true);
407 } else {
408 slash_command_registry.unregister_command(assistant_slash_commands::DocsSlashCommand);
409 }
410
411 if settings.cargo_workspace.enabled {
412 slash_command_registry
413 .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
414 } else {
415 slash_command_registry
416 .unregister_command(assistant_slash_commands::CargoWorkspaceSlashCommand);
417 }
418}