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