1use crate::schema::json_schema_for;
2use anyhow::{Result, anyhow};
3use assistant_tool::{ActionLog, Tool, ToolResult};
4use gpui::{AnyWindowHandle, App, Entity, Task};
5use language::{DiagnosticSeverity, OffsetRangeExt};
6use language_model::{LanguageModel, LanguageModelRequest, LanguageModelToolSchemaFormat};
7use project::Project;
8use schemars::JsonSchema;
9use serde::{Deserialize, Serialize};
10use std::{fmt::Write, path::Path, sync::Arc};
11use ui::IconName;
12use util::markdown::MarkdownInlineCode;
13
14#[derive(Debug, Serialize, Deserialize, JsonSchema)]
15pub struct DiagnosticsToolInput {
16 /// The path to get diagnostics for. If not provided, returns a project-wide summary.
17 ///
18 /// This path should never be absolute, and the first component
19 /// of the path should always be a root directory in a project.
20 ///
21 /// <example>
22 /// If the project has the following root directories:
23 ///
24 /// - lorem
25 /// - ipsum
26 ///
27 /// If you wanna access diagnostics for `dolor.txt` in `ipsum`, you should use the path `ipsum/dolor.txt`.
28 /// </example>
29 #[serde(deserialize_with = "deserialize_path")]
30 pub path: Option<String>,
31}
32
33fn deserialize_path<'de, D>(deserializer: D) -> Result<Option<String>, D::Error>
34where
35 D: serde::Deserializer<'de>,
36{
37 let opt = Option::<String>::deserialize(deserializer)?;
38 // The model passes an empty string sometimes
39 Ok(opt.filter(|s| !s.is_empty()))
40}
41
42pub struct DiagnosticsTool;
43
44impl Tool for DiagnosticsTool {
45 type Input = DiagnosticsToolInput;
46
47 fn name(&self) -> String {
48 "diagnostics".into()
49 }
50
51 fn needs_confirmation(&self, _: &Self::Input, _: &App) -> bool {
52 false
53 }
54
55 fn may_perform_edits(&self) -> bool {
56 false
57 }
58
59 fn description(&self) -> String {
60 include_str!("./diagnostics_tool/description.md").into()
61 }
62
63 fn icon(&self) -> IconName {
64 IconName::XCircle
65 }
66
67 fn input_schema(&self, format: LanguageModelToolSchemaFormat) -> Result<serde_json::Value> {
68 json_schema_for::<DiagnosticsToolInput>(format)
69 }
70
71 fn ui_text(&self, input: &Self::Input) -> String {
72 if let Some(path) = input.path.as_ref().filter(|p| !p.is_empty()) {
73 format!("Check diagnostics for {}", MarkdownInlineCode(path))
74 } else {
75 "Check project diagnostics".to_string()
76 }
77 }
78
79 fn run(
80 self: Arc<Self>,
81 input: Self::Input,
82 _request: Arc<LanguageModelRequest>,
83 project: Entity<Project>,
84 action_log: Entity<ActionLog>,
85 _model: Arc<dyn LanguageModel>,
86 _window: Option<AnyWindowHandle>,
87 cx: &mut App,
88 ) -> ToolResult {
89 match input.path {
90 Some(path) if !path.is_empty() => {
91 let Some(project_path) = project.read(cx).find_project_path(&path, cx) else {
92 return Task::ready(Err(anyhow!("Could not find path {path} in project",)))
93 .into();
94 };
95
96 let buffer =
97 project.update(cx, |project, cx| project.open_buffer(project_path, cx));
98
99 cx.spawn(async move |cx| {
100 let mut output = String::new();
101 let buffer = buffer.await?;
102 let snapshot = buffer.read_with(cx, |buffer, _cx| buffer.snapshot())?;
103
104 for (_, group) in snapshot.diagnostic_groups(None) {
105 let entry = &group.entries[group.primary_ix];
106 let range = entry.range.to_point(&snapshot);
107 let severity = match entry.diagnostic.severity {
108 DiagnosticSeverity::ERROR => "error",
109 DiagnosticSeverity::WARNING => "warning",
110 _ => continue,
111 };
112
113 writeln!(
114 output,
115 "{} at line {}: {}",
116 severity,
117 range.start.row + 1,
118 entry.diagnostic.message
119 )?;
120 }
121
122 if output.is_empty() {
123 Ok("File doesn't have errors or warnings!".to_string().into())
124 } else {
125 Ok(output.into())
126 }
127 })
128 .into()
129 }
130 _ => {
131 let project = project.read(cx);
132 let mut output = String::new();
133 let mut has_diagnostics = false;
134
135 for (project_path, _, summary) in project.diagnostic_summaries(true, cx) {
136 if summary.error_count > 0 || summary.warning_count > 0 {
137 let Some(worktree) = project.worktree_for_id(project_path.worktree_id, cx)
138 else {
139 continue;
140 };
141
142 has_diagnostics = true;
143 output.push_str(&format!(
144 "{}: {} error(s), {} warning(s)\n",
145 Path::new(worktree.read(cx).root_name())
146 .join(project_path.path)
147 .display(),
148 summary.error_count,
149 summary.warning_count
150 ));
151 }
152 }
153
154 action_log.update(cx, |action_log, _cx| {
155 action_log.checked_project_diagnostics();
156 });
157
158 if has_diagnostics {
159 Task::ready(Ok(output.into())).into()
160 } else {
161 Task::ready(Ok("No errors or warnings found in the project."
162 .to_string()
163 .into()))
164 .into()
165 }
166 }
167 }
168 }
169}