diagnostics.go

  1package tools
  2
  3import (
  4	"context"
  5	_ "embed"
  6	"fmt"
  7	"log/slog"
  8	"sort"
  9	"strings"
 10	"sync"
 11	"time"
 12
 13	"charm.land/fantasy"
 14	"github.com/charmbracelet/crush/internal/lsp"
 15	"github.com/charmbracelet/x/powernap/pkg/lsp/protocol"
 16)
 17
 18type DiagnosticsParams struct {
 19	FilePath string `json:"file_path,omitempty" description:"The path to the file to get diagnostics for (leave empty for project diagnostics)"`
 20}
 21
 22const DiagnosticsToolName = "lsp_diagnostics"
 23
 24//go:embed diagnostics.md
 25var diagnosticsDescription []byte
 26
 27func NewDiagnosticsTool(lspManager *lsp.Manager) fantasy.AgentTool {
 28	return fantasy.NewAgentTool(
 29		DiagnosticsToolName,
 30		string(diagnosticsDescription),
 31		func(ctx context.Context, params DiagnosticsParams, call fantasy.ToolCall) (fantasy.ToolResponse, error) {
 32			if lspManager.Clients().Len() == 0 {
 33				return fantasy.NewTextErrorResponse("no LSP clients available"), nil
 34			}
 35			notifyLSPs(ctx, lspManager, params.FilePath)
 36			output := getDiagnostics(params.FilePath, lspManager)
 37			return fantasy.NewTextResponse(output), nil
 38		})
 39}
 40
 41// openInLSPs ensures LSP servers are running and aware of the file, but does
 42// not notify changes or wait for fresh diagnostics. Use this for read-only
 43// operations like view where the file content hasn't changed.
 44func openInLSPs(
 45	ctx context.Context,
 46	manager *lsp.Manager,
 47	filepath string,
 48) {
 49	if filepath == "" || manager == nil {
 50		return
 51	}
 52
 53	manager.Start(ctx, filepath)
 54
 55	for client := range manager.Clients().Seq() {
 56		if !client.HandlesFile(filepath) {
 57			continue
 58		}
 59		_ = client.OpenFileOnDemand(ctx, filepath)
 60	}
 61}
 62
 63// waitForLSPDiagnostics waits briefly for diagnostics publication after a file
 64// has been opened. Intended for read-only situations where viewing up-to-date
 65// files matters but latency should remain low (i.e. when using the view tool).
 66func waitForLSPDiagnostics(
 67	ctx context.Context,
 68	manager *lsp.Manager,
 69	filepath string,
 70	timeout time.Duration,
 71) {
 72	if filepath == "" || manager == nil || timeout <= 0 {
 73		return
 74	}
 75
 76	var wg sync.WaitGroup
 77	for client := range manager.Clients().Seq() {
 78		if !client.HandlesFile(filepath) {
 79			continue
 80		}
 81		wg.Go(func() {
 82			client.WaitForDiagnostics(ctx, timeout)
 83		})
 84	}
 85	wg.Wait()
 86}
 87
 88// notifyLSPs notifies LSP servers that a file has changed and waits for
 89// updated diagnostics. Use this after edit/multiedit operations.
 90func notifyLSPs(
 91	ctx context.Context,
 92	manager *lsp.Manager,
 93	filepath string,
 94) {
 95	if filepath == "" || manager == nil {
 96		return
 97	}
 98
 99	manager.Start(ctx, filepath)
100
101	for client := range manager.Clients().Seq() {
102		if !client.HandlesFile(filepath) {
103			continue
104		}
105		_ = client.OpenFileOnDemand(ctx, filepath)
106		_ = client.NotifyChange(ctx, filepath)
107		client.WaitForDiagnostics(ctx, 5*time.Second)
108	}
109}
110
111func getDiagnostics(filePath string, manager *lsp.Manager) string {
112	if manager == nil {
113		return ""
114	}
115
116	var fileDiagnostics []string
117	var projectDiagnostics []string
118
119	for lspName, client := range manager.Clients().Seq2() {
120		for location, diags := range client.GetDiagnostics() {
121			path, err := location.Path()
122			if err != nil {
123				slog.Error("Failed to convert diagnostic location URI to path", "uri", location, "error", err)
124				continue
125			}
126			isCurrentFile := path == filePath
127			for _, diag := range diags {
128				formattedDiag := formatDiagnostic(path, diag, lspName)
129				if isCurrentFile {
130					fileDiagnostics = append(fileDiagnostics, formattedDiag)
131				} else {
132					projectDiagnostics = append(projectDiagnostics, formattedDiag)
133				}
134			}
135		}
136	}
137
138	sortDiagnostics(fileDiagnostics)
139	sortDiagnostics(projectDiagnostics)
140
141	var output strings.Builder
142	writeDiagnostics(&output, "file_diagnostics", fileDiagnostics)
143	writeDiagnostics(&output, "project_diagnostics", projectDiagnostics)
144
145	if len(fileDiagnostics) > 0 || len(projectDiagnostics) > 0 {
146		fileErrors := countSeverity(fileDiagnostics, "Error")
147		fileWarnings := countSeverity(fileDiagnostics, "Warn")
148		projectErrors := countSeverity(projectDiagnostics, "Error")
149		projectWarnings := countSeverity(projectDiagnostics, "Warn")
150		output.WriteString("\n<diagnostic_summary>\n")
151		fmt.Fprintf(&output, "Current file: %d errors, %d warnings\n", fileErrors, fileWarnings)
152		fmt.Fprintf(&output, "Project: %d errors, %d warnings\n", projectErrors, projectWarnings)
153		output.WriteString("</diagnostic_summary>\n")
154	}
155
156	out := output.String()
157	slog.Debug("Diagnostics", "output", out)
158	return out
159}
160
161func writeDiagnostics(output *strings.Builder, tag string, in []string) {
162	if len(in) == 0 {
163		return
164	}
165	output.WriteString("\n<" + tag + ">\n")
166	if len(in) > 10 {
167		output.WriteString(strings.Join(in[:10], "\n"))
168		fmt.Fprintf(output, "\n... and %d more diagnostics", len(in)-10)
169	} else {
170		output.WriteString(strings.Join(in, "\n"))
171	}
172	output.WriteString("\n</" + tag + ">\n")
173}
174
175func sortDiagnostics(in []string) []string {
176	sort.Slice(in, func(i, j int) bool {
177		iIsError := strings.HasPrefix(in[i], "Error")
178		jIsError := strings.HasPrefix(in[j], "Error")
179		if iIsError != jIsError {
180			return iIsError // Errors come first
181		}
182		return in[i] < in[j] // Then alphabetically
183	})
184	return in
185}
186
187func formatDiagnostic(pth string, diagnostic protocol.Diagnostic, source string) string {
188	severity := "Info"
189	switch diagnostic.Severity {
190	case protocol.SeverityError:
191		severity = "Error"
192	case protocol.SeverityWarning:
193		severity = "Warn"
194	case protocol.SeverityHint:
195		severity = "Hint"
196	}
197
198	location := fmt.Sprintf("%s:%d:%d", pth, diagnostic.Range.Start.Line+1, diagnostic.Range.Start.Character+1)
199
200	sourceInfo := source
201	if diagnostic.Source != "" {
202		sourceInfo += " " + diagnostic.Source
203	}
204
205	codeInfo := ""
206	if diagnostic.Code != nil {
207		codeInfo = fmt.Sprintf("[%v]", diagnostic.Code)
208	}
209
210	tagsInfo := ""
211	if len(diagnostic.Tags) > 0 {
212		var tags []string
213		for _, tag := range diagnostic.Tags {
214			switch tag {
215			case protocol.Unnecessary:
216				tags = append(tags, "unnecessary")
217			case protocol.Deprecated:
218				tags = append(tags, "deprecated")
219			}
220		}
221		if len(tags) > 0 {
222			tagsInfo = fmt.Sprintf(" (%s)", strings.Join(tags, ", "))
223		}
224	}
225
226	return fmt.Sprintf("%s: %s [%s]%s%s %s",
227		severity,
228		location,
229		sourceInfo,
230		codeInfo,
231		tagsInfo,
232		diagnostic.Message)
233}
234
235func countSeverity(diagnostics []string, severity string) int {
236	count := 0
237	for _, diag := range diagnostics {
238		if strings.HasPrefix(diag, severity) {
239			count++
240		}
241	}
242	return count
243}