prompts.rs

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