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
200pub fn init_settings(cx: &mut App) {
201 AgentSettings::register(cx);
202 SlashCommandSettings::register(cx);
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 init_settings(cx);
215
216 assistant_context::init(client.clone(), cx);
217 rules_library::init(cx);
218 if !is_eval {
219 // Initializing the language model from the user settings messes with the eval, so we only initialize them when
220 // we're not running inside of the eval.
221 init_language_model_settings(cx);
222 }
223 assistant_slash_command::init(cx);
224 agent::init(cx);
225 agent_panel::init(cx);
226 context_server_configuration::init(language_registry.clone(), fs.clone(), cx);
227 TextThreadEditor::init(cx);
228
229 register_slash_commands(cx);
230 inline_assistant::init(
231 fs.clone(),
232 prompt_builder.clone(),
233 client.telemetry().clone(),
234 cx,
235 );
236 terminal_inline_assistant::init(
237 fs.clone(),
238 prompt_builder.clone(),
239 client.telemetry().clone(),
240 cx,
241 );
242 indexed_docs::init(cx);
243 cx.observe_new(move |workspace, window, cx| {
244 ConfigureContextServerModal::register(workspace, language_registry.clone(), window, cx)
245 })
246 .detach();
247 cx.observe_new(ManageProfilesModal::register).detach();
248}
249
250fn init_language_model_settings(cx: &mut App) {
251 update_active_language_model_from_settings(cx);
252
253 cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
254 .detach();
255 cx.subscribe(
256 &LanguageModelRegistry::global(cx),
257 |_, event: &language_model::Event, cx| match event {
258 language_model::Event::ProviderStateChanged
259 | language_model::Event::AddedProvider(_)
260 | language_model::Event::RemovedProvider(_) => {
261 update_active_language_model_from_settings(cx);
262 }
263 _ => {}
264 },
265 )
266 .detach();
267}
268
269fn update_active_language_model_from_settings(cx: &mut App) {
270 let settings = AgentSettings::get_global(cx);
271
272 fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
273 language_model::SelectedModel {
274 provider: LanguageModelProviderId::from(selection.provider.0.clone()),
275 model: LanguageModelId::from(selection.model.clone()),
276 }
277 }
278
279 let default = settings.default_model.as_ref().map(to_selected_model);
280 let inline_assistant = settings
281 .inline_assistant_model
282 .as_ref()
283 .map(to_selected_model);
284 let commit_message = settings
285 .commit_message_model
286 .as_ref()
287 .map(to_selected_model);
288 let thread_summary = settings
289 .thread_summary_model
290 .as_ref()
291 .map(to_selected_model);
292 let inline_alternatives = settings
293 .inline_alternatives
294 .iter()
295 .map(to_selected_model)
296 .collect::<Vec<_>>();
297
298 LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
299 registry.select_default_model(default.as_ref(), cx);
300 registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
301 registry.select_commit_message_model(commit_message.as_ref(), cx);
302 registry.select_thread_summary_model(thread_summary.as_ref(), cx);
303 registry.select_inline_alternative_models(inline_alternatives, cx);
304 });
305}
306
307fn register_slash_commands(cx: &mut App) {
308 let slash_command_registry = SlashCommandRegistry::global(cx);
309
310 slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
311 slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
312 slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
313 slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
314 slash_command_registry
315 .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
316 slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
317 slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
318 slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
319 slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
320 slash_command_registry
321 .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
322 slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
323
324 cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
325 let slash_command_registry = slash_command_registry.clone();
326 move |is_enabled, _cx| {
327 if is_enabled {
328 slash_command_registry.register_command(
329 assistant_slash_commands::StreamingExampleSlashCommand,
330 false,
331 );
332 }
333 }
334 })
335 .detach();
336
337 update_slash_commands_from_settings(cx);
338 cx.observe_global::<SettingsStore>(update_slash_commands_from_settings)
339 .detach();
340}
341
342fn update_slash_commands_from_settings(cx: &mut App) {
343 let slash_command_registry = SlashCommandRegistry::global(cx);
344 let settings = SlashCommandSettings::get_global(cx);
345
346 if settings.docs.enabled {
347 slash_command_registry.register_command(assistant_slash_commands::DocsSlashCommand, true);
348 } else {
349 slash_command_registry.unregister_command(assistant_slash_commands::DocsSlashCommand);
350 }
351
352 if settings.cargo_workspace.enabled {
353 slash_command_registry
354 .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
355 } else {
356 slash_command_registry
357 .unregister_command(assistant_slash_commands::CargoWorkspaceSlashCommand);
358 }
359}