1use anyhow::{Context as _, Result, anyhow};
2use assistant_tool::{ActionLog, Tool};
3use gpui::{App, Entity, Task};
4use language::{self, Anchor, Buffer, ToPointUtf16};
5use language_model::LanguageModelRequestMessage;
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(
101 &self,
102 format: language_model::LanguageModelToolSchemaFormat,
103 ) -> serde_json::Value {
104 json_schema_for::<CodeActionToolInput>(format)
105 }
106
107 fn ui_text(&self, input: &serde_json::Value) -> String {
108 match serde_json::from_value::<CodeActionToolInput>(input.clone()) {
109 Ok(input) => {
110 if let Some(action) = &input.action {
111 if action == "textDocument/rename" {
112 let new_name = match &input.arguments {
113 Some(serde_json::Value::String(new_name)) => new_name.clone(),
114 Some(value) => {
115 if let Ok(new_name) =
116 serde_json::from_value::<String>(value.clone())
117 {
118 new_name
119 } else {
120 "invalid name".to_string()
121 }
122 }
123 None => "missing name".to_string(),
124 };
125 format!("Rename '{}' to '{}'", input.text_range, new_name)
126 } else {
127 format!(
128 "Execute code action '{}' for '{}'",
129 action, input.text_range
130 )
131 }
132 } else {
133 format!("List available code actions for '{}'", input.text_range)
134 }
135 }
136 Err(_) => "Perform code action".to_string(),
137 }
138 }
139
140 fn run(
141 self: Arc<Self>,
142 input: serde_json::Value,
143 _messages: &[LanguageModelRequestMessage],
144 project: Entity<Project>,
145 action_log: Entity<ActionLog>,
146 cx: &mut App,
147 ) -> Task<Result<String>> {
148 let input = match serde_json::from_value::<CodeActionToolInput>(input) {
149 Ok(input) => input,
150 Err(err) => return Task::ready(Err(anyhow!(err))),
151 };
152
153 cx.spawn(async move |cx| {
154 let buffer = {
155 let project_path = project.read_with(cx, |project, cx| {
156 project
157 .find_project_path(&input.path, cx)
158 .context("Path not found in project")
159 })??;
160
161 project.update(cx, |project, cx| project.open_buffer(project_path, cx))?.await?
162 };
163
164 action_log.update(cx, |action_log, cx| {
165 action_log.buffer_read(buffer.clone(), cx);
166 })?;
167
168 let range = {
169 let Some(range) = buffer.read_with(cx, |buffer, _cx| {
170 find_text_range(&buffer, &input.context_before_range, &input.text_range, &input.context_after_range)
171 })? else {
172 return Err(anyhow!(
173 "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."
174 ));
175 };
176
177 range
178 };
179
180 if let Some(action_type) = &input.action {
181 // Special-case the `rename` operation
182 let response = if action_type == "textDocument/rename" {
183 let Some(new_name) = input.arguments.and_then(|args| serde_json::from_value::<String>(args).ok()) else {
184 return Err(anyhow!("For rename operations, 'arguments' must be a string containing the new name"));
185 };
186
187 let position = buffer.read_with(cx, |buffer, _| {
188 range.start.to_point_utf16(&buffer.snapshot())
189 })?;
190
191 project
192 .update(cx, |project, cx| {
193 project.perform_rename(buffer.clone(), position, new_name.clone(), cx)
194 })?
195 .await?;
196
197 format!("Renamed '{}' to '{}'", input.text_range, new_name)
198 } else {
199 // Get code actions for the range
200 let actions = project
201 .update(cx, |project, cx| {
202 project.code_actions(&buffer, range.clone(), None, cx)
203 })?
204 .await?;
205
206 if actions.is_empty() {
207 return Err(anyhow!("No code actions available for this range"));
208 }
209
210 // Find all matching actions
211 let regex = match Regex::new(action_type) {
212 Ok(regex) => regex,
213 Err(err) => return Err(anyhow!("Invalid regex pattern: {}", err)),
214 };
215 let mut matching_actions = actions
216 .into_iter()
217 .filter(|action| { regex.is_match(action.lsp_action.title()) });
218
219 let Some(action) = matching_actions.next() else {
220 return Err(anyhow!("No code actions match the pattern: {}", action_type));
221 };
222
223 // There should have been exactly one matching action.
224 if let Some(second) = matching_actions.next() {
225 let mut all_matches = vec![action, second];
226
227 all_matches.extend(matching_actions);
228
229 return Err(anyhow!(
230 "Pattern '{}' matches multiple code actions: {}",
231 action_type,
232 all_matches.into_iter().map(|action| action.lsp_action.title().to_string()).collect::<Vec<_>>().join(", ")
233 ));
234 }
235
236 let title = action.lsp_action.title().to_string();
237
238 project
239 .update(cx, |project, cx| {
240 project.apply_code_action(buffer.clone(), action, true, cx)
241 })?
242 .await?;
243
244 format!("Completed code action: {}", title)
245 };
246
247 project
248 .update(cx, |project, cx| project.save_buffer(buffer.clone(), cx))?
249 .await?;
250
251 action_log.update(cx, |log, cx| {
252 log.buffer_edited(buffer.clone(), cx)
253 })?;
254
255 Ok(response)
256 } else {
257 // No action specified, so list the available ones.
258 let (position_start, position_end) = buffer.read_with(cx, |buffer, _| {
259 let snapshot = buffer.snapshot();
260 (
261 range.start.to_point_utf16(&snapshot),
262 range.end.to_point_utf16(&snapshot)
263 )
264 })?;
265
266 // Convert position to display coordinates (1-based)
267 let position_start_display = language::Point {
268 row: position_start.row + 1,
269 column: position_start.column + 1,
270 };
271
272 let position_end_display = language::Point {
273 row: position_end.row + 1,
274 column: position_end.column + 1,
275 };
276
277 // Get code actions for the range
278 let actions = project
279 .update(cx, |project, cx| {
280 project.code_actions(&buffer, range.clone(), None, cx)
281 })?
282 .await?;
283
284 let mut response = format!(
285 "Available code actions for text range '{}' at position {}:{} to {}:{} (UTF-16 coordinates):\n\n",
286 input.text_range,
287 position_start_display.row, position_start_display.column,
288 position_end_display.row, position_end_display.column
289 );
290
291 if actions.is_empty() {
292 response.push_str("No code actions available for this range.");
293 } else {
294 for (i, action) in actions.iter().enumerate() {
295 let title = match &action.lsp_action {
296 LspAction::Action(code_action) => code_action.title.as_str(),
297 LspAction::Command(command) => command.title.as_str(),
298 LspAction::CodeLens(code_lens) => {
299 if let Some(cmd) = &code_lens.command {
300 cmd.title.as_str()
301 } else {
302 "Unknown code lens"
303 }
304 },
305 };
306
307 let kind = match &action.lsp_action {
308 LspAction::Action(code_action) => {
309 if let Some(kind) = &code_action.kind {
310 kind.as_str()
311 } else {
312 "unknown"
313 }
314 },
315 LspAction::Command(_) => "command",
316 LspAction::CodeLens(_) => "code_lens",
317 };
318
319 response.push_str(&format!("{}. {title} ({kind})\n", i + 1));
320 }
321 }
322
323 Ok(response)
324 }
325 })
326 }
327}
328
329/// Finds the range of the text in the buffer, if it appears between context_before_range
330/// and context_after_range, and if that combined string has one unique result in the buffer.
331///
332/// If an exact match fails, it tries adding a newline to the end of context_before_range and
333/// to the beginning of context_after_range to accommodate line-based context matching.
334fn find_text_range(
335 buffer: &Buffer,
336 context_before_range: &str,
337 text_range: &str,
338 context_after_range: &str,
339) -> Option<Range<Anchor>> {
340 let snapshot = buffer.snapshot();
341 let text = snapshot.text();
342
343 // First try with exact match
344 let search_string = format!("{context_before_range}{text_range}{context_after_range}");
345 let mut positions = text.match_indices(&search_string);
346 let position_result = positions.next();
347
348 if let Some(position) = position_result {
349 // Check if the matched string is unique
350 if positions.next().is_none() {
351 let range_start = position.0 + context_before_range.len();
352 let range_end = range_start + text_range.len();
353 let range_start_anchor = snapshot.anchor_before(snapshot.offset_to_point(range_start));
354 let range_end_anchor = snapshot.anchor_before(snapshot.offset_to_point(range_end));
355
356 return Some(range_start_anchor..range_end_anchor);
357 }
358 }
359
360 // If exact match fails or is not unique, try with line-based context
361 // Add a newline to the end of before context and beginning of after context
362 let line_based_before = if context_before_range.ends_with('\n') {
363 context_before_range.to_string()
364 } else {
365 format!("{context_before_range}\n")
366 };
367
368 let line_based_after = if context_after_range.starts_with('\n') {
369 context_after_range.to_string()
370 } else {
371 format!("\n{context_after_range}")
372 };
373
374 let line_search_string = format!("{line_based_before}{text_range}{line_based_after}");
375 let mut line_positions = text.match_indices(&line_search_string);
376 let line_position = line_positions.next()?;
377
378 // The line-based search string must also appear exactly once
379 if line_positions.next().is_some() {
380 return None;
381 }
382
383 let line_range_start = line_position.0 + line_based_before.len();
384 let line_range_end = line_range_start + text_range.len();
385 let line_range_start_anchor =
386 snapshot.anchor_before(snapshot.offset_to_point(line_range_start));
387 let line_range_end_anchor = snapshot.anchor_before(snapshot.offset_to_point(line_range_end));
388
389 Some(line_range_start_anchor..line_range_end_anchor)
390}