diagnostics.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. package tools
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "maps"
  7. "sort"
  8. "strings"
  9. "time"
  10. "github.com/kujtimiihoxha/termai/internal/lsp"
  11. "github.com/kujtimiihoxha/termai/internal/lsp/protocol"
  12. )
  13. type diagnosticsTool struct {
  14. lspClients map[string]*lsp.Client
  15. }
  16. const (
  17. DiagnosticsToolName = "diagnostics"
  18. )
  19. type DiagnosticsParams struct {
  20. FilePath string `json:"file_path"`
  21. }
  22. func (b *diagnosticsTool) Info() ToolInfo {
  23. return ToolInfo{
  24. Name: DiagnosticsToolName,
  25. Description: "Get diagnostics for a file and/or project.",
  26. Parameters: map[string]any{
  27. "file_path": map[string]any{
  28. "type": "string",
  29. "description": "The path to the file to get diagnostics for (leave w empty for project diagnostics)",
  30. },
  31. },
  32. Required: []string{},
  33. }
  34. }
  35. func (b *diagnosticsTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
  36. var params DiagnosticsParams
  37. if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
  38. return NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
  39. }
  40. lsps := b.lspClients
  41. if len(lsps) == 0 {
  42. return NewTextErrorResponse("no LSP clients available"), nil
  43. }
  44. if params.FilePath != "" {
  45. notifyLspOpenFile(ctx, params.FilePath, lsps)
  46. }
  47. output := appendDiagnostics(params.FilePath, lsps)
  48. return NewTextResponse(output), nil
  49. }
  50. func notifyLspOpenFile(ctx context.Context, filePath string, lsps map[string]*lsp.Client) {
  51. // Create a channel to receive diagnostic notifications
  52. diagChan := make(chan struct{}, 1)
  53. // Register a temporary diagnostic handler for each client
  54. for _, client := range lsps {
  55. // Store the original diagnostics map to detect changes
  56. originalDiags := make(map[protocol.DocumentUri][]protocol.Diagnostic)
  57. maps.Copy(originalDiags, client.GetDiagnostics())
  58. // Create a notification handler that will signal when diagnostics are received
  59. handler := func(params json.RawMessage) {
  60. lsp.HandleDiagnostics(client, params)
  61. var diagParams protocol.PublishDiagnosticsParams
  62. if err := json.Unmarshal(params, &diagParams); err != nil {
  63. return
  64. }
  65. // If this is for our file or we've received any new diagnostics, signal completion
  66. if diagParams.URI.Path() == filePath || hasDiagnosticsChanged(client.GetDiagnostics(), originalDiags) {
  67. select {
  68. case diagChan <- struct{}{}:
  69. // Signal sent
  70. default:
  71. // Channel already has a value, no need to send again
  72. }
  73. }
  74. }
  75. // Register our temporary handler
  76. client.RegisterNotificationHandler("textDocument/publishDiagnostics", handler)
  77. // Open the file
  78. err := client.OpenFile(ctx, filePath)
  79. if err != nil {
  80. // If there's an error opening the file, continue to the next client
  81. continue
  82. }
  83. }
  84. // Wait for diagnostics with a reasonable timeout
  85. select {
  86. case <-diagChan:
  87. // Diagnostics received
  88. case <-time.After(10 * time.Second):
  89. // Timeout after 5 seconds - this is a fallback in case no diagnostics are published
  90. case <-ctx.Done():
  91. // Context cancelled
  92. }
  93. // Note: We're not unregistering our handler because the Client.RegisterNotificationHandler
  94. // replaces any existing handler, and we'll be replaced by the original handler when
  95. // the LSP client is reinitialized or when a new handler is registered.
  96. }
  97. // hasDiagnosticsChanged checks if there are any new diagnostics compared to the original set
  98. func hasDiagnosticsChanged(current, original map[protocol.DocumentUri][]protocol.Diagnostic) bool {
  99. for uri, diags := range current {
  100. origDiags, exists := original[uri]
  101. if !exists || len(diags) != len(origDiags) {
  102. return true
  103. }
  104. }
  105. return false
  106. }
  107. func appendDiagnostics(filePath string, lsps map[string]*lsp.Client) string {
  108. fileDiagnostics := []string{}
  109. projectDiagnostics := []string{}
  110. // Enhanced format function that includes more diagnostic information
  111. formatDiagnostic := func(pth string, diagnostic protocol.Diagnostic, source string) string {
  112. // Base components
  113. severity := "Info"
  114. switch diagnostic.Severity {
  115. case protocol.SeverityError:
  116. severity = "Error"
  117. case protocol.SeverityWarning:
  118. severity = "Warn"
  119. case protocol.SeverityHint:
  120. severity = "Hint"
  121. }
  122. // Location information
  123. location := fmt.Sprintf("%s:%d:%d", pth, diagnostic.Range.Start.Line+1, diagnostic.Range.Start.Character+1)
  124. // Source information (LSP name)
  125. sourceInfo := ""
  126. if diagnostic.Source != "" {
  127. sourceInfo = diagnostic.Source
  128. } else if source != "" {
  129. sourceInfo = source
  130. }
  131. // Code information
  132. codeInfo := ""
  133. if diagnostic.Code != nil {
  134. codeInfo = fmt.Sprintf("[%v]", diagnostic.Code)
  135. }
  136. // Tags information
  137. tagsInfo := ""
  138. if len(diagnostic.Tags) > 0 {
  139. tags := []string{}
  140. for _, tag := range diagnostic.Tags {
  141. switch tag {
  142. case protocol.Unnecessary:
  143. tags = append(tags, "unnecessary")
  144. case protocol.Deprecated:
  145. tags = append(tags, "deprecated")
  146. }
  147. }
  148. if len(tags) > 0 {
  149. tagsInfo = fmt.Sprintf(" (%s)", strings.Join(tags, ", "))
  150. }
  151. }
  152. // Assemble the full diagnostic message
  153. return fmt.Sprintf("%s: %s [%s]%s%s %s",
  154. severity,
  155. location,
  156. sourceInfo,
  157. codeInfo,
  158. tagsInfo,
  159. diagnostic.Message)
  160. }
  161. for lspName, client := range lsps {
  162. diagnostics := client.GetDiagnostics()
  163. if len(diagnostics) > 0 {
  164. for location, diags := range diagnostics {
  165. isCurrentFile := location.Path() == filePath
  166. // Group diagnostics by severity for better organization
  167. for _, diag := range diags {
  168. formattedDiag := formatDiagnostic(location.Path(), diag, lspName)
  169. if isCurrentFile {
  170. fileDiagnostics = append(fileDiagnostics, formattedDiag)
  171. } else {
  172. projectDiagnostics = append(projectDiagnostics, formattedDiag)
  173. }
  174. }
  175. }
  176. }
  177. }
  178. // Sort diagnostics by severity (errors first) and then by location
  179. sort.Slice(fileDiagnostics, func(i, j int) bool {
  180. iIsError := strings.HasPrefix(fileDiagnostics[i], "Error")
  181. jIsError := strings.HasPrefix(fileDiagnostics[j], "Error")
  182. if iIsError != jIsError {
  183. return iIsError // Errors come first
  184. }
  185. return fileDiagnostics[i] < fileDiagnostics[j] // Then alphabetically
  186. })
  187. sort.Slice(projectDiagnostics, func(i, j int) bool {
  188. iIsError := strings.HasPrefix(projectDiagnostics[i], "Error")
  189. jIsError := strings.HasPrefix(projectDiagnostics[j], "Error")
  190. if iIsError != jIsError {
  191. return iIsError
  192. }
  193. return projectDiagnostics[i] < projectDiagnostics[j]
  194. })
  195. output := ""
  196. if len(fileDiagnostics) > 0 {
  197. output += "\n<file_diagnostics>\n"
  198. if len(fileDiagnostics) > 10 {
  199. output += strings.Join(fileDiagnostics[:10], "\n")
  200. output += fmt.Sprintf("\n... and %d more diagnostics", len(fileDiagnostics)-10)
  201. } else {
  202. output += strings.Join(fileDiagnostics, "\n")
  203. }
  204. output += "\n</file_diagnostics>\n"
  205. }
  206. if len(projectDiagnostics) > 0 {
  207. output += "\n<project_diagnostics>\n"
  208. if len(projectDiagnostics) > 10 {
  209. output += strings.Join(projectDiagnostics[:10], "\n")
  210. output += fmt.Sprintf("\n... and %d more diagnostics", len(projectDiagnostics)-10)
  211. } else {
  212. output += strings.Join(projectDiagnostics, "\n")
  213. }
  214. output += "\n</project_diagnostics>\n"
  215. }
  216. // Add summary counts
  217. if len(fileDiagnostics) > 0 || len(projectDiagnostics) > 0 {
  218. fileErrors := countSeverity(fileDiagnostics, "Error")
  219. fileWarnings := countSeverity(fileDiagnostics, "Warn")
  220. projectErrors := countSeverity(projectDiagnostics, "Error")
  221. projectWarnings := countSeverity(projectDiagnostics, "Warn")
  222. output += "\n<diagnostic_summary>\n"
  223. output += fmt.Sprintf("Current file: %d errors, %d warnings\n", fileErrors, fileWarnings)
  224. output += fmt.Sprintf("Project: %d errors, %d warnings\n", projectErrors, projectWarnings)
  225. output += "</diagnostic_summary>\n"
  226. }
  227. return output
  228. }
  229. // Helper function to count diagnostics by severity
  230. func countSeverity(diagnostics []string, severity string) int {
  231. count := 0
  232. for _, diag := range diagnostics {
  233. if strings.HasPrefix(diag, severity) {
  234. count++
  235. }
  236. }
  237. return count
  238. }
  239. func NewDiagnosticsTool(lspClients map[string]*lsp.Client) BaseTool {
  240. return &diagnosticsTool{
  241. lspClients,
  242. }
  243. }