perf(tools/view): pause briefly for LSP diagnostics when viewing a file

Christian Rocha created

Change summary

internal/agent/tools/diagnostics.go | 21 +++++++++++++++++++++
internal/agent/tools/view.go        |  2 ++
2 files changed, 23 insertions(+)

Detailed changes

internal/agent/tools/diagnostics.go 🔗

@@ -59,6 +59,27 @@ func openInLSPs(
 	}
 }
 
+// waitForLSPDiagnostics waits briefly for diagnostics publication after a file
+// has been opened. Intended for read-only situations where viewing up-to-date
+// files matters but latency should remain low (i.e. when using the view tool).
+func waitForLSPDiagnostics(
+	ctx context.Context,
+	manager *lsp.Manager,
+	filepath string,
+	timeout time.Duration,
+) {
+	if filepath == "" || manager == nil || timeout <= 0 {
+		return
+	}
+
+	for client := range manager.Clients().Seq() {
+		if !client.HandlesFile(filepath) {
+			continue
+		}
+		client.WaitForDiagnostics(ctx, timeout)
+	}
+}
+
 // notifyLSPs notifies LSP servers that a file has changed and waits for
 // updated diagnostics. Use this after edit/multiedit operations.
 func notifyLSPs(

internal/agent/tools/view.go 🔗

@@ -10,6 +10,7 @@ import (
 	"os"
 	"path/filepath"
 	"strings"
+	"time"
 	"unicode/utf8"
 
 	"charm.land/fantasy"
@@ -194,6 +195,7 @@ func NewViewTool(
 			}
 
 			openInLSPs(ctx, lspManager, filePath)
+			waitForLSPDiagnostics(ctx, lspManager, filePath, 300*time.Millisecond)
 			output := "<file>\n"
 			output += addLineNumbers(content, params.Offset+1)