client.go

  1package lsp
  2
  3import (
  4	"context"
  5	"encoding/json"
  6	"fmt"
  7	"log/slog"
  8	"maps"
  9	"os"
 10	"path/filepath"
 11	"strings"
 12	"sync"
 13	"sync/atomic"
 14	"time"
 15
 16	"github.com/charmbracelet/crush/internal/config"
 17	"github.com/charmbracelet/crush/internal/csync"
 18	"github.com/charmbracelet/crush/internal/home"
 19	powernap "github.com/charmbracelet/x/powernap/pkg/lsp"
 20	"github.com/charmbracelet/x/powernap/pkg/lsp/protocol"
 21	"github.com/charmbracelet/x/powernap/pkg/transport"
 22)
 23
 24// DiagnosticCounts holds the count of diagnostics by severity.
 25type DiagnosticCounts struct {
 26	Error       int
 27	Warning     int
 28	Information int
 29	Hint        int
 30}
 31
 32type Client struct {
 33	client *powernap.Client
 34	name   string
 35	debug  bool
 36
 37	// Working directory this LSP is scoped to.
 38	workDir string
 39
 40	// File types this LSP server handles (e.g., .go, .rs, .py)
 41	fileTypes []string
 42
 43	// Configuration for this LSP client
 44	config config.LSPConfig
 45
 46	// Original context and resolver for recreating the client
 47	ctx      context.Context
 48	resolver config.VariableResolver
 49
 50	// Diagnostic change callback
 51	onDiagnosticsChanged func(name string, count int)
 52
 53	// Diagnostic cache
 54	diagnostics *csync.VersionedMap[protocol.DocumentURI, []protocol.Diagnostic]
 55
 56	// Cached diagnostic counts to avoid map copy on every UI render.
 57	diagCountsCache   DiagnosticCounts
 58	diagCountsVersion uint64
 59	diagCountsMu      sync.Mutex
 60
 61	// Files are currently opened by the LSP
 62	openFiles *csync.Map[string, *OpenFileInfo]
 63
 64	// Server state
 65	serverState atomic.Value
 66}
 67
 68// New creates a new LSP client using the powernap implementation.
 69func New(ctx context.Context, name string, cfg config.LSPConfig, resolver config.VariableResolver, debug bool) (*Client, error) {
 70	client := &Client{
 71		name:        name,
 72		fileTypes:   cfg.FileTypes,
 73		diagnostics: csync.NewVersionedMap[protocol.DocumentURI, []protocol.Diagnostic](),
 74		openFiles:   csync.NewMap[string, *OpenFileInfo](),
 75		config:      cfg,
 76		ctx:         ctx,
 77		debug:       debug,
 78		resolver:    resolver,
 79	}
 80	client.serverState.Store(StateStarting)
 81
 82	if err := client.createPowernapClient(); err != nil {
 83		return nil, err
 84	}
 85
 86	return client, nil
 87}
 88
 89// Initialize initializes the LSP client and returns the server capabilities.
 90func (c *Client) Initialize(ctx context.Context, workspaceDir string) (*protocol.InitializeResult, error) {
 91	if err := c.client.Initialize(ctx, false); err != nil {
 92		return nil, fmt.Errorf("failed to initialize the lsp client: %w", err)
 93	}
 94
 95	// Convert powernap capabilities to protocol capabilities
 96	caps := c.client.GetCapabilities()
 97	protocolCaps := protocol.ServerCapabilities{
 98		TextDocumentSync: caps.TextDocumentSync,
 99		CompletionProvider: func() *protocol.CompletionOptions {
100			if caps.CompletionProvider != nil {
101				return &protocol.CompletionOptions{
102					TriggerCharacters:   caps.CompletionProvider.TriggerCharacters,
103					AllCommitCharacters: caps.CompletionProvider.AllCommitCharacters,
104					ResolveProvider:     caps.CompletionProvider.ResolveProvider,
105				}
106			}
107			return nil
108		}(),
109	}
110
111	result := &protocol.InitializeResult{
112		Capabilities: protocolCaps,
113	}
114
115	c.registerHandlers()
116
117	return result, nil
118}
119
120// Close closes the LSP client.
121func (c *Client) Close(ctx context.Context) error {
122	c.CloseAllFiles(ctx)
123
124	// Shutdown and exit the client
125	if err := c.client.Shutdown(ctx); err != nil {
126		slog.Warn("Failed to shutdown LSP client", "error", err)
127	}
128
129	return c.client.Exit()
130}
131
132// createPowernapClient creates a new powernap client with the current configuration.
133func (c *Client) createPowernapClient() error {
134	workDir, err := os.Getwd()
135	if err != nil {
136		return fmt.Errorf("failed to get working directory: %w", err)
137	}
138
139	rootURI := string(protocol.URIFromPath(workDir))
140	c.workDir = workDir
141
142	command, err := c.resolver.ResolveValue(c.config.Command)
143	if err != nil {
144		return fmt.Errorf("invalid lsp command: %w", err)
145	}
146
147	clientConfig := powernap.ClientConfig{
148		Command:     home.Long(command),
149		Args:        c.config.Args,
150		RootURI:     rootURI,
151		Environment: maps.Clone(c.config.Env),
152		Settings:    c.config.Options,
153		InitOptions: c.config.InitOptions,
154		WorkspaceFolders: []protocol.WorkspaceFolder{
155			{
156				URI:  rootURI,
157				Name: filepath.Base(workDir),
158			},
159		},
160	}
161
162	powernapClient, err := powernap.NewClient(clientConfig)
163	if err != nil {
164		return fmt.Errorf("failed to create lsp client: %w", err)
165	}
166
167	c.client = powernapClient
168	return nil
169}
170
171// registerHandlers registers the standard LSP notification and request handlers.
172func (c *Client) registerHandlers() {
173	c.RegisterServerRequestHandler("workspace/applyEdit", HandleApplyEdit)
174	c.RegisterServerRequestHandler("workspace/configuration", HandleWorkspaceConfiguration)
175	c.RegisterServerRequestHandler("client/registerCapability", HandleRegisterCapability)
176	c.RegisterNotificationHandler("window/showMessage", func(ctx context.Context, method string, params json.RawMessage) {
177		if c.debug {
178			HandleServerMessage(ctx, method, params)
179		}
180	})
181	c.RegisterNotificationHandler("textDocument/publishDiagnostics", func(_ context.Context, _ string, params json.RawMessage) {
182		HandleDiagnostics(c, params)
183	})
184}
185
186// Restart closes the current LSP client and creates a new one with the same configuration.
187func (c *Client) Restart() error {
188	var openFiles []string
189	for uri := range c.openFiles.Seq2() {
190		openFiles = append(openFiles, string(uri))
191	}
192
193	closeCtx, cancel := context.WithTimeout(c.ctx, 10*time.Second)
194	defer cancel()
195
196	if err := c.Close(closeCtx); err != nil {
197		slog.Warn("Error closing client during restart", "name", c.name, "error", err)
198	}
199
200	c.SetServerState(StateStopped)
201
202	c.diagCountsCache = DiagnosticCounts{}
203	c.diagCountsVersion = 0
204
205	if err := c.createPowernapClient(); err != nil {
206		return err
207	}
208
209	initCtx, cancel := context.WithTimeout(c.ctx, 30*time.Second)
210	defer cancel()
211
212	c.SetServerState(StateStarting)
213
214	if err := c.client.Initialize(initCtx, false); err != nil {
215		c.SetServerState(StateError)
216		return fmt.Errorf("failed to initialize lsp client: %w", err)
217	}
218
219	c.registerHandlers()
220
221	if err := c.WaitForServerReady(initCtx); err != nil {
222		slog.Error("Server failed to become ready after restart", "name", c.name, "error", err)
223		c.SetServerState(StateError)
224		return err
225	}
226
227	for _, uri := range openFiles {
228		if err := c.OpenFile(initCtx, uri); err != nil {
229			slog.Warn("Failed to reopen file after restart", "file", uri, "error", err)
230		}
231	}
232	return nil
233}
234
235// ServerState represents the state of an LSP server
236type ServerState int
237
238const (
239	StateStopped ServerState = iota
240	StateStarting
241	StateReady
242	StateError
243	StateDisabled
244)
245
246// GetServerState returns the current state of the LSP server
247func (c *Client) GetServerState() ServerState {
248	if val := c.serverState.Load(); val != nil {
249		return val.(ServerState)
250	}
251	return StateStarting
252}
253
254// SetServerState sets the current state of the LSP server
255func (c *Client) SetServerState(state ServerState) {
256	c.serverState.Store(state)
257}
258
259// GetName returns the name of the LSP client
260func (c *Client) GetName() string {
261	return c.name
262}
263
264// SetDiagnosticsCallback sets the callback function for diagnostic changes
265func (c *Client) SetDiagnosticsCallback(callback func(name string, count int)) {
266	c.onDiagnosticsChanged = callback
267}
268
269// WaitForServerReady waits for the server to be ready
270func (c *Client) WaitForServerReady(ctx context.Context) error {
271	// Set initial state
272	c.SetServerState(StateStarting)
273
274	// Create a context with timeout
275	ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
276	defer cancel()
277
278	// Try to ping the server with a simple request
279	ticker := time.NewTicker(500 * time.Millisecond)
280	defer ticker.Stop()
281
282	if c.debug {
283		slog.Debug("Waiting for LSP server to be ready...")
284	}
285
286	c.openKeyConfigFiles(ctx)
287
288	for {
289		select {
290		case <-ctx.Done():
291			c.SetServerState(StateError)
292			return fmt.Errorf("timeout waiting for LSP server to be ready")
293		case <-ticker.C:
294			// Check if client is running
295			if !c.client.IsRunning() {
296				if c.debug {
297					slog.Debug("LSP server not ready yet", "server", c.name)
298				}
299				continue
300			}
301
302			// Server is ready
303			c.SetServerState(StateReady)
304			if c.debug {
305				slog.Debug("LSP server is ready")
306			}
307			return nil
308		}
309	}
310}
311
312// OpenFileInfo contains information about an open file
313type OpenFileInfo struct {
314	Version int32
315	URI     protocol.DocumentURI
316}
317
318// HandlesFile checks if this LSP client handles the given file based on its
319// extension and whether it's within the working directory.
320func (c *Client) HandlesFile(path string) bool {
321	// Check if file is within working directory.
322	absPath, err := filepath.Abs(path)
323	if err != nil {
324		slog.Debug("Cannot resolve path", "name", c.name, "file", path, "error", err)
325		return false
326	}
327	relPath, err := filepath.Rel(c.workDir, absPath)
328	if err != nil || strings.HasPrefix(relPath, "..") {
329		slog.Debug("File outside workspace", "name", c.name, "file", path, "workDir", c.workDir)
330		return false
331	}
332	return handlesFiletype(c.name, c.fileTypes, path)
333}
334
335// OpenFile opens a file in the LSP server.
336func (c *Client) OpenFile(ctx context.Context, filepath string) error {
337	if !c.HandlesFile(filepath) {
338		return nil
339	}
340
341	uri := string(protocol.URIFromPath(filepath))
342
343	if _, exists := c.openFiles.Get(uri); exists {
344		return nil // Already open
345	}
346
347	// Skip files that do not exist or cannot be read
348	content, err := os.ReadFile(filepath)
349	if err != nil {
350		return fmt.Errorf("error reading file: %w", err)
351	}
352
353	// Notify the server about the opened document
354	if err = c.client.NotifyDidOpenTextDocument(ctx, uri, string(powernap.DetectLanguage(filepath)), 1, string(content)); err != nil {
355		return err
356	}
357
358	c.openFiles.Set(uri, &OpenFileInfo{
359		Version: 1,
360		URI:     protocol.DocumentURI(uri),
361	})
362
363	return nil
364}
365
366// NotifyChange notifies the server about a file change.
367func (c *Client) NotifyChange(ctx context.Context, filepath string) error {
368	uri := string(protocol.URIFromPath(filepath))
369
370	content, err := os.ReadFile(filepath)
371	if err != nil {
372		return fmt.Errorf("error reading file: %w", err)
373	}
374
375	fileInfo, isOpen := c.openFiles.Get(uri)
376	if !isOpen {
377		return fmt.Errorf("cannot notify change for unopened file: %s", filepath)
378	}
379
380	// Increment version
381	fileInfo.Version++
382
383	// Create change event
384	changes := []protocol.TextDocumentContentChangeEvent{
385		{
386			Value: protocol.TextDocumentContentChangeWholeDocument{
387				Text: string(content),
388			},
389		},
390	}
391
392	return c.client.NotifyDidChangeTextDocument(ctx, uri, int(fileInfo.Version), changes)
393}
394
395// IsFileOpen checks if a file is currently open.
396func (c *Client) IsFileOpen(filepath string) bool {
397	uri := string(protocol.URIFromPath(filepath))
398	_, exists := c.openFiles.Get(uri)
399	return exists
400}
401
402// CloseAllFiles closes all currently open files.
403func (c *Client) CloseAllFiles(ctx context.Context) {
404	for uri := range c.openFiles.Seq2() {
405		if c.debug {
406			slog.Debug("Closing file", "file", uri)
407		}
408		if err := c.client.NotifyDidCloseTextDocument(ctx, uri); err != nil {
409			slog.Warn("Error closing file", "uri", uri, "error", err)
410			continue
411		}
412		c.openFiles.Del(uri)
413	}
414}
415
416// GetFileDiagnostics returns diagnostics for a specific file.
417func (c *Client) GetFileDiagnostics(uri protocol.DocumentURI) []protocol.Diagnostic {
418	diags, _ := c.diagnostics.Get(uri)
419	return diags
420}
421
422// GetDiagnostics returns all diagnostics for all files.
423func (c *Client) GetDiagnostics() map[protocol.DocumentURI][]protocol.Diagnostic {
424	return c.diagnostics.Copy()
425}
426
427// GetDiagnosticCounts returns cached diagnostic counts by severity.
428// Uses the VersionedMap version to avoid recomputing on every call.
429func (c *Client) GetDiagnosticCounts() DiagnosticCounts {
430	currentVersion := c.diagnostics.Version()
431
432	c.diagCountsMu.Lock()
433	defer c.diagCountsMu.Unlock()
434
435	if currentVersion == c.diagCountsVersion {
436		return c.diagCountsCache
437	}
438
439	// Recompute counts.
440	counts := DiagnosticCounts{}
441	for _, diags := range c.diagnostics.Seq2() {
442		for _, diag := range diags {
443			switch diag.Severity {
444			case protocol.SeverityError:
445				counts.Error++
446			case protocol.SeverityWarning:
447				counts.Warning++
448			case protocol.SeverityInformation:
449				counts.Information++
450			case protocol.SeverityHint:
451				counts.Hint++
452			}
453		}
454	}
455
456	c.diagCountsCache = counts
457	c.diagCountsVersion = currentVersion
458	return counts
459}
460
461// OpenFileOnDemand opens a file only if it's not already open.
462func (c *Client) OpenFileOnDemand(ctx context.Context, filepath string) error {
463	// Check if the file is already open
464	if c.IsFileOpen(filepath) {
465		return nil
466	}
467
468	// Open the file
469	return c.OpenFile(ctx, filepath)
470}
471
472// GetDiagnosticsForFile ensures a file is open and returns its diagnostics.
473func (c *Client) GetDiagnosticsForFile(ctx context.Context, filepath string) ([]protocol.Diagnostic, error) {
474	documentURI := protocol.URIFromPath(filepath)
475
476	// Make sure the file is open
477	if !c.IsFileOpen(filepath) {
478		if err := c.OpenFile(ctx, filepath); err != nil {
479			return nil, fmt.Errorf("failed to open file for diagnostics: %w", err)
480		}
481
482		// Give the LSP server a moment to process the file
483		time.Sleep(100 * time.Millisecond)
484	}
485
486	// Get diagnostics
487	diagnostics, _ := c.diagnostics.Get(documentURI)
488
489	return diagnostics, nil
490}
491
492// ClearDiagnosticsForURI removes diagnostics for a specific URI from the cache.
493func (c *Client) ClearDiagnosticsForURI(uri protocol.DocumentURI) {
494	c.diagnostics.Del(uri)
495}
496
497// RegisterNotificationHandler registers a notification handler.
498func (c *Client) RegisterNotificationHandler(method string, handler transport.NotificationHandler) {
499	c.client.RegisterNotificationHandler(method, handler)
500}
501
502// RegisterServerRequestHandler handles server requests.
503func (c *Client) RegisterServerRequestHandler(method string, handler transport.Handler) {
504	c.client.RegisterHandler(method, handler)
505}
506
507// DidChangeWatchedFiles sends a workspace/didChangeWatchedFiles notification to the server.
508func (c *Client) DidChangeWatchedFiles(ctx context.Context, params protocol.DidChangeWatchedFilesParams) error {
509	return c.client.NotifyDidChangeWatchedFiles(ctx, params.Changes)
510}
511
512// openKeyConfigFiles opens important configuration files that help initialize the server.
513func (c *Client) openKeyConfigFiles(ctx context.Context) {
514	wd, err := os.Getwd()
515	if err != nil {
516		return
517	}
518
519	// Try to open each file, ignoring errors if they don't exist
520	for _, file := range c.config.RootMarkers {
521		file = filepath.Join(wd, file)
522		if _, err := os.Stat(file); err == nil {
523			// File exists, try to open it
524			if err := c.OpenFile(ctx, file); err != nil {
525				slog.Error("Failed to open key config file", "file", file, "error", err)
526			} else {
527				slog.Debug("Opened key config file for initialization", "file", file)
528			}
529		}
530	}
531}
532
533// WaitForDiagnostics waits until diagnostics change or the timeout is reached.
534func (c *Client) WaitForDiagnostics(ctx context.Context, d time.Duration) {
535	ticker := time.NewTicker(200 * time.Millisecond)
536	defer ticker.Stop()
537	timeout := time.After(d)
538	pv := c.diagnostics.Version()
539	for {
540		select {
541		case <-ctx.Done():
542			return
543		case <-timeout:
544			return
545		case <-ticker.C:
546			if pv != c.diagnostics.Version() {
547				return
548			}
549		}
550	}
551}
552
553// FindReferences finds all references to the symbol at the given position.
554func (c *Client) FindReferences(ctx context.Context, filepath string, line, character int, includeDeclaration bool) ([]protocol.Location, error) {
555	if err := c.OpenFileOnDemand(ctx, filepath); err != nil {
556		return nil, err
557	}
558	// NOTE: line and character should be 0-based.
559	// See: https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/#position
560	return c.client.FindReferences(ctx, filepath, line-1, character-1, includeDeclaration)
561}