fix(lsp): return a copy of lsp diagnostics to avoid data race (#681)

Liiiz created

* fix(lsp): return a copy of lsp diagnostics to avoid data race

* Replace maps.Copy with maps.Clone

Change summary

internal/llm/tools/diagnostics.go | 4 +---
internal/lsp/client.go            | 6 +++++-
2 files changed, 6 insertions(+), 4 deletions(-)

Detailed changes

internal/llm/tools/diagnostics.go 🔗

@@ -5,7 +5,6 @@ import (
 	"encoding/json"
 	"fmt"
 	"log/slog"
-	"maps"
 	"sort"
 	"strings"
 	"time"
@@ -109,8 +108,7 @@ func waitForLspDiagnostics(ctx context.Context, filePath string, lsps map[string
 	diagChan := make(chan struct{}, 1)
 
 	for _, client := range lsps {
-		originalDiags := make(map[protocol.DocumentURI][]protocol.Diagnostic)
-		maps.Copy(originalDiags, client.GetDiagnostics())
+		originalDiags := client.GetDiagnostics()
 
 		handler := func(params json.RawMessage) {
 			lsp.HandleDiagnostics(client, params)

internal/lsp/client.go 🔗

@@ -7,6 +7,7 @@ import (
 	"fmt"
 	"io"
 	"log/slog"
+	"maps"
 	"os"
 	"os/exec"
 	"path/filepath"
@@ -765,7 +766,10 @@ func (c *Client) GetFileDiagnostics(uri protocol.DocumentURI) []protocol.Diagnos
 
 // GetDiagnostics returns all diagnostics for all files
 func (c *Client) GetDiagnostics() map[protocol.DocumentURI][]protocol.Diagnostic {
-	return c.diagnostics
+	c.diagnosticsMu.RLock()
+	defer c.diagnosticsMu.RUnlock()
+
+	return maps.Clone(c.diagnostics)
 }
 
 // OpenFileOnDemand opens a file only if it's not already open