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