code_action_tool.rs

  1use anyhow::{Context as _, Result, anyhow};
  2use assistant_tool::{ActionLog, Tool, ToolResult};
  3use gpui::{App, Entity, Task};
  4use language::{self, Anchor, Buffer, ToPointUtf16};
  5use language_model::{LanguageModelRequestMessage, LanguageModelToolSchemaFormat};
  6use project::{self, LspAction, Project};
  7use regex::Regex;
  8use schemars::JsonSchema;
  9use serde::{Deserialize, Serialize};
 10use std::{ops::Range, sync::Arc};
 11use ui::IconName;
 12
 13use crate::schema::json_schema_for;
 14
 15#[derive(Debug, Serialize, Deserialize, JsonSchema)]
 16pub struct CodeActionToolInput {
 17    /// The relative path to the file containing the text range.
 18    ///
 19    /// WARNING: you MUST start this path with one of the project's root directories.
 20    pub path: String,
 21
 22    /// The specific code action to execute.
 23    ///
 24    /// If this field is provided, the tool will execute the specified action.
 25    /// If omitted, the tool will list all available code actions for the text range.
 26    ///
 27    /// Here are some actions that are commonly supported (but may not be for this particular
 28    /// text range; you can omit this field to list all the actions, if you want to know
 29    /// what your options are, or you can just try an action and if it fails I'll tell you
 30    /// what the available actions were instead):
 31    /// - "quickfix.all" - applies all available quick fixes in the range
 32    /// - "source.organizeImports" - sorts and cleans up import statements
 33    /// - "source.fixAll" - applies all available auto fixes
 34    /// - "refactor.extract" - extracts selected code into a new function or variable
 35    /// - "refactor.inline" - inlines a variable by replacing references with its value
 36    /// - "refactor.rewrite" - general code rewriting operations
 37    /// - "source.addMissingImports" - adds imports for references that lack them
 38    /// - "source.removeUnusedImports" - removes imports that aren't being used
 39    /// - "source.implementInterface" - generates methods required by an interface/trait
 40    /// - "source.generateAccessors" - creates getter/setter methods
 41    /// - "source.convertToAsyncFunction" - converts callback-style code to async/await
 42    ///
 43    /// Also, there is a special case: if you specify exactly "textDocument/rename" as the action,
 44    /// then this will rename the symbol to whatever string you specified for the `arguments` field.
 45    pub action: Option<String>,
 46
 47    /// Optional arguments to pass to the code action.
 48    ///
 49    /// For rename operations (when action="textDocument/rename"), this should contain the new name.
 50    /// For other code actions, these arguments may be passed to the language server.
 51    pub arguments: Option<serde_json::Value>,
 52
 53    /// The text that comes immediately before the text range in the file.
 54    pub context_before_range: String,
 55
 56    /// The text range. This text must appear in the file right between `context_before_range`
 57    /// and `context_after_range`.
 58    ///
 59    /// The file must contain exactly one occurrence of `context_before_range` followed by
 60    /// `text_range` followed by `context_after_range`. If the file contains zero occurrences,
 61    /// or if it contains more than one occurrence, the tool will fail, so it is absolutely
 62    /// critical that you verify ahead of time that the string is unique. You can search
 63    /// the file's contents to verify this ahead of time.
 64    ///
 65    /// To make the string more likely to be unique, include a minimum of 1 line of context
 66    /// before the text range, as well as a minimum of 1 line of context after the text range.
 67    /// If these lines of context are not enough to obtain a string that appears only once
 68    /// in the file, then double the number of context lines until the string becomes unique.
 69    /// (Start with 1 line before and 1 line after though, because too much context is
 70    /// needlessly costly.)
 71    ///
 72    /// Do not alter the context lines of code in any way, and make sure to preserve all
 73    /// whitespace and indentation for all lines of code. The combined string must be exactly
 74    /// as it appears in the file, or else this tool call will fail.
 75    pub text_range: String,
 76
 77    /// The text that comes immediately after the text range in the file.
 78    pub context_after_range: String,
 79}
 80
 81pub struct CodeActionTool;
 82
 83impl Tool for CodeActionTool {
 84    fn name(&self) -> String {
 85        "code_actions".into()
 86    }
 87
 88    fn needs_confirmation(&self, _input: &serde_json::Value, _cx: &App) -> bool {
 89        false
 90    }
 91
 92    fn description(&self) -> String {
 93        include_str!("./code_action_tool/description.md").into()
 94    }
 95
 96    fn icon(&self) -> IconName {
 97        IconName::Wand
 98    }
 99
100    fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
101        json_schema_for::<CodeActionToolInput>(format)
102    }
103
104    fn ui_text(&self, input: &serde_json::Value) -> String {
105        match serde_json::from_value::<CodeActionToolInput>(input.clone()) {
106            Ok(input) => {
107                if let Some(action) = &input.action {
108                    if action == "textDocument/rename" {
109                        let new_name = match &input.arguments {
110                            Some(serde_json::Value::String(new_name)) => new_name.clone(),
111                            Some(value) => {
112                                if let Ok(new_name) =
113                                    serde_json::from_value::<String>(value.clone())
114                                {
115                                    new_name
116                                } else {
117                                    "invalid name".to_string()
118                                }
119                            }
120                            None => "missing name".to_string(),
121                        };
122                        format!("Rename '{}' to '{}'", input.text_range, new_name)
123                    } else {
124                        format!(
125                            "Execute code action '{}' for '{}'",
126                            action, input.text_range
127                        )
128                    }
129                } else {
130                    format!("List available code actions for '{}'", input.text_range)
131                }
132            }
133            Err(_) => "Perform code action".to_string(),
134        }
135    }
136
137    fn run(
138        self: Arc<Self>,
139        input: serde_json::Value,
140        _messages: &[LanguageModelRequestMessage],
141        project: Entity<Project>,
142        action_log: Entity<ActionLog>,
143        cx: &mut App,
144    ) -> ToolResult {
145        let input = match serde_json::from_value::<CodeActionToolInput>(input) {
146            Ok(input) => input,
147            Err(err) => return Task::ready(Err(anyhow!(err))).into(),
148        };
149
150        cx.spawn(async move |cx| {
151            let buffer = {
152                let project_path = project.read_with(cx, |project, cx| {
153                    project
154                        .find_project_path(&input.path, cx)
155                        .context("Path not found in project")
156                })??;
157
158                project.update(cx, |project, cx| project.open_buffer(project_path, cx))?.await?
159            };
160
161            action_log.update(cx, |action_log, cx| {
162                action_log.track_buffer(buffer.clone(), cx);
163            })?;
164
165            let range = {
166                let Some(range) = buffer.read_with(cx, |buffer, _cx| {
167                    find_text_range(&buffer, &input.context_before_range, &input.text_range, &input.context_after_range)
168                })? else {
169                    return Err(anyhow!(
170                        "Failed to locate the text specified by context_before_range, text_range, and context_after_range. Make sure context_before_range and context_after_range each match exactly once in the file."
171                    ));
172                };
173
174                range
175            };
176
177            if let Some(action_type) = &input.action {
178                // Special-case the `rename` operation
179                let response = if action_type == "textDocument/rename" {
180                    let Some(new_name) = input.arguments.and_then(|args| serde_json::from_value::<String>(args).ok()) else {
181                        return Err(anyhow!("For rename operations, 'arguments' must be a string containing the new name"));
182                    };
183
184                    let position = buffer.read_with(cx, |buffer, _| {
185                        range.start.to_point_utf16(&buffer.snapshot())
186                    })?;
187
188                    project
189                        .update(cx, |project, cx| {
190                            project.perform_rename(buffer.clone(), position, new_name.clone(), cx)
191                        })?
192                        .await?;
193
194                    format!("Renamed '{}' to '{}'", input.text_range, new_name)
195                } else {
196                    // Get code actions for the range
197                    let actions = project
198                        .update(cx, |project, cx| {
199                            project.code_actions(&buffer, range.clone(), None, cx)
200                        })?
201                        .await?;
202
203                    if actions.is_empty() {
204                        return Err(anyhow!("No code actions available for this range"));
205                    }
206
207                    // Find all matching actions
208                    let regex = match Regex::new(action_type) {
209                        Ok(regex) => regex,
210                        Err(err) => return Err(anyhow!("Invalid regex pattern: {}", err)),
211                    };
212                    let mut matching_actions = actions
213                        .into_iter()
214                        .filter(|action| { regex.is_match(action.lsp_action.title()) });
215
216                    let Some(action) = matching_actions.next() else {
217                        return Err(anyhow!("No code actions match the pattern: {}", action_type));
218                    };
219
220                    // There should have been exactly one matching action.
221                    if let Some(second) = matching_actions.next() {
222                        let mut all_matches = vec![action, second];
223
224                        all_matches.extend(matching_actions);
225
226                        return Err(anyhow!(
227                            "Pattern '{}' matches multiple code actions: {}",
228                            action_type,
229                            all_matches.into_iter().map(|action| action.lsp_action.title().to_string()).collect::<Vec<_>>().join(", ")
230                        ));
231                    }
232
233                    let title = action.lsp_action.title().to_string();
234
235                    project
236                        .update(cx, |project, cx| {
237                            project.apply_code_action(buffer.clone(), action, true, cx)
238                        })?
239                        .await?;
240
241                    format!("Completed code action: {}", title)
242                };
243
244                project
245                    .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))?
246                    .await?;
247
248                action_log.update(cx, |log, cx| {
249                    log.buffer_edited(buffer.clone(), cx)
250                })?;
251
252                Ok(response)
253            } else {
254                // No action specified, so list the available ones.
255                let (position_start, position_end) = buffer.read_with(cx, |buffer, _| {
256                    let snapshot = buffer.snapshot();
257                    (
258                        range.start.to_point_utf16(&snapshot),
259                        range.end.to_point_utf16(&snapshot)
260                    )
261                })?;
262
263                // Convert position to display coordinates (1-based)
264                let position_start_display = language::Point {
265                    row: position_start.row + 1,
266                    column: position_start.column + 1,
267                };
268
269                let position_end_display = language::Point {
270                    row: position_end.row + 1,
271                    column: position_end.column + 1,
272                };
273
274                // Get code actions for the range
275                let actions = project
276                    .update(cx, |project, cx| {
277                        project.code_actions(&buffer, range.clone(), None, cx)
278                    })?
279                    .await?;
280
281                let mut response = format!(
282                    "Available code actions for text range '{}' at position {}:{} to {}:{} (UTF-16 coordinates):\n\n",
283                    input.text_range,
284                    position_start_display.row, position_start_display.column,
285                    position_end_display.row, position_end_display.column
286                );
287
288                if actions.is_empty() {
289                    response.push_str("No code actions available for this range.");
290                } else {
291                    for (i, action) in actions.iter().enumerate() {
292                        let title = match &action.lsp_action {
293                            LspAction::Action(code_action) => code_action.title.as_str(),
294                            LspAction::Command(command) => command.title.as_str(),
295                            LspAction::CodeLens(code_lens) => {
296                                if let Some(cmd) = &code_lens.command {
297                                    cmd.title.as_str()
298                                } else {
299                                    "Unknown code lens"
300                                }
301                            },
302                        };
303
304                        let kind = match &action.lsp_action {
305                            LspAction::Action(code_action) => {
306                                if let Some(kind) = &code_action.kind {
307                                    kind.as_str()
308                                } else {
309                                    "unknown"
310                                }
311                            },
312                            LspAction::Command(_) => "command",
313                            LspAction::CodeLens(_) => "code_lens",
314                        };
315
316                        response.push_str(&format!("{}. {title} ({kind})\n", i + 1));
317                    }
318                }
319
320                Ok(response)
321            }
322        }).into()
323    }
324}
325
326/// Finds the range of the text in the buffer, if it appears between context_before_range
327/// and context_after_range, and if that combined string has one unique result in the buffer.
328///
329/// If an exact match fails, it tries adding a newline to the end of context_before_range and
330/// to the beginning of context_after_range to accommodate line-based context matching.
331fn find_text_range(
332    buffer: &Buffer,
333    context_before_range: &str,
334    text_range: &str,
335    context_after_range: &str,
336) -> Option<Range<Anchor>> {
337    let snapshot = buffer.snapshot();
338    let text = snapshot.text();
339
340    // First try with exact match
341    let search_string = format!("{context_before_range}{text_range}{context_after_range}");
342    let mut positions = text.match_indices(&search_string);
343    let position_result = positions.next();
344
345    if let Some(position) = position_result {
346        // Check if the matched string is unique
347        if positions.next().is_none() {
348            let range_start = position.0 + context_before_range.len();
349            let range_end = range_start + text_range.len();
350            let range_start_anchor = snapshot.anchor_before(snapshot.offset_to_point(range_start));
351            let range_end_anchor = snapshot.anchor_before(snapshot.offset_to_point(range_end));
352
353            return Some(range_start_anchor..range_end_anchor);
354        }
355    }
356
357    // If exact match fails or is not unique, try with line-based context
358    // Add a newline to the end of before context and beginning of after context
359    let line_based_before = if context_before_range.ends_with('\n') {
360        context_before_range.to_string()
361    } else {
362        format!("{context_before_range}\n")
363    };
364
365    let line_based_after = if context_after_range.starts_with('\n') {
366        context_after_range.to_string()
367    } else {
368        format!("\n{context_after_range}")
369    };
370
371    let line_search_string = format!("{line_based_before}{text_range}{line_based_after}");
372    let mut line_positions = text.match_indices(&line_search_string);
373    let line_position = line_positions.next()?;
374
375    // The line-based search string must also appear exactly once
376    if line_positions.next().is_some() {
377        return None;
378    }
379
380    let line_range_start = line_position.0 + line_based_before.len();
381    let line_range_end = line_range_start + text_range.len();
382    let line_range_start_anchor =
383        snapshot.anchor_before(snapshot.offset_to_point(line_range_start));
384    let line_range_end_anchor = snapshot.anchor_before(snapshot.offset_to_point(line_range_end));
385
386    Some(line_range_start_anchor..line_range_end_anchor)
387}