prompts.rs

  1use anyhow::Result;
  2use assets::Assets;
  3use fs::Fs;
  4use futures::StreamExt;
  5use gpui::{App, AppContext as _, AssetSource};
  6use handlebars::{Handlebars, RenderError};
  7use language::{BufferSnapshot, LanguageName, Point};
  8use parking_lot::Mutex;
  9use serde::Serialize;
 10use std::{
 11    ops::Range,
 12    path::{Path, PathBuf},
 13    sync::Arc,
 14    time::Duration,
 15};
 16use text::LineEnding;
 17use util::{ResultExt, get_system_shell};
 18
 19use crate::UserPromptId;
 20
 21#[derive(Debug, Clone, Serialize)]
 22pub struct ProjectContext {
 23    pub worktrees: Vec<WorktreeContext>,
 24    /// Whether any worktree has a rules_file. Provided as a field because handlebars can't do this.
 25    pub has_rules: bool,
 26    pub user_rules: Vec<UserRulesContext>,
 27    /// `!user_rules.is_empty()` - provided as a field because handlebars can't do this.
 28    pub has_user_rules: bool,
 29    pub os: String,
 30    pub arch: String,
 31    pub shell: String,
 32}
 33
 34impl ProjectContext {
 35    pub fn new(worktrees: Vec<WorktreeContext>, default_user_rules: Vec<UserRulesContext>) -> Self {
 36        let has_rules = worktrees
 37            .iter()
 38            .any(|worktree| worktree.rules_file.is_some());
 39        Self {
 40            worktrees,
 41            has_rules,
 42            has_user_rules: !default_user_rules.is_empty(),
 43            user_rules: default_user_rules,
 44            os: std::env::consts::OS.to_string(),
 45            arch: std::env::consts::ARCH.to_string(),
 46            shell: get_system_shell(),
 47        }
 48    }
 49}
 50
 51#[derive(Debug, Clone, Serialize)]
 52pub struct UserRulesContext {
 53    pub uuid: UserPromptId,
 54    pub title: Option<String>,
 55    pub contents: String,
 56}
 57
 58#[derive(Debug, Clone, Serialize)]
 59pub struct WorktreeContext {
 60    pub root_name: String,
 61    pub rules_file: Option<RulesFileContext>,
 62}
 63
 64#[derive(Debug, Clone, Serialize)]
 65pub struct RulesFileContext {
 66    pub path_in_worktree: Arc<Path>,
 67    pub abs_path: Arc<Path>,
 68    pub text: String,
 69}
 70
 71#[derive(Serialize)]
 72pub struct ContentPromptDiagnosticContext {
 73    pub line_number: usize,
 74    pub error_message: String,
 75    pub code_content: String,
 76}
 77
 78#[derive(Serialize)]
 79pub struct ContentPromptContext {
 80    pub content_type: String,
 81    pub language_name: Option<String>,
 82    pub is_insert: bool,
 83    pub is_truncated: bool,
 84    pub document_content: String,
 85    pub user_prompt: String,
 86    pub rewrite_section: Option<String>,
 87    pub diagnostic_errors: Vec<ContentPromptDiagnosticContext>,
 88}
 89
 90#[derive(Serialize)]
 91pub struct TerminalAssistantPromptContext {
 92    pub os: String,
 93    pub arch: String,
 94    pub shell: Option<String>,
 95    pub working_directory: Option<String>,
 96    pub latest_output: Vec<String>,
 97    pub user_prompt: String,
 98}
 99
