1#![cfg_attr(target_os = "windows", allow(unused, dead_code))]
2
3mod assistant_configuration;
4pub mod assistant_panel;
5mod inline_assistant;
6pub mod slash_command_settings;
7mod terminal_inline_assistant;
8
9use std::sync::Arc;
10
11use assistant_settings::{AssistantSettings, LanguageModelSelection};
12use assistant_slash_command::SlashCommandRegistry;
13use client::Client;
14use command_palette_hooks::CommandPaletteFilter;
15use feature_flags::FeatureFlagAppExt;
16use fs::Fs;
17use gpui::{App, Global, ReadGlobal, UpdateGlobal, actions};
18use language_model::{
19 LanguageModelId, LanguageModelProviderId, LanguageModelRegistry, LanguageModelResponseMessage,
20};
21use prompt_store::PromptBuilder;
22use serde::Deserialize;
23use settings::{Settings, SettingsStore};
24
25pub use crate::assistant_panel::{AssistantPanel, AssistantPanelEvent};
26pub(crate) use crate::inline_assistant::*;
27use crate::slash_command_settings::SlashCommandSettings;
28
29actions!(
30 assistant,
31 [
32 InsertActivePrompt,
33 DeployHistory,
34 NewChat,
35 CycleNextInlineAssist,
36 CyclePreviousInlineAssist
37 ]
38);
39
40const DEFAULT_CONTEXT_LINES: usize = 50;
41
42#[derive(Deserialize, Debug)]
43pub struct LanguageModelUsage {
44 pub prompt_tokens: u32,
45 pub completion_tokens: u32,
46 pub total_tokens: u32,
47}
48
49#[derive(Deserialize, Debug)]
50pub struct LanguageModelChoiceDelta {
51 pub index: u32,
52 pub delta: LanguageModelResponseMessage,
53 pub finish_reason: Option<String>,
54}
55
56/// The state pertaining to the Assistant.
57#[derive(Default)]
58struct Assistant {
59 /// Whether the Assistant is enabled.
60 enabled: bool,
61}
62
63impl Global for Assistant {}
64
65impl Assistant {
66 const NAMESPACE: &'static str = "assistant";
67
68 fn set_enabled(&mut self, enabled: bool, cx: &mut App) {
69 if self.enabled == enabled {
70 return;
71 }
72
73 self.enabled = enabled;
74
75 if !enabled {
76 CommandPaletteFilter::update_global(cx, |filter, _cx| {
77 filter.hide_namespace(Self::NAMESPACE);
78 });
79
80 return;
81 }
82
83 CommandPaletteFilter::update_global(cx, |filter, _cx| {
84 filter.show_namespace(Self::NAMESPACE);
85 });
86 }
87
88 pub fn enabled(cx: &App) -> bool {
89 Self::global(cx).enabled
90 }
91}
92
93pub fn init(
94 fs: Arc<dyn Fs>,
95 client: Arc<Client>,
96 prompt_builder: Arc<PromptBuilder>,
97 cx: &mut App,
98) {
99 cx.set_global(Assistant::default());
100 AssistantSettings::register(cx);
101 SlashCommandSettings::register(cx);
102
103 assistant_context_editor::init(client.clone(), cx);
104 rules_library::init(cx);
105 init_language_model_settings(cx);
106 assistant_slash_command::init(cx);
107 assistant_tool::init(cx);
108 assistant_panel::init(cx);
109
110 register_slash_commands(cx);
111 inline_assistant::init(
112 fs.clone(),
113 prompt_builder.clone(),
114 client.telemetry().clone(),
115 cx,
116 );
117 terminal_inline_assistant::init(
118 fs.clone(),
119 prompt_builder.clone(),
120 client.telemetry().clone(),
121 cx,
122 );
123 indexed_docs::init(cx);
124
125 CommandPaletteFilter::update_global(cx, |filter, _cx| {
126 filter.hide_namespace(Assistant::NAMESPACE);
127 });
128 Assistant::update_global(cx, |assistant, cx| {
129 let settings = AssistantSettings::get_global(cx);
130
131 assistant.set_enabled(settings.enabled, cx);
132 });
133 cx.observe_global::<SettingsStore>(|cx| {
134 Assistant::update_global(cx, |assistant, cx| {
135 let settings = AssistantSettings::get_global(cx);
136 assistant.set_enabled(settings.enabled, cx);
137 });
138 })
139 .detach();
140}
141
142fn init_language_model_settings(cx: &mut App) {
143 update_active_language_model_from_settings(cx);
144
145 cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
146 .detach();
147 cx.subscribe(
148 &LanguageModelRegistry::global(cx),
149 |_, event: &language_model::Event, cx| match event {
150 language_model::Event::ProviderStateChanged
151 | language_model::Event::AddedProvider(_)
152 | language_model::Event::RemovedProvider(_) => {
153 update_active_language_model_from_settings(cx);
154 }
155 _ => {}
156 },
157 )
158 .detach();
159}
160
161fn update_active_language_model_from_settings(cx: &mut App) {
162 let settings = AssistantSettings::get_global(cx);
163
164 fn to_selected_model(selection: &LanguageModelSelection) -> language_model::SelectedModel {
165 language_model::SelectedModel {
166 provider: LanguageModelProviderId::from(selection.provider.clone()),
167 model: LanguageModelId::from(selection.model.clone()),
168 }
169 }
170
171 let default = to_selected_model(&settings.default_model);
172 let inline_assistant = settings
173 .inline_assistant_model
174 .as_ref()
175 .map(to_selected_model);
176 let commit_message = settings
177 .commit_message_model
178 .as_ref()
179 .map(to_selected_model);
180 let thread_summary = settings
181 .thread_summary_model
182 .as_ref()
183 .map(to_selected_model);
184 let inline_alternatives = settings
185 .inline_alternatives
186 .iter()
187 .map(to_selected_model)
188 .collect::<Vec<_>>();
189
190 LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
191 registry.select_default_model(Some(&default), cx);
192 registry.select_inline_assistant_model(inline_assistant.as_ref(), cx);
193 registry.select_commit_message_model(commit_message.as_ref(), cx);
194 registry.select_thread_summary_model(thread_summary.as_ref(), cx);
195 registry.select_inline_alternative_models(inline_alternatives, cx);
196 });
197}
198
199fn register_slash_commands(cx: &mut App) {
200 let slash_command_registry = SlashCommandRegistry::global(cx);
201
202 slash_command_registry.register_command(assistant_slash_commands::FileSlashCommand, true);
203 slash_command_registry.register_command(assistant_slash_commands::DeltaSlashCommand, true);
204 slash_command_registry.register_command(assistant_slash_commands::OutlineSlashCommand, true);
205 slash_command_registry.register_command(assistant_slash_commands::TabSlashCommand, true);
206 slash_command_registry
207 .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
208 slash_command_registry.register_command(assistant_slash_commands::PromptSlashCommand, true);
209 slash_command_registry.register_command(assistant_slash_commands::SelectionCommand, true);
210 slash_command_registry.register_command(assistant_slash_commands::DefaultSlashCommand, false);
211 slash_command_registry.register_command(assistant_slash_commands::TerminalSlashCommand, true);
212 slash_command_registry.register_command(assistant_slash_commands::NowSlashCommand, false);
213 slash_command_registry
214 .register_command(assistant_slash_commands::DiagnosticsSlashCommand, true);
215 slash_command_registry.register_command(assistant_slash_commands::FetchSlashCommand, true);
216
217 cx.observe_flag::<assistant_slash_commands::StreamingExampleSlashCommandFeatureFlag, _>({
218 let slash_command_registry = slash_command_registry.clone();
219 move |is_enabled, _cx| {
220 if is_enabled {
221 slash_command_registry.register_command(
222 assistant_slash_commands::StreamingExampleSlashCommand,
223 false,
224 );
225 }
226 }
227 })
228 .detach();
229
230 update_slash_commands_from_settings(cx);
231 cx.observe_global::<SettingsStore>(update_slash_commands_from_settings)
232 .detach();
233}
234
235fn update_slash_commands_from_settings(cx: &mut App) {
236 let slash_command_registry = SlashCommandRegistry::global(cx);
237 let settings = SlashCommandSettings::get_global(cx);
238
239 if settings.docs.enabled {
240 slash_command_registry.register_command(assistant_slash_commands::DocsSlashCommand, true);
241 } else {
242 slash_command_registry.unregister_command(assistant_slash_commands::DocsSlashCommand);
243 }
244
245 if settings.cargo_workspace.enabled {
246 slash_command_registry
247 .register_command(assistant_slash_commands::CargoWorkspaceSlashCommand, true);
248 } else {
249 slash_command_registry
250 .unregister_command(assistant_slash_commands::CargoWorkspaceSlashCommand);
251 }
252}
253
254#[cfg(test)]
255#[ctor::ctor]
256fn init_logger() {
257 if std::env::var("RUST_LOG").is_ok() {
258 env_logger::init();
259 }
260}