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