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