100pub struct PromptLoadingParams<'a> {
101    pub fs: Arc<dyn Fs>,
102    pub repo_path: Option<PathBuf>,
103    pub cx: &'a gpui::App,
104}
105
106pub struct PromptBuilder {
107    handlebars: Arc<Mutex<Handlebars<'static>>>,
108}
109
110impl PromptBuilder {
111    pub fn load(fs: Arc<dyn Fs>, stdout_is_a_pty: bool, cx: &mut App) -> Arc<Self> {
112        Self::new(Some(PromptLoadingParams {
113            fs: fs.clone(),
114            repo_path: stdout_is_a_pty
115                .then(|| std::env::current_dir().log_err())
116                .flatten(),
117            cx,
118        }))
119        .log_err()
120        .map(Arc::new)
121        .unwrap_or_else(|| Arc::new(Self::new(None).unwrap()))
122    }
123
124    pub fn new(loading_params: Option<PromptLoadingParams>) -> Result<Self> {
125        let mut handlebars = Handlebars::new();
126        Self::register_built_in_templates(&mut handlebars)?;
127
128        let handlebars = Arc::new(Mutex::new(handlebars));
129
130        if let Some(params) = loading_params {
131            Self::watch_fs_for_template_overrides(params, handlebars.clone());
132        }
133
134        Ok(Self { handlebars })
135    }
136
137    /// Watches the filesystem for changes to prompt template overrides.
138    ///
139    /// This function sets up a file watcher on the prompt templates directory. It performs
140    /// an initial scan of the directory and registers any existing template overrides.
141    /// Then it continuously monitors for changes, reloading templates as they are
142    /// modified or added.
143    ///
144    /// If the templates directory doesn't exist initially, it waits for it to be created.
145    /// If the directory is removed, it restores the built-in templates and waits for the
146    /// directory to be recreated.
147    ///
148    /// # Arguments
149    ///
150    /// * `params` - A `PromptLoadingParams` struct containing the filesystem, repository path,
151    ///   and application context.
152    /// * `handlebars` - An `Arc<Mutex<Handlebars>>` for registering and updating templates.
153    fn watch_fs_for_template_overrides(
154        params: PromptLoadingParams,
155        handlebars: Arc<Mutex<Handlebars<'static>>>,
156    ) {
157        let templates_dir = paths::prompt_overrides_dir(params.repo_path.as_deref());
158        params.cx.background_spawn(async move {
159            let Some(parent_dir) = templates_dir.parent() else {
160                return;
161            };
162
163            let mut found_dir_once = false;
164            loop {
165                // Check if the templates directory exists and handle its status
166                // If it exists, log its presence and check if it's a symlink
167                // If it doesn't exist:
168                //   - Log that we're using built-in prompts
169                //   - Check if it's a broken symlink and log if so
170                //   - Set up a watcher to detect when it's created
171                // After the first check, set the `found_dir_once` flag
172                // This allows us to avoid logging when looping back around after deleting the prompt overrides directory.
173                let dir_status = params.fs.is_dir(&templates_dir).await;
174                let symlink_status = params.fs.read_link(&templates_dir).await.ok();
175                if dir_status {
176                    let mut log_message = format!("Prompt template overrides directory found at {}", templates_dir.display());
177                    if let Some(target) = symlink_status {
178                        log_message.push_str(" -> ");
179                        log_message.push_str(&target.display().to_string());
180                    }
181                    log::info!("{}.", log_message);
182                } else {
183                    if !found_dir_once {
184                        log::info!("No prompt template overrides directory found at {}. Using built-in prompts.", templates_dir.display());
185                        if let Some(target) = symlink_status {
186                            log::info!("Symlink found pointing to {}, but target is invalid.", target.display());
187                        }
188                    }
189
190                    if params.fs.is_dir(parent_dir).await {
191                        let (mut changes, _watcher) = params.fs.watch(parent_dir, Duration::from_secs(1)).await;
192                        while let Some(changed_paths) = changes.next().await {
193                            if changed_paths.iter().any(|p| &p.path == &templates_dir) {
194                                let mut log_message = format!("Prompt template overrides directory detected at {}", templates_dir.display());
195                                if let Ok(target) = params.fs.read_link(&templates_dir).await {
196                                    log_message.push_str(" -> ");
197                                    log_message.push_str(&target.display().to_string());
198                                }
199                                log::info!("{}.", log_message);
200                                break;
201                            }
202                        }
203                    } else {
204                        return;
205                    }
206                }
207
208                found_dir_once = true;
209
210                // Initial scan of the prompt overrides directory
211                if let Ok(mut entries) = params.fs.read_dir(&templates_dir).await {
212                    while let Some(Ok(file_path)) = entries.next().await {
213                        if file_path.to_string_lossy().ends_with(".hbs") {
214                            if let Ok(content) = params.fs.load(&file_path).await {
215                                let file_name = file_path.file_stem().unwrap().to_string_lossy();
216                                log::debug!("Registering prompt template override: {}", file_name);
217                                handlebars.lock().register_template_string(&file_name, content).log_err();
218                            }
219                        }
220                    }
221                }
222
223                // Watch both the parent directory and the template overrides directory:
224                // - Monitor the parent directory to detect if the template overrides directory is deleted.
225                // - Monitor the template overrides directory to re-register templates when they change.
226                // Combine both watch streams into a single stream.
227                let (parent_changes, parent_watcher) = params.fs.watch(parent_dir, Duration::from_secs(1)).await;
228                let (changes, watcher) = params.fs.watch(&templates_dir, Duration::from_secs(1)).await;
229                let mut combined_changes = futures::stream::select(changes, parent_changes);
230
231                while let Some(changed_paths) = combined_changes.next().await {
232                    if changed_paths.iter().any(|p| &p.path == &templates_dir) {
233                        if !params.fs.is_dir(&templates_dir).await {
234                            log::info!("Prompt template overrides directory removed. Restoring built-in prompt templates.");
235                            Self::register_built_in_templates(&mut handlebars.lock()).log_err();
236                            break;
237                        }
238                    }
239                    for event in changed_paths {
240                        if event.path.starts_with(&templates_dir) && event.path.extension().map_or(false, |ext| ext == "hbs") {
241                            log::info!("Reloading prompt template override: {}", event.path.display());
242                            if let Some(content) = params.fs.load(&event.path).await.log_err() {
243                                let file_name = event.path.file_stem().unwrap().to_string_lossy();
244                                handlebars.lock().register_template_string(&file_name, content).log_err();
245                            }
246                        }
247                    }
248                }
249
250                drop(watcher);
251                drop(parent_watcher);
252            }
253        })
254            .detach();
255    }
256
257    fn register_built_in_templates(handlebars: &mut Handlebars) -> Result<()> {
258        for path in Assets.list("prompts")? {
259            if let Some(id) = path
260                .split('/')
261                .next_back()
262                .and_then(|s| s.strip_suffix(".hbs"))
263            {
264                if let Some(prompt) = Assets.load(path.as_ref()).log_err().flatten() {
265                    log::debug!("Registering built-in prompt template: {}", id);
266                    let prompt = String::from_utf8_lossy(prompt.as_ref());
267                    handlebars.register_template_string(id, LineEnding::normalize_cow(prompt))?
268                }
269            }
270        }
271
272        Ok(())
273    }
274
275    pub fn generate_assistant_system_prompt(
276        &self,
277        context: &ProjectContext,
278    ) -> Result<String, RenderError> {
279        self.handlebars
280            .lock()
281            .render("assistant_system_prompt", context)
282    }
283
284    pub fn generate_inline_transformation_prompt(
285        &self,
286        user_prompt: String,
287        language_name: Option<&LanguageName>,
288        buffer: BufferSnapshot,
289        range: Range<usize>,
290    ) -> Result<String, RenderError> {
291        let content_type = match language_name.as_ref().map(|l| l.as_ref()) {
292            None | Some("Markdown" | "Plain Text") => "text",
293            Some(_) => "code",
294        };
295
296        const MAX_CTX: usize = 50000;
297        let is_insert = range.is_empty();
298        let mut is_truncated = false;
299
300        let before_range = 0..range.start;
301        let truncated_before = if before_range.len() > MAX_CTX {
302            is_truncated = true;
303            let start = buffer.clip_offset(range.start - MAX_CTX, text::Bias::Right);
304            start..range.start
305        } else {
306            before_range
307        };
308
309        let after_range = range.end..buffer.len();
310        let truncated_after = if after_range.len() > MAX_CTX {
311            is_truncated = true;
312            let end = buffer.clip_offset(range.end + MAX_CTX, text::Bias::Left);
313            range.end..end
314        } else {
315            after_range
316        };
317
318        let mut document_content = String::new();
319        for chunk in buffer.text_for_range(truncated_before) {
320            document_content.push_str(chunk);
321        }
322        if is_insert {
323            document_content.push_str("<insert_here></insert_here>");
324        } else {
325            document_content.push_str("<rewrite_this>\n");
326            for chunk in buffer.text_for_range(range.clone()) {
327                document_content.push_str(chunk);
328            }
329            document_content.push_str("\n</rewrite_this>");
330        }
331        for chunk in buffer.text_for_range(truncated_after) {
332            document_content.push_str(chunk);
333        }
334
335        let rewrite_section = if !is_insert {
336            let mut section = String::new();
337            for chunk in buffer.text_for_range(range.clone()) {
338                section.push_str(chunk);
339            }
340            Some(section)
341        } else {
342            None
343        };
344        let diagnostics = buffer.diagnostics_in_range::<_, Point>(range, false);
345        let diagnostic_errors: Vec<ContentPromptDiagnosticContext> = diagnostics
346            .map(|entry| {
347                let start = entry.range.start;
348                ContentPromptDiagnosticContext {
349                    line_number: (start.row + 1) as usize,
350                    error_message: entry.diagnostic.message.clone(),
351                    code_content: buffer.text_for_range(entry.range.clone()).collect(),
352                }
353            })
354            .collect();
355
356        let context = ContentPromptContext {
357            content_type: content_type.to_string(),
358            language_name: language_name.map(|s| s.to_string()),
359            is_insert,
360            is_truncated,
361            document_content,
362            user_prompt,
363            rewrite_section,
364            diagnostic_errors,
365        };
366        self.handlebars.lock().render("content_prompt", &context)
367    }
368
369    pub fn generate_terminal_assistant_prompt(
370        &self,
371        user_prompt: &str,
372        shell: Option<&str>,
373        working_directory: Option<&str>,
374        latest_output: &[String],
375    ) -> Result<String, RenderError> {
376        let context = TerminalAssistantPromptContext {
377            os: std::env::consts::OS.to_string(),
378            arch: std::env::consts::ARCH.to_string(),
379            shell: shell.map(|s| s.to_string()),
380            working_directory: working_directory.map(|s| s.to_string()),
381            latest_output: latest_output.to_vec(),
382            user_prompt: user_prompt.to_string(),
383        };
384
385        self.handlebars
386            .lock()
387            .render("terminal_assistant_prompt", &context)
388    }
389
390    pub fn generate_suggest_edits_prompt(&self) -> Result<String, RenderError> {
391        self.handlebars.lock().render("suggest_edits", &())
392    }
393}
394
395#[cfg(test)]
396mod test {
397    use super::*;
398    use uuid::Uuid;
399
400    #[test]
401    fn test_assistant_system_prompt_renders() {
402        let worktrees = vec![WorktreeContext {
403            root_name: "path".into(),
404            rules_file: Some(RulesFileContext {
405                path_in_worktree: Path::new(".rules").into(),
406                abs_path: Path::new("/some/path/.rules").into(),
407                text: "".into(),
408            }),
409        }];
410        let default_user_rules = vec![UserRulesContext {
411            uuid: UserPromptId(Uuid::nil()),
412            title: Some("Rules title".into()),
413            contents: "Rules contents".into(),
414        }];
415        let project_context = ProjectContext::new(worktrees, default_user_rules);
416        PromptBuilder::new(None)
417            .unwrap()
418            .generate_assistant_system_prompt(&project_context)
419            .unwrap();
420    }
421}