diagnostics.go 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. package tools
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "sort"
  7. "strings"
  8. "time"
  9. "github.com/kujtimiihoxha/termai/internal/lsp"
  10. "github.com/kujtimiihoxha/termai/internal/lsp/protocol"
  11. )
  12. type diagnosticsTool struct {
  13. lspClients map[string]*lsp.Client
  14. }
  15. const (
  16. DiagnosticsToolName = "diagnostics"
  17. )
  18. type DiagnosticsParams struct {
  19. FilePath string `json:"file_path"`
  20. }
  21. func (b *diagnosticsTool) Info() ToolInfo {
  22. return ToolInfo{
  23. Name: DiagnosticsToolName,
  24. Description: "Get diagnostics for a file and/or project.",
  25. Parameters: map[string]any{
  26. "file_path": map[string]any{
  27. "type": "string",
  28. "description": "The path to the file to get diagnostics for (leave w empty for project diagnostics)",
  29. },
  30. },
  31. Required: []string{},
  32. }
  33. }
  34. func (b *diagnosticsTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
  35. var params DiagnosticsParams
  36. if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
  37. return NewTextErrorResponse(fmt.Sprintf("error parsing parameters: %s", err)), nil
  38. }
  39. lsps := b.lspClients
  40. if len(lsps) == 0 {
  41. return NewTextErrorResponse("no LSP clients available"), nil
  42. }
  43. if params.FilePath == "" {
  44. notifyLspOpenFile(ctx, params.FilePath, lsps)
  45. }
  46. output := appendDiagnostics(params.FilePath, lsps)
  47. return NewTextResponse(output), nil
  48. }
  49. func notifyLspOpenFile(ctx context.Context, filePath string, lsps map[string]*lsp.Client) {
  50. for _, client := range lsps {
  51. err := client.OpenFile(ctx, filePath)
  52. if err != nil {
  53. // Wait for the file to be opened and diagnostics to be received
  54. // TODO: see if we can do this in a more efficient way
  55. time.Sleep(2 * time.Second)
  56. }
  57. }
  58. }
  59. func appendDiagnostics(filePath string, lsps map[string]*lsp.Client) string {
  60. fileDiagnostics := []string{}
  61. projectDiagnostics := []string{}
  62. // Enhanced format function that includes more diagnostic information
  63. formatDiagnostic := func(pth string, diagnostic protocol.Diagnostic, source string) string {
  64. // Base components
  65. severity := "Info"
  66. switch diagnostic.Severity {
  67. case protocol.SeverityError:
  68. severity = "Error"
  69. case protocol.SeverityWarning:
  70. severity = "Warn"
  71. case protocol.SeverityHint:
  72. severity = "Hint"
  73. }
  74. // Location information
  75. location := fmt.Sprintf("%s:%d:%d", pth, diagnostic.Range.Start.Line+1, diagnostic.Range.Start.Character+1)
  76. // Source information (LSP name)
  77. sourceInfo := ""
  78. if diagnostic.Source != "" {
  79. sourceInfo = diagnostic.Source
  80. } else if source != "" {
  81. sourceInfo = source
  82. }
  83. // Code information
  84. codeInfo := ""
  85. if diagnostic.Code != nil {
  86. codeInfo = fmt.Sprintf("[%v]", diagnostic.Code)
  87. }
  88. // Tags information
  89. tagsInfo := ""
  90. if len(diagnostic.Tags) > 0 {
  91. tags := []string{}
  92. for _, tag := range diagnostic.Tags {
  93. switch tag {
  94. case protocol.Unnecessary:
  95. tags = append(tags, "unnecessary")
  96. case protocol.Deprecated:
  97. tags = append(tags, "deprecated")
  98. }
  99. }
  100. if len(tags) > 0 {
  101. tagsInfo = fmt.Sprintf(" (%s)", strings.Join(tags, ", "))
  102. }
  103. }
  104. // Assemble the full diagnostic message
  105. return fmt.Sprintf("%s: %s [%s]%s%s %s",
  106. severity,
  107. location,
  108. sourceInfo,
  109. codeInfo,
  110. tagsInfo,
  111. diagnostic.Message)
  112. }
  113. for lspName, client := range lsps {
  114. diagnostics := client.GetDiagnostics()
  115. if len(diagnostics) > 0 {
  116. for location, diags := range diagnostics {
  117. isCurrentFile := location.Path() == filePath
  118. // Group diagnostics by severity for better organization
  119. for _, diag := range diags {
  120. formattedDiag := formatDiagnostic(location.Path(), diag, lspName)
  121. if isCurrentFile {
  122. fileDiagnostics = append(fileDiagnostics, formattedDiag)
  123. } else {
  124. projectDiagnostics = append(projectDiagnostics, formattedDiag)
  125. }
  126. }
  127. }
  128. }
  129. }
  130. // Sort diagnostics by severity (errors first) and then by location
  131. sort.Slice(fileDiagnostics, func(i, j int) bool {
  132. iIsError := strings.HasPrefix(fileDiagnostics[i], "Error")
  133. jIsError := strings.HasPrefix(fileDiagnostics[j], "Error")
  134. if iIsError != jIsError {
  135. return iIsError // Errors come first
  136. }
  137. return fileDiagnostics[i] < fileDiagnostics[j] // Then alphabetically
  138. })
  139. sort.Slice(projectDiagnostics, func(i, j int) bool {
  140. iIsError := strings.HasPrefix(projectDiagnostics[i], "Error")
  141. jIsError := strings.HasPrefix(projectDiagnostics[j], "Error")
  142. if iIsError != jIsError {
  143. return iIsError
  144. }
  145. return projectDiagnostics[i] < projectDiagnostics[j]
  146. })
  147. output := ""
  148. if len(fileDiagnostics) > 0 {
  149. output += "\n<file_diagnostics>\n"
  150. if len(fileDiagnostics) > 10 {
  151. output += strings.Join(fileDiagnostics[:10], "\n")
  152. output += fmt.Sprintf("\n... and %d more diagnostics", len(fileDiagnostics)-10)
  153. } else {
  154. output += strings.Join(fileDiagnostics, "\n")
  155. }
  156. output += "\n</file_diagnostics>\n"
  157. }
  158. if len(projectDiagnostics) > 0 {
  159. output += "\n<project_diagnostics>\n"
  160. if len(projectDiagnostics) > 10 {
  161. output += strings.Join(projectDiagnostics[:10], "\n")
  162. output += fmt.Sprintf("\n... and %d more diagnostics", len(projectDiagnostics)-10)
  163. } else {
  164. output += strings.Join(projectDiagnostics, "\n")
  165. }
  166. output += "\n</project_diagnostics>\n"
  167. }
  168. // Add summary counts
  169. if len(fileDiagnostics) > 0 || len(projectDiagnostics) > 0 {
  170. fileErrors := countSeverity(fileDiagnostics, "Error")
  171. fileWarnings := countSeverity(fileDiagnostics, "Warn")
  172. projectErrors := countSeverity(projectDiagnostics, "Error")
  173. projectWarnings := countSeverity(projectDiagnostics, "Warn")
  174. output += "\n<diagnostic_summary>\n"
  175. output += fmt.Sprintf("Current file: %d errors, %d warnings\n", fileErrors, fileWarnings)
  176. output += fmt.Sprintf("Project: %d errors, %d warnings\n", projectErrors, projectWarnings)
  177. output += "</diagnostic_summary>\n"
  178. }
  179. return output
  180. }
  181. // Helper function to count diagnostics by severity
  182. func countSeverity(diagnostics []string, severity string) int {
  183. count := 0
  184. for _, diag := range diagnostics {
  185. if strings.HasPrefix(diag, severity) {
  186. count++
  187. }
  188. }
  189. return count
  190. }
  191. func NewDiagnosticsTool(lspClients map[string]*lsp.Client) BaseTool {
  192. return &diagnosticsTool{
  193. lspClients,
  194. }
  195. }