1mod acp;
2mod agent_configuration;
3mod agent_diff;
4mod agent_model_selector;
5mod agent_panel;
6mod buffer_codegen;
7mod context_picker;
8mod context_server_configuration;
9mod context_strip;
10mod inline_assistant;
11mod inline_prompt_editor;
12mod language_model_selector;
13mod message_editor;
14mod profile_selector;
15mod slash_command;
16mod slash_command_picker;
17mod terminal_codegen;
18mod terminal_inline_assistant;
19mod text_thread_editor;
20mod ui;
21
22use std::rc::Rc;
23use std::sync::Arc;
24
25use agent::ThreadId;
26use agent_settings::{AgentProfileId, AgentSettings};
27use assistant_slash_command::SlashCommandRegistry;
28use client::Client;
29use command_palette_hooks::CommandPaletteFilter;
30use feature_flags::FeatureFlagAppExt as _;
31use fs::Fs;
32use gpui::{Action, App, Entity, SharedString, actions};
33use language::LanguageRegistry;
34use language_model::{
35 ConfiguredModel, LanguageModel, LanguageModelId, LanguageModelProviderId, LanguageModelRegistry,
36};
37use project::DisableAiSettings;
38use project::agent_server_store::AgentServerCommand;
39use prompt_store::PromptBuilder;
40use schemars::JsonSchema;
41use serde::{Deserialize, Serialize};
42use settings::{LanguageModelSelection, Settings as _, SettingsStore};
43use std::any::TypeId;
44
45use crate::agent_configuration::{ConfigureContextServerModal, ManageProfilesModal};
46pub use crate::agent_panel::{AgentPanel, ConcreteAssistantPanelDelegate};
47pub use crate::inline_assistant::InlineAssistant;
48pub use agent_diff::{AgentDiffPane, AgentDiffToolbar};
49pub use text_thread_editor::{AgentPanelDelegate, TextThreadEditor};
50use zed_actions;
51
52actions!(
53 agent,
54 [
55 /// Creates a new text-based conversation thread.
56 NewTextThread,
57 /// Toggles the context picker interface for adding files, symbols, or other context.
58 ToggleContextPicker,
59 /// Toggles the menu to create new agent threads.
60 ToggleNewThreadMenu,
61 /// Toggles the navigation menu for switching between threads and views.
62 ToggleNavigationMenu,
63 /// Toggles the options menu for agent settings and preferences.
64 ToggleOptionsMenu,
65 /// Deletes the recently opened thread from history.
66 DeleteRecentlyOpenThread,
67 /// Toggles the profile or mode selector for switching between agent profiles.
68 ToggleProfileSelector,
69 /// Cycles through available session modes.
70 CycleModeSelector,
71 /// Removes all added context from the current conversation.
72 RemoveAllContext,
73 /// Expands the message editor to full size.
74 ExpandMessageEditor,
75 /// Opens the conversation history view.
76 OpenHistory,
77 /// Adds a context server to the configuration.
78 AddContextServer,
79 /// Removes the currently selected thread.
80 RemoveSelectedThread,
81 /// Starts a chat conversation with follow-up enabled.
82 ChatWithFollow,
83 /// Cycles to the next inline assist suggestion.
84 CycleNextInlineAssist,
85 /// Cycles to the previous inline assist suggestion.
86 CyclePreviousInlineAssist,
87 /// Moves focus up in the interface.
88 FocusUp,
89 /// Moves focus down in the interface.
90 FocusDown,
91 /// Moves focus left in the interface.
92 FocusLeft,
93 /// Moves focus right in the interface.
94 FocusRight,
95 /// Removes the currently focused context item.
96 RemoveFocusedContext,
97 /// Accepts the suggested context item.
98 AcceptSuggestedContext,
99 /// Opens the active thread as a markdown file.
100 OpenActiveThreadAsMarkdown,
101 /// Opens the agent diff view to review changes.
102 OpenAgentDiff,
103 /// Keeps the current suggestion or change.
104 Keep,
105 /// Rejects the current suggestion or change.
106 Reject,
107 /// Rejects all suggestions or changes.
108 RejectAll,
109 /// Keeps all suggestions or changes.
110 KeepAll,
111 /// Allow this operation only this time.
112 AllowOnce,
113 /// Allow this operation and remember the choice.
114 AllowAlways,
115 /// Reject this operation only this time.
116 RejectOnce,
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 InlineAssistant,
231}
232
233impl ModelUsageContext {
234 pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
235 match self {
236 Self::InlineAssistant => {
237 LanguageModelRegistry::read_global(cx).inline_assistant_model()
238 }
239 }
240 }
241
242 pub fn language_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
243 self.configured_model(cx)
244 .map(|configured_model| configured_model.model)
245 }
246}
247
248/// Initializes the `agent` crate.
249pub fn init(
250 fs: Arc<dyn Fs>,
251 client: Arc<Client>,
252 prompt_builder: Arc<PromptBuilder>,
253 language_registry: Arc<LanguageRegistry>,
254 is_eval: bool,
255 cx: &mut App,
256) {
257 AgentSettings::register(cx);
258
259 assistant_context::init(client.clone(), cx);
260 rules_library::init(cx);
261 if !is_eval {
262 // Initializing the language model from the user settings messes with the eval, so we only initialize them when
263 // we're not running inside of the eval.
264 init_language_model_settings(cx);
265 }
266 assistant_slash_command::init(cx);
267 agent::init(cx);
268 agent_panel::init(cx);
269 context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
270 TextThreadEditor::init(cx);
271
272 register_slash_commands(cx);
273 inline_assistant::init(
274 fs.clone(),
275 prompt_builder.clone(),
276 client.telemetry().clone(),
277 cx,
278 );
279 terminal_inline_assistant::init(fs.clone(), prompt_builder, client.telemetry().clone(), cx);
280 cx.observe_new(move |workspace, window, cx| {
281 ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
282 })
283 .detach();
284 cx.observe_new(ManageProfilesModal::register).detach();
285
286 // Update command palette filter based on AI settings
287 update_command_palette_filter(cx);
288
289 // Watch for settings changes
290 cx.observe_global::<SettingsStore>(|app_cx| {
291 // When settings change, update the command palette filter
292 update_command_palette_filter(app_cx);
293 })
294 .detach();
295}
296
297fn update_command_palette_filter(cx: &mut App) {
298 let disable_ai = DisableAiSettings::get_global(cx).disable_ai;
299 CommandPaletteFilter::update_global(cx, |filter, _| {
300 if disable_ai {
301 filter.hide_namespace("agent");
302 filter.hide_namespace("assistant");
303 filter.hide_namespace("copilot");
304 filter.hide_namespace("supermaven");
305 filter.hide_namespace("zed_predict_onboarding");
306 filter.hide_namespace("edit_prediction");
307
308 use editor::actions::{
309 AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
310 PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
311 };
312 let edit_prediction_actions = [
313 TypeId::of::<AcceptEditPrediction>(),
314 TypeId::of::<AcceptPartialEditPrediction>(),
315 TypeId::of::<ShowEditPrediction>(),
316 TypeId::of::<NextEditPrediction>(),
317 TypeId::of::<PreviousEditPrediction>(),
318 TypeId::of::<ToggleEditPrediction>(),
319 ];
320 filter.hide_action_types(&edit_prediction_actions);
321 filter.hide_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
322 } else {
323 filter.show_namespace("agent");
324 filter.show_namespace("assistant");
325 filter.show_namespace("copilot");
326 filter.show_namespace("zed_predict_onboarding");
327
328 filter.show_namespace("edit_prediction");
329
330 use editor::actions::{
331 AcceptEditPrediction, AcceptPartialEditPrediction, NextEditPrediction,
332 PreviousEditPrediction, ShowEditPrediction, ToggleEditPrediction,
333 };
334 let edit_prediction_actions = [
335 TypeId::of::<AcceptEditPrediction>(),
336 TypeId::of::<AcceptPartialEditPrediction>(),
337 TypeId::of::<ShowEditPrediction>(),
338 TypeId::of::<NextEditPrediction>(),
339 TypeId::of::<PreviousEditPrediction>(),
340 TypeId::of::<ToggleEditPrediction>(),
341 ];
342 filter.show_action_types(edit_prediction_actions.iter());
343
344 filter.show_action_types(&[TypeId::of::<zed_actions::OpenZedPredictOnboarding>()]);
345 }
346 });
347}
348
349fn init_language_model_settings(cx: &mut App) {
350 update_active_language_model_from_settings(cx);
351
352 cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
353 .detach();
354 cx.subscribe(
355 &LanguageModelRegistry::global(cx),
356 |_, event: &language_model::Event, cx| match event {
357 language_model::Event::ProviderStateChanged(_)
358 | language_model::Event::AddedProvider(_)
359 | language_model::Event::RemovedProvider(_) => {
360 update_active_language_model_from_settings(cx);
361 }
362 _ => {}
363 },
364 )
365 .detach();
366}
367
368fn update_active_language_model_from_settings(cx: &mut App) {
369 let settings = AgentSettings::get_global(cx);
370
371 fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
372 language_model::SelectedModel {
373 provider: LanguageModelProviderId::from(selection.provider.0.clone()),
374 model: LanguageModelId::from(selection.model.clone()),
375 }
376 }
377
378 let default = settings.default_model.as_ref().map(to_selected_model);
379 let inline_assistant = settings
380 .inline_assistant_model
381 .as_ref()
382 .map(to_selected_model);
383 let commit_message = settings
384 .commit_message_model
385 .as_ref()
386 .map(to_selected_model);
387 let thread_summary = settings
388 .thread_summary_model
389 .as_ref()
390 .map(to_selected_model);
391 let inline_alternatives = settings
392 .inline_alternatives
393 .iter()
394 .map(to_selected_model)
395 .collect::<Vec<_>>();
396
397 LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
398 registry.select_default_model(default.as_ref(), cx);
399 registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
400 registry.select_commit_message_model(commit_message.as_ref(), cx);
401 registry.select_thread_summary_model(thread_summary.as_ref(), cx);
402 registry.select_inline_alternative_models(inline_alternatives, cx);
403 });
404}
405
406fn register_slash_commands(cx: &mut App) {
407 let slash_command_registry = SlashCommandRegistry::global(cx);
408
409 slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
410 slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
411 slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
412 slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
413 slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
414 slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
415 slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
416 slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
417 slash_command_registry
418 .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
419 slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
420
421 cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
422 move |is_enabled, _cx| {
423 if is_enabled {
424 slash_command_registry.register_command(
425 assistant_slash_commands::StreamingExampleSlashCommand,
426 false,
427 );
428 }
429 }
430 })
431 .detach();
432}