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;
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 prompt_store::PromptBuilder;
43use schemars::JsonSchema;
44use serde::{Deserialize, Serialize};
45use settings::{Settings as _, SettingsStore};
46
47pub use crate::active_thread::ActiveThread;
48use crate::agent_configuration::{ConfigureContextServerModal, ManageProfilesModal};
49pub use crate::agent_panel::{AgentPanel, ConcreteAssistantPanelDelegate};
50pub use crate::inline_assistant::InlineAssistant;
51use crate::slash_command_settings::SlashCommandSettings;
52pub use agent_diff::{AgentDiffPane, AgentDiffToolbar};
53pub use text_thread_editor::{AgentPanelDelegate, TextThreadEditor};
54pub use ui::preview::{all_agent_previews, get_agent_preview};
55
56actions!(
57 agent,
58 [
59 /// Creates a new text-based conversation thread.
60 NewTextThread,
61 /// Toggles the context picker interface for adding files, symbols, or other context.
62 ToggleContextPicker,
63 /// Toggles the navigation menu for switching between threads and views.
64 ToggleNavigationMenu,
65 /// Toggles the options menu for agent settings and preferences.
66 ToggleOptionsMenu,
67 /// Deletes the recently opened thread from history.
68 DeleteRecentlyOpenThread,
69 /// Toggles the profile selector for switching between agent profiles.
70 ToggleProfileSelector,
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 /// Follows the agent's suggestions.
112 Follow,
113 /// Resets the trial upsell notification.
114 ResetTrialUpsell,
115 /// Resets the trial end upsell notification.
116 ResetTrialEndUpsell,
117 /// Continues the current thread.
118 ContinueThread,
119 /// Continues the thread with burn mode enabled.
120 ContinueWithBurnMode,
121 /// Toggles burn mode for faster responses.
122 ToggleBurnMode,
123 ]
124);
125
126/// Creates a new conversation thread, optionally based on an existing thread.
127#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
128#[action(namespace = agent)]
129#[serde(deny_unknown_fields)]
130pub struct NewThread {
131 #[serde(default)]
132 from_thread_id: Option<ThreadId>,
133}
134
135/// Creates a new external agent conversation thread.
136#[derive(Default, Clone, PartialEq, Deserialize, JsonSchema, Action)]
137#[action(namespace = agent)]
138#[serde(deny_unknown_fields)]
139pub struct NewExternalAgentThread {
140 /// Which agent to use for the conversation.
141 agent: Option<ExternalAgent>,
142}
143
144#[derive(Default, Clone, Copy, PartialEq, Serialize, Deserialize, JsonSchema)]
145#[serde(rename_all = "snake_case")]
146enum ExternalAgent {
147 #[default]
148 Gemini,
149 ClaudeCode,
150}
151
152impl ExternalAgent {
153 pub fn server(&self) -> Rc<dyn agent_servers::AgentServer> {
154 match self {
155 ExternalAgent::Gemini => Rc::new(agent_servers::Gemini),
156 ExternalAgent::ClaudeCode => Rc::new(agent_servers::ClaudeCode),
157 }
158 }
159}
160
161/// Opens the profile management interface for configuring agent tools and settings.
162#[derive(PartialEq, Clone, Default, Debug, Deserialize, JsonSchema, Action)]
163#[action(namespace = agent)]
164#[serde(deny_unknown_fields)]
165pub struct ManageProfiles {
166 #[serde(default)]
167 pub customize_tools: Option<AgentProfileId>,
168}
169
170impl ManageProfiles {
171 pub fn customize_tools(profile_id: AgentProfileId) -> Self {
172 Self {
173 customize_tools: Some(profile_id),
174 }
175 }
176}
177
178#[derive(Clone)]
179pub(crate) enum ModelUsageContext {
180 Thread(Entity<Thread>),
181 InlineAssistant,
182}
183
184impl ModelUsageContext {
185 pub fn configured_model(&self, cx: &App) -> Option<ConfiguredModel> {
186 match self {
187 Self::Thread(thread) => thread.read(cx).configured_model(),
188 Self::InlineAssistant => {
189 LanguageModelRegistry::read_global(cx).inline_assistant_model()
190 }
191 }
192 }
193
194 pub fn language_model(&self, cx: &App) -> Option<Arc<dyn LanguageModel>> {
195 self.configured_model(cx)
196 .map(|configured_model| configured_model.model)
197 }
198}
199
200/// Initializes the `agent` crate.
201pub fn init(
202 fs: Arc<dyn Fs>,
203 client: Arc<Client>,
204 prompt_builder: Arc<PromptBuilder>,
205 language_registry: Arc<LanguageRegistry>,
206 is_eval: bool,
207 cx: &mut App,
208) {
209 AgentSettings::register(cx);
210 SlashCommandSettings::register(cx);
211
212 assistant_context::init(client.clone(), cx);
213 rules_library::init(cx);
214 if !is_eval {
215 // Initializing the language model from the user settings messes with the eval, so we only initialize them when
216 // we're not running inside of the eval.
217 init_language_model_settings(cx);
218 }
219 assistant_slash_command::init(cx);
220 agent::init(cx);
221 agent_panel::init(cx);
222 context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
223 TextThreadEditor::init(cx);
224
225 register_slash_commands(cx);
226 inline_assistant::init(
227 fs.clone(),
228 prompt_builder.clone(),
229 client.telemetry().clone(),
230 cx,
231 );
232 terminal_inline_assistant::init(
233 fs.clone(),
234 prompt_builder.clone(),
235 client.telemetry().clone(),
236 cx,
237 );
238 indexed_docs::init(cx);
239 cx.observe_new(move |workspace, window, cx| {
240 ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
241 })
242 .detach();
243 cx.observe_new(ManageProfilesModal::register).detach();
244}
245
246fn init_language_model_settings(cx: &mut App) {
247 update_active_language_model_from_settings(cx);
248
249 cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
250 .detach();
251 cx.subscribe(
252 &LanguageModelRegistry::global(cx),
253 |_, event: &language_model::Event, cx| match event {
254 language_model::Event::ProviderStateChanged
255 | language_model::Event::AddedProvider(_)
256 | language_model::Event::RemovedProvider(_) => {
257 update_active_language_model_from_settings(cx);
258 }
259 _ => {}
260 },
261 )
262 .detach();
263}
264
265fn update_active_language_model_from_settings(cx: &mut App) {
266 let settings = AgentSettings::get_global(cx);
267
268 fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
269 language_model::SelectedModel {
270 provider: LanguageModelProviderId::from(selection.provider.0.clone()),
271 model: LanguageModelId::from(selection.model.clone()),
272 }
273 }
274
275 let default = settings.default_model.as_ref().map(to_selected_model);
276 let inline_assistant = settings
277 .inline_assistant_model
278 .as_ref()
279 .map(to_selected_model);
280 let commit_message = settings
281 .commit_message_model
282 .as_ref()
283 .map(to_selected_model);
284 let thread_summary = settings
285 .thread_summary_model
286 .as_ref()
287 .map(to_selected_model);
288 let inline_alternatives = settings
289 .inline_alternatives
290 .iter()
291 .map(to_selected_model)
292 .collect::<Vec<_>>();
293
294 LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
295 registry.select_default_model(default.as_ref(), cx);
296 registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
297 registry.select_commit_message_model(commit_message.as_ref(), cx);
298 registry.select_thread_summary_model(thread_summary.as_ref(), cx);
299 registry.select_inline_alternative_models(inline_alternatives, cx);
300 });
301}
302
303fn register_slash_commands(cx: &mut App) {
304 let slash_command_registry = SlashCommandRegistry::global(cx);
305
306 slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
307 slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
308 slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
309 slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
310 slash_command_registry
311 .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
312 slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
313 slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
314 slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
315 slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
316 slash_command_registry
317 .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
318 slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
319
320 cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
321 let slash_command_registry = slash_command_registry.clone();
322 move |is_enabled, _cx| {
323 if is_enabled {
324 slash_command_registry.register_command(
325 assistant_slash_commands::StreamingExampleSlashCommand,
326 false,
327 );
328 }
329 }
330 })
331 .detach();
332
333 update_slash_commands_from_settings(cx);
334 cx.observe_global::<SettingsStore>(update_slash_commands_from_settings)
335 .detach();
336}
337
338fn update_slash_commands_from_settings(cx: &mut App) {
339 let slash_command_registry = SlashCommandRegistry::global(cx);
340 let settings = SlashCommandSettings::get_global(cx);
341
342 if settings.docs.enabled {
343 slash_command_registry.register_command(assistant_slash_commands::DocsSlashCommand, true);
344 } else {
345 slash_command_registry.unregister_command(assistant_slash_commands::DocsSlashCommand);
346 }
347
348 if settings.cargo_workspace.enabled {
349 slash_command_registry
350 .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
351 } else {
352 slash_command_registry
353 .unregister_command(assistant_slash_commands::CargoWorkspaceSlashCommand);
354 }
355}