assistant.rs

  1#![cfg_attr(target_os = "windows", allow(unused, dead_code))]
  2
  3pub mod assistant_panel;
  4pub mod assistant_settings;
  5mod context;
  6pub mod context_store;
  7mod inline_assistant;
  8mod model_selector;
  9mod prompt_library;
 10mod prompts;
 11mod slash_command;
 12pub(crate) mod slash_command_picker;
 13pub mod slash_command_settings;
 14mod streaming_diff;
 15mod terminal_inline_assistant;
 16mod tools;
 17mod workflow;
 18
 19pub use assistant_panel::{AssistantPanel, AssistantPanelEvent};
 20use assistant_settings::AssistantSettings;
 21use assistant_slash_command::SlashCommandRegistry;
 22use assistant_tool::ToolRegistry;
 23use client::{proto, Client};
 24use command_palette_hooks::CommandPaletteFilter;
 25pub use context::*;
 26use context_servers::ContextServerRegistry;
 27pub use context_store::*;
 28use feature_flags::FeatureFlagAppExt;
 29use fs::Fs;
 30use gpui::{actions, AppContext, Global, SharedString, UpdateGlobal};
 31use gpui::{impl_actions, Context as _};
 32use indexed_docs::IndexedDocsRegistry;
 33pub(crate) use inline_assistant::*;
 34use language_model::{
 35    LanguageModelId, LanguageModelProviderId, LanguageModelRegistry, LanguageModelResponseMessage,
 36};
 37pub(crate) use model_selector::*;
 38pub use prompts::PromptBuilder;
 39use prompts::PromptLoadingParams;
 40use semantic_index::{CloudEmbeddingProvider, SemanticIndex};
 41use serde::{Deserialize, Serialize};
 42use settings::{update_settings_file, Settings, SettingsStore};
 43use slash_command::{
 44    context_server_command, default_command, diagnostics_command, docs_command, fetch_command,
 45    file_command, now_command, project_command, prompt_command, search_command, symbols_command,
 46    tab_command, terminal_command, workflow_command,
 47};
 48use std::path::PathBuf;
 49use std::sync::Arc;
 50pub(crate) use streaming_diff::*;
 51use util::ResultExt;
 52pub use workflow::*;
 53
 54use crate::slash_command_settings::SlashCommandSettings;
 55
 56actions!(
 57    assistant,
 58    [
 59        Assist,
 60        Split,
 61        CycleMessageRole,
 62        QuoteSelection,
 63        InsertIntoEditor,
 64        ToggleFocus,
 65        InsertActivePrompt,
 66        DeployHistory,
 67        DeployPromptLibrary,
 68        ConfirmCommand,
 69        NewContext,
 70        ToggleModelSelector,
 71    ]
 72);
 73
 74#[derive(PartialEq, Clone, Deserialize)]
 75pub enum InsertDraggedFiles {
 76    ProjectPaths(Vec<PathBuf>),
 77    ExternalFiles(Vec<PathBuf>),
 78}
 79
 80impl_actions!(assistant, [InsertDraggedFiles]);
 81
 82const DEFAULT_CONTEXT_LINES: usize = 50;
 83
 84#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
 85pub struct MessageId(clock::Lamport);
 86
 87impl MessageId {
 88    pub fn as_u64(self) -> u64 {
 89        self.0.as_u64()
 90    }
 91}
 92
 93#[derive(Deserialize, Debug)]
 94pub struct LanguageModelUsage {
 95    pub prompt_tokens: u32,
 96    pub completion_tokens: u32,
 97    pub total_tokens: u32,
 98}
 99
100#[derive(Deserialize, Debug)]
101pub struct LanguageModelChoiceDelta {
102    pub index: u32,
103    pub delta: LanguageModelResponseMessage,
104    pub finish_reason: Option<String>,
105}
106
107#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
108pub enum MessageStatus {
109    Pending,
110    Done,
111    Error(SharedString),
112    Canceled,
113}
114
115impl MessageStatus {
116    pub fn from_proto(status: proto::ContextMessageStatus) -> MessageStatus {
117        match status.variant {
118            Some(proto::context_message_status::Variant::Pending(_)) => MessageStatus::Pending,
119            Some(proto::context_message_status::Variant::Done(_)) => MessageStatus::Done,
120            Some(proto::context_message_status::Variant::Error(error)) => {
121                MessageStatus::Error(error.message.into())
122            }
123            Some(proto::context_message_status::Variant::Canceled(_)) => MessageStatus::Canceled,
124            None => MessageStatus::Pending,
125        }
126    }
127
128    pub fn to_proto(&self) -> proto::ContextMessageStatus {
129        match self {
130            MessageStatus::Pending => proto::ContextMessageStatus {
131                variant: Some(proto::context_message_status::Variant::Pending(
132                    proto::context_message_status::Pending {},
133                )),
134            },
135            MessageStatus::Done => proto::ContextMessageStatus {
136                variant: Some(proto::context_message_status::Variant::Done(
137                    proto::context_message_status::Done {},
138                )),
139            },
140            MessageStatus::Error(message) => proto::ContextMessageStatus {
141                variant: Some(proto::context_message_status::Variant::Error(
142                    proto::context_message_status::Error {
143                        message: message.to_string(),
144                    },
145                )),
146            },
147            MessageStatus::Canceled => proto::ContextMessageStatus {
148                variant: Some(proto::context_message_status::Variant::Canceled(
149                    proto::context_message_status::Canceled {},
150                )),
151            },
152        }
153    }
154}
155
156/// The state pertaining to the Assistant.
157#[derive(Default)]
158struct Assistant {
159    /// Whether the Assistant is enabled.
160    enabled: bool,
161}
162
163impl Global for Assistant {}
164
165impl Assistant {
166    const NAMESPACE: &'static str = "assistant";
167
168    fn set_enabled(&mut self, enabled: bool, cx: &mut AppContext) {
169        if self.enabled == enabled {
170            return;
171        }
172
173        self.enabled = enabled;
174
175        if !enabled {
176            CommandPaletteFilter::update_global(cx, |filter, _cx| {
177                filter.hide_namespace(Self::NAMESPACE);
178            });
179
180            return;
181        }
182
183        CommandPaletteFilter::update_global(cx, |filter, _cx| {
184            filter.show_namespace(Self::NAMESPACE);
185        });
186    }
187}
188
189pub fn init(
190    fs: Arc<dyn Fs>,
191    client: Arc<Client>,
192    stdout_is_a_pty: bool,
193    cx: &mut AppContext,
194) -> Arc<PromptBuilder> {
195    cx.set_global(Assistant::default());
196    AssistantSettings::register(cx);
197    SlashCommandSettings::register(cx);
198
199    // TODO: remove this when 0.148.0 is released.
200    if AssistantSettings::get_global(cx).using_outdated_settings_version {
201        update_settings_file::<AssistantSettings>(fs.clone(), cx, {
202            let fs = fs.clone();
203            |content, cx| {
204                content.update_file(fs, cx);
205            }
206        });
207    }
208
209    cx.spawn(|mut cx| {
210        let client = client.clone();
211        async move {
212            let embedding_provider = CloudEmbeddingProvider::new(client.clone());
213            let semantic_index = SemanticIndex::new(
214                paths::embeddings_dir().join("semantic-index-db.0.mdb"),
215                Arc::new(embedding_provider),
216                &mut cx,
217            )
218            .await?;
219            cx.update(|cx| cx.set_global(semantic_index))
220        }
221    })
222    .detach();
223
224    context_store::init(&client.clone().into());
225    prompt_library::init(cx);
226    init_language_model_settings(cx);
227    assistant_slash_command::init(cx);
228    assistant_tool::init(cx);
229    assistant_panel::init(cx);
230    context_servers::init(cx);
231
232    let prompt_builder = prompts::PromptBuilder::new(Some(PromptLoadingParams {
233        fs: fs.clone(),
234        repo_path: stdout_is_a_pty
235            .then(|| std::env::current_dir().log_err())
236            .flatten(),
237        cx,
238    }))
239    .log_err()
240    .map(Arc::new)
241    .unwrap_or_else(|| Arc::new(prompts::PromptBuilder::new(None).unwrap()));
242    register_slash_commands(Some(prompt_builder.clone()), cx);
243    register_tools(cx);
244    inline_assistant::init(
245        fs.clone(),
246        prompt_builder.clone(),
247        client.telemetry().clone(),
248        cx,
249    );
250    terminal_inline_assistant::init(
251        fs.clone(),
252        prompt_builder.clone(),
253        client.telemetry().clone(),
254        cx,
255    );
256    IndexedDocsRegistry::init_global(cx);
257
258    CommandPaletteFilter::update_global(cx, |filter, _cx| {
259        filter.hide_namespace(Assistant::NAMESPACE);
260    });
261    Assistant::update_global(cx, |assistant, cx| {
262        let settings = AssistantSettings::get_global(cx);
263
264        assistant.set_enabled(settings.enabled, cx);
265    });
266    cx.observe_global::<SettingsStore>(|cx| {
267        Assistant::update_global(cx, |assistant, cx| {
268            let settings = AssistantSettings::get_global(cx);
269            assistant.set_enabled(settings.enabled, cx);
270        });
271    })
272    .detach();
273
274    register_context_server_handlers(cx);
275
276    prompt_builder
277}
278
279fn register_context_server_handlers(cx: &mut AppContext) {
280    cx.subscribe(
281        &context_servers::manager::ContextServerManager::global(cx),
282        |manager, event, cx| match event {
283            context_servers::manager::Event::ServerStarted { server_id } => {
284                cx.update_model(
285                    &manager,
286                    |manager: &mut context_servers::manager::ContextServerManager, cx| {
287                        let slash_command_registry = SlashCommandRegistry::global(cx);
288                        let context_server_registry = ContextServerRegistry::global(cx);
289                        if let Some(server) = manager.get_server(server_id) {
290                            cx.spawn(|_, _| async move {
291                                let Some(protocol) = server.client.read().clone() else {
292                                    return;
293                                };
294
295                                if let Some(prompts) = protocol.list_prompts().await.log_err() {
296                                    for prompt in prompts
297                                        .into_iter()
298                                        .filter(context_server_command::acceptable_prompt)
299                                    {
300                                        log::info!(
301                                            "registering context server command: {:?}",
302                                            prompt.name
303                                        );
304                                        context_server_registry.register_command(
305                                            server.id.clone(),
306                                            prompt.name.as_str(),
307                                        );
308                                        slash_command_registry.register_command(
309                                            context_server_command::ContextServerSlashCommand::new(
310                                                &server, prompt,
311                                            ),
312                                            true,
313                                        );
314                                    }
315                                }
316                            })
317                            .detach();
318                        }
319                    },
320                );
321            }
322            context_servers::manager::Event::ServerStopped { server_id } => {
323                let slash_command_registry = SlashCommandRegistry::global(cx);
324                let context_server_registry = ContextServerRegistry::global(cx);
325                if let Some(commands) = context_server_registry.get_commands(server_id) {
326                    for command_name in commands {
327                        slash_command_registry.unregister_command_by_name(&command_name);
328                        context_server_registry.unregister_command(&server_id, &command_name);
329                    }
330                }
331            }
332        },
333    )
334    .detach();
335}
336
337fn init_language_model_settings(cx: &mut AppContext) {
338    update_active_language_model_from_settings(cx);
339
340    cx.observe_global::<SettingsStore>(update_active_language_model_from_settings)
341        .detach();
342    cx.subscribe(
343        &LanguageModelRegistry::global(cx),
344        |_, event: &language_model::Event, cx| match event {
345            language_model::Event::ProviderStateChanged
346            | language_model::Event::AddedProvider(_)
347            | language_model::Event::RemovedProvider(_) => {
348                update_active_language_model_from_settings(cx);
349            }
350            _ => {}
351        },
352    )
353    .detach();
354}
355
356fn update_active_language_model_from_settings(cx: &mut AppContext) {
357    let settings = AssistantSettings::get_global(cx);
358    let provider_name = LanguageModelProviderId::from(settings.default_model.provider.clone());
359    let model_id = LanguageModelId::from(settings.default_model.model.clone());
360    LanguageModelRegistry::global(cx).update(cx, |registry, cx| {
361        registry.select_active_model(&provider_name, &model_id, cx);
362    });
363}
364
365fn register_slash_commands(prompt_builder: Option<Arc<PromptBuilder>>, cx: &mut AppContext) {
366    let slash_command_registry = SlashCommandRegistry::global(cx);
367    slash_command_registry.register_command(file_command::FileSlashCommand, true);
368    slash_command_registry.register_command(symbols_command::OutlineSlashCommand, true);
369    slash_command_registry.register_command(tab_command::TabSlashCommand, true);
370    slash_command_registry.register_command(project_command::ProjectSlashCommand, true);
371    slash_command_registry.register_command(prompt_command::PromptSlashCommand, true);
372    slash_command_registry.register_command(default_command::DefaultSlashCommand, false);
373    slash_command_registry.register_command(terminal_command::TerminalSlashCommand, true);
374    slash_command_registry.register_command(now_command::NowSlashCommand, false);
375    slash_command_registry.register_command(diagnostics_command::DiagnosticsSlashCommand, true);
376
377    if let Some(prompt_builder) = prompt_builder {
378        slash_command_registry.register_command(
379            workflow_command::WorkflowSlashCommand::new(prompt_builder.clone()),
380            true,
381        );
382    }
383    slash_command_registry.register_command(fetch_command::FetchSlashCommand, false);
384
385    update_slash_commands_from_settings(cx);
386    cx.observe_global::<SettingsStore>(update_slash_commands_from_settings)
387        .detach();
388
389    cx.observe_flag::<search_command::SearchSlashCommandFeatureFlag, _>({
390        let slash_command_registry = slash_command_registry.clone();
391        move |is_enabled, _cx| {
392            if is_enabled {
393                slash_command_registry.register_command(search_command::SearchSlashCommand, true);
394            }
395        }
396    })
397    .detach();
398}
399
400fn update_slash_commands_from_settings(cx: &mut AppContext) {
401    let slash_command_registry = SlashCommandRegistry::global(cx);
402    let settings = SlashCommandSettings::get_global(cx);
403
404    if settings.docs.enabled {
405        slash_command_registry.register_command(docs_command::DocsSlashCommand, true);
406    } else {
407        slash_command_registry.unregister_command(docs_command::DocsSlashCommand);
408    }
409
410    if settings.project.enabled {
411        slash_command_registry.register_command(project_command::ProjectSlashCommand, true);
412    } else {
413        slash_command_registry.unregister_command(project_command::ProjectSlashCommand);
414    }
415}
416
417fn register_tools(cx: &mut AppContext) {
418    let tool_registry = ToolRegistry::global(cx);
419    tool_registry.register_tool(tools::now_tool::NowTool);
420}
421
422pub fn humanize_token_count(count: usize) -> String {
423    match count {
424        0..=999 => count.to_string(),
425        1000..=9999 => {
426            let thousands = count / 1000;
427            let hundreds = (count % 1000 + 50) / 100;
428            if hundreds == 0 {
429                format!("{}k", thousands)
430            } else if hundreds == 10 {
431                format!("{}k", thousands + 1)
432            } else {
433                format!("{}.{}k", thousands, hundreds)
434            }
435        }
436        _ => format!("{}k", (count + 500) / 1000),
437    }
438}
439
440#[cfg(test)]
441#[ctor::ctor]
442fn init_logger() {
443    if std::env::var("RUST_LOG").is_ok() {
444        env_logger::init();
445    }
446}