on main help sign in
fix(lsp): simplify init/ping, store capabilities (#713)
3b9babbCarlos Alexandro Becker
internal/lsp/caps.gonew file+112
@@ -0,0 +1,112 @@
1+package lsp
2+
3+import "github.com/charmbracelet/crush/internal/lsp/protocol"
4+
5+func (c *Client) setCapabilities(caps protocol.ServerCapabilities) {
6+ c.capsMu.Lock()
7+ defer c.capsMu.Unlock()
8+ c.caps = caps
9+ c.capsSet.Store(true)
10+}
11+
12+func (c *Client) getCapabilities() (protocol.ServerCapabilities, bool) {
13+ c.capsMu.RLock()
14+ defer c.capsMu.RUnlock()
15+ return c.caps, c.capsSet.Load()
16+}
17+
18+func (c *Client) IsMethodSupported(method string) bool {
19+ // Always allow core lifecycle and generic methods
20+ switch method {
21+ case "initialize", "shutdown", "exit", "$/cancelRequest":
22+ return true
23+ }
24+
25+ caps, ok := c.getCapabilities()
26+ if !ok {
27+ // caps not set yet, be permissive
28+ return true
29+ }
30+
31+ switch method {
32+ case "textDocument/hover":
33+ return caps.HoverProvider != nil
34+ case "textDocument/definition":
35+ return caps.DefinitionProvider != nil
36+ case "textDocument/references":
37+ return caps.ReferencesProvider != nil
38+ case "textDocument/implementation":
39+ return caps.ImplementationProvider != nil
40+ case "textDocument/typeDefinition":
41+ return caps.TypeDefinitionProvider != nil
42+ case "textDocument/documentColor", "textDocument/colorPresentation":
43+ return caps.ColorProvider != nil
44+ case "textDocument/foldingRange":
45+ return caps.FoldingRangeProvider != nil
46+ case "textDocument/declaration":
47+ return caps.DeclarationProvider != nil
48+ case "textDocument/selectionRange":
49+ return caps.SelectionRangeProvider != nil
50+ case "textDocument/prepareCallHierarchy", "callHierarchy/incomingCalls", "callHierarchy/outgoingCalls":
51+ return caps.CallHierarchyProvider != nil
52+ case "textDocument/semanticTokens/full", "textDocument/semanticTokens/full/delta", "textDocument/semanticTokens/range":
53+ return caps.SemanticTokensProvider != nil
54+ case "textDocument/linkedEditingRange":
55+ return caps.LinkedEditingRangeProvider != nil
56+ case "workspace/willCreateFiles":
57+ return caps.Workspace != nil && caps.Workspace.FileOperations != nil && caps.Workspace.FileOperations.WillCreate != nil
58+ case "workspace/willRenameFiles":
59+ return caps.Workspace != nil && caps.Workspace.FileOperations != nil && caps.Workspace.FileOperations.WillRename != nil
60+ case "workspace/willDeleteFiles":
61+ return caps.Workspace != nil && caps.Workspace.FileOperations != nil && caps.Workspace.FileOperations.WillDelete != nil
62+ case "textDocument/moniker":
63+ return caps.MonikerProvider != nil
64+ case "textDocument/prepareTypeHierarchy", "typeHierarchy/supertypes", "typeHierarchy/subtypes":
65+ return caps.TypeHierarchyProvider != nil
66+ case "textDocument/inlineValue":
67+ return caps.InlineValueProvider != nil
68+ case "textDocument/inlayHint", "inlayHint/resolve":
69+ return caps.InlayHintProvider != nil
70+ case "textDocument/diagnostic", "workspace/diagnostic":
71+ return caps.DiagnosticProvider != nil
72+ case "textDocument/inlineCompletion":
73+ return caps.InlineCompletionProvider != nil
74+ case "workspace/textDocumentContent":
75+ return caps.Workspace != nil && caps.Workspace.TextDocumentContent != nil
76+ case "textDocument/willSaveWaitUntil":
77+ if caps.TextDocumentSync == nil {
78+ return false
79+ }
80+ return true
81+ case "textDocument/completion", "completionItem/resolve":
82+ return caps.CompletionProvider != nil
83+ case "textDocument/signatureHelp":
84+ return caps.SignatureHelpProvider != nil
85+ case "textDocument/documentHighlight":
86+ return caps.DocumentHighlightProvider != nil
87+ case "textDocument/documentSymbol":
88+ return caps.DocumentSymbolProvider != nil
89+ case "textDocument/codeAction", "codeAction/resolve":
90+ return caps.CodeActionProvider != nil
91+ case "workspace/symbol", "workspaceSymbol/resolve":
92+ return caps.WorkspaceSymbolProvider != nil
93+ case "textDocument/codeLens", "codeLens/resolve":
94+ return caps.CodeLensProvider != nil
95+ case "textDocument/documentLink", "documentLink/resolve":
96+ return caps.DocumentLinkProvider != nil
97+ case "textDocument/formatting":
98+ return caps.DocumentFormattingProvider != nil
99+ case "textDocument/rangeFormatting":
100+ return caps.DocumentRangeFormattingProvider != nil
101+ case "textDocument/rangesFormatting":
102+ return caps.DocumentRangeFormattingProvider != nil
103+ case "textDocument/onTypeFormatting":
104+ return caps.DocumentOnTypeFormattingProvider != nil
105+ case "textDocument/rename", "textDocument/prepareRename":
106+ return caps.RenameProvider != nil
107+ case "workspace/executeCommand":
108+ return caps.ExecuteCommandProvider != nil
109+ default:
110+ return true
111+ }
112+}
internal/lsp/client.go+30−126
@@ -62,6 +62,11 @@ type Client struct {
62
62
63 // Server state
63 // Server state
64 serverState atomic.Value
64 serverState atomic.Value
65+
66+ // Server capabilities as returned by initialize
67+ caps protocol.ServerCapabilities
68+ capsMu sync.RWMutex
69+ capsSet atomic.Bool
65}
70}
66
71
67// NewClient creates a new LSP client.
72// NewClient creates a new LSP client.
@@ -143,7 +148,7 @@ func (c *Client) RegisterServerRequestHandler(method string, handler ServerReque
143}
148}
144
149
145func (c *Client) InitializeLSPClient(ctx context.Context, workspaceDir string) (*protocol.InitializeResult, error) {
150func (c *Client) InitializeLSPClient(ctx context.Context, workspaceDir string) (*protocol.InitializeResult, error) {
146− initParams := &protocol.InitializeParams{
151+ initParams := protocol.ParamInitialize{
147 WorkspaceFoldersInitializeParams: protocol.WorkspaceFoldersInitializeParams{
152 WorkspaceFoldersInitializeParams: protocol.WorkspaceFoldersInitializeParams{
148 WorkspaceFolders: []protocol.WorkspaceFolder{
153 WorkspaceFolders: []protocol.WorkspaceFolder{
149 {
154 {
@@ -220,12 +225,14 @@ func (c *Client) InitializeLSPClient(ctx context.Context, workspaceDir string) (
220 },
225 },
221 }
226 }
222
227
223− var result protocol.InitializeResult
224− if err := c.Call(ctx, "initialize", initParams, &result); err != nil {
228+ result, err := c.Initialize(ctx, initParams)
229+ if err != nil {
225 return nil, fmt.Errorf("initialize failed: %w", err)
230 return nil, fmt.Errorf("initialize failed: %w", err)
226 }
231 }
227
232
228− if err := c.Notify(ctx, "initialized", struct{}{}); err != nil {
233+ c.setCapabilities(result.Capabilities)
234+
235+ if err := c.Initialized(ctx, protocol.InitializedParams{}); err != nil {
229 return nil, fmt.Errorf("initialized notification failed: %w", err)
236 return nil, fmt.Errorf("initialized notification failed: %w", err)
230 }
237 }
231
238
@@ -234,14 +241,9 @@ func (c *Client) InitializeLSPClient(ctx context.Context, workspaceDir string) (
234 c.RegisterServerRequestHandler("workspace/configuration", HandleWorkspaceConfiguration)
241 c.RegisterServerRequestHandler("workspace/configuration", HandleWorkspaceConfiguration)
235 c.RegisterServerRequestHandler("client/registerCapability", HandleRegisterCapability)
242 c.RegisterServerRequestHandler("client/registerCapability", HandleRegisterCapability)
236 c.RegisterNotificationHandler("window/showMessage", HandleServerMessage)
243 c.RegisterNotificationHandler("window/showMessage", HandleServerMessage)
237− c.RegisterNotificationHandler("textDocument/publishDiagnostics",
244+ c.RegisterNotificationHandler("textDocument/publishDiagnostics", func(params json.RawMessage) {
238− func(params json.RawMessage) { HandleDiagnostics(c, params) })
245+ HandleDiagnostics(c, params)
239−
246+ })
240− // Notify the LSP server
241− err := c.Initialized(ctx, protocol.InitializedParams{})
242− if err != nil {
243− return nil, fmt.Errorf("initialization failed: %w", err)
244− }
245
247
246 return &result, nil
248 return &result, nil
247}
249}
@@ -329,16 +331,7 @@ func (c *Client) WaitForServerReady(ctx context.Context) error {
329 slog.Debug("Waiting for LSP server to be ready...")
331 slog.Debug("Waiting for LSP server to be ready...")
330 }
332 }
331
333
332− // Determine server type for specialized initialization
333− serverType := c.detectServerType()
334−
335− // For TypeScript-like servers, we need to open some key files first
336− if serverType == ServerTypeTypeScript {
337− if cfg.Options.DebugLSP {
338− slog.Debug("TypeScript-like server detected, opening key configuration files")
339− }
340− c.openKeyConfigFiles(ctx)
334+ c.openKeyConfigFiles(ctx)
341− }
342
335
343 for {
336 for {
344 select {
337 select {
@@ -347,21 +340,19 @@ func (c *Client) WaitForServerReady(ctx context.Context) error {
347 return fmt.Errorf("timeout waiting for LSP server to be ready")
340 return fmt.Errorf("timeout waiting for LSP server to be ready")
348 case <-ticker.C:
341 case <-ticker.C:
349 // Try a ping method appropriate for this server type
342 // Try a ping method appropriate for this server type
350− err := c.pingServerByType(ctx, serverType)
351− if err == nil {
343+ if err := c.ping(ctx); err != nil {
352− // Server responded successfully
353− c.SetServerState(StateReady)
354 if cfg.Options.DebugLSP {
344 if cfg.Options.DebugLSP {
355− slog.Debug("LSP server is ready")
345+ slog.Debug("LSP server not ready yet", "error", err, "server", c.name)
356 }
346 }
357− return nil
347+ continue
358− } else {
359− slog.Debug("LSP server not ready yet", "error", err, "serverType", serverType)
360 }
348 }
361
349
350+ // Server responded successfully
351+ c.SetServerState(StateReady)
362 if cfg.Options.DebugLSP {
352 if cfg.Options.DebugLSP {
363− slog.Debug("LSP server not ready yet", "error", err, "serverType", serverType)
353+ slog.Debug("LSP server is ready")
364 }
354 }
355+ return nil
365 }
356 }
366 }
357 }
367}
358}
@@ -443,86 +434,13 @@ func (c *Client) openKeyConfigFiles(ctx context.Context) {
443 }
434 }
444}
435}
445
436
446−// pingServerByType sends a ping request appropriate for the server type
437+// ping sends a ping request...
447−func (c *Client) pingServerByType(ctx context.Context, serverType ServerType) error {
448− switch serverType {
449− case ServerTypeTypeScript:
450− // For TypeScript, try a document symbol request on an open file
451− return c.pingTypeScriptServer(ctx)
452− case ServerTypeGo:
453− // For Go, workspace/symbol works well
454− return c.pingWithWorkspaceSymbol(ctx)
455− case ServerTypeRust:
456− // For Rust, workspace/symbol works well
457− return c.pingWithWorkspaceSymbol(ctx)
458− default:
459− // Default ping method
460− return c.pingWithWorkspaceSymbol(ctx)
461− }
462−}
463−
464−// pingTypeScriptServer tries to ping a TypeScript server with appropriate methods
465−func (c *Client) pingTypeScriptServer(ctx context.Context) error {
438+func (c *Client) ping(ctx context.Context) error {
466− // First try workspace/symbol which works for many servers
439+ if _, err := c.Symbol(ctx, protocol.WorkspaceSymbolParams{}); err == nil {
467− if err := c.pingWithWorkspaceSymbol(ctx); err == nil {
468− return nil
469− }
470−
471− // If that fails, try to find an open file and request document symbols
472− c.openFilesMu.RLock()
473− defer c.openFilesMu.RUnlock()
474−
475− // If we have any open files, try to get document symbols for one
476− for uri := range c.openFiles {
477− filePath, err := protocol.DocumentURI(uri).Path()
478− if err != nil {
479− slog.Error("Failed to convert URI to path for TypeScript symbol collection", "uri", uri, "error", err)
480− continue
481− }
482−
483− if strings.HasSuffix(filePath, ".ts") || strings.HasSuffix(filePath, ".js") ||
484− strings.HasSuffix(filePath, ".tsx") || strings.HasSuffix(filePath, ".jsx") {
485− var symbols []protocol.DocumentSymbol
486− err := c.Call(ctx, "textDocument/documentSymbol", protocol.DocumentSymbolParams{
487− TextDocument: protocol.TextDocumentIdentifier{
488− URI: protocol.DocumentURI(uri),
489− },
490− }, &symbols)
491− if err == nil {
492− return nil
493− }
494− }
495− }
496−
497− // If we have no open TypeScript files, try to find and open one
498− workDir := config.Get().WorkingDir()
499− err := filepath.WalkDir(workDir, func(path string, d os.DirEntry, err error) error {
500− if err != nil {
501− return err
502− }
503−
504− // Skip directories and non-TypeScript files
505− if d.IsDir() {
506− return nil
507− }
508−
509− ext := filepath.Ext(path)
510− if ext == ".ts" || ext == ".js" || ext == ".tsx" || ext == ".jsx" {
511− // Found a TypeScript file, try to open it
512− if err := c.OpenFile(ctx, path); err == nil {
513− // Successfully opened, stop walking
514− return filepath.SkipAll
515− }
516− }
517−
518 return nil
440 return nil
519− })
520− if err != nil {
521− slog.Debug("Error walking directory for TypeScript files", "error", err)
522 }
441 }
523−
442+ // This is a very lightweight request that should work for most servers
524− // Final fallback - just try a generic capability
443+ return c.Notify(ctx, "$/cancelRequest", protocol.CancelParams{ID: "1"})
525− return c.pingWithServerCapabilities(ctx)
526}
444}
527
445
528// openTypeScriptFiles finds and opens TypeScript files to help initialize the server
446// openTypeScriptFiles finds and opens TypeScript files to help initialize the server
@@ -597,20 +515,6 @@ func shouldSkipDir(path string) bool {
597 return skipDirs[dirName]
515 return skipDirs[dirName]
598}
516}
599
517
600−// pingWithWorkspaceSymbol tries a workspace/symbol request
601−func (c *Client) pingWithWorkspaceSymbol(ctx context.Context) error {
602− var result []protocol.SymbolInformation
603− return c.Call(ctx, "workspace/symbol", protocol.WorkspaceSymbolParams{
604− Query: "",
605− }, &result)
606−}
607−
608−// pingWithServerCapabilities tries to get server capabilities
609−func (c *Client) pingWithServerCapabilities(ctx context.Context) error {
610− // This is a very lightweight request that should work for most servers
611− return c.Notify(ctx, "$/cancelRequest", struct{ ID int }{ID: -1})
612−}
613−
614type OpenFileInfo struct {
518type OpenFileInfo struct {
615 Version int32
519 Version int32
616 URI protocol.DocumentURI
520 URI protocol.DocumentURI
@@ -668,7 +572,7 @@ func (c *Client) OpenFile(ctx context.Context, filepath string) error {
668 },
572 },
669 }
573 }
670
574
671− if err := c.Notify(ctx, "textDocument/didOpen", params); err != nil {
575+ if err := c.DidOpen(ctx, params); err != nil {
672 return err
576 return err
673 }
577 }
674
578
@@ -718,7 +622,7 @@ func (c *Client) NotifyChange(ctx context.Context, filepath string) error {
718 },
622 },
719 }
623 }
720
624
721− return c.Notify(ctx, "textDocument/didChange", params)
625+ return c.DidChange(ctx, params)
722}
626}
723
627
724func (c *Client) CloseFile(ctx context.Context, filepath string) error {
628func (c *Client) CloseFile(ctx context.Context, filepath string) error {
@@ -741,7 +645,7 @@ func (c *Client) CloseFile(ctx context.Context, filepath string) error {
741 if cfg.Options.DebugLSP {
645 if cfg.Options.DebugLSP {
742 slog.Debug("Closing file", "file", filepath)
646 slog.Debug("Closing file", "file", filepath)
743 }
647 }
744− if err := c.Notify(ctx, "textDocument/didClose", params); err != nil {
648+ if err := c.DidClose(ctx, params); err != nil {
745 return err
649 return err
746 }
650 }
747
651
internal/lsp/transport.go+10−1
@@ -188,9 +188,12 @@ func (c *Client) handleMessages() {
188
188
189// Call makes a request and waits for the response
189// Call makes a request and waits for the response
190func (c *Client) Call(ctx context.Context, method string, params any, result any) error {
190func (c *Client) Call(ctx context.Context, method string, params any, result any) error {
191− cfg := config.Get()
191+ if !c.IsMethodSupported(method) {
192+ return fmt.Errorf("method not supported by server: %s", method)
193+ }
192 id := c.nextID.Add(1)
194 id := c.nextID.Add(1)
193
195
196+ cfg := config.Get()
194 if cfg.Options.DebugLSP {
197 if cfg.Options.DebugLSP {
195 slog.Debug("Making call", "method", method, "id", id)
198 slog.Debug("Making call", "method", method, "id", id)
196 }
199 }
@@ -253,6 +256,12 @@ func (c *Client) Call(ctx context.Context, method string, params any, result any
253// Notify sends a notification (a request without an ID that doesn't expect a response)
256// Notify sends a notification (a request without an ID that doesn't expect a response)
254func (c *Client) Notify(ctx context.Context, method string, params any) error {
257func (c *Client) Notify(ctx context.Context, method string, params any) error {
255 cfg := config.Get()
258 cfg := config.Get()
259+ if !c.IsMethodSupported(method) {
260+ if cfg.Options.DebugLSP {
261+ slog.Debug("Skipping notification: method not supported by server", "method", method)
262+ }
263+ return nil
264+ }
256 if cfg.Options.DebugLSP {
265 if cfg.Options.DebugLSP {
257 slog.Debug("Sending notification", "method", method)
266 slog.Debug("Sending notification", "method", method)
258 }
267 }
internal/lsp/watcher/watcher.go+1−8
@@ -623,18 +623,11 @@ func (w *WorkspaceWatcher) matchesPattern(path string, pattern protocol.GlobPatt
623 if basePath == "" {
623 if basePath == "" {
624 return false
624 return false
625 }
625 }
626− // For relative patterns
627− if basePath, err = protocol.DocumentURI(basePath).Path(); err != nil {
628− // XXX: Do we want to return here, or send the error up the stack?
629− slog.Error("Error converting base path to URI", "basePath", basePath, "error", err)
630− }
631−
632− basePath = filepath.ToSlash(basePath)
633
626
634 // Make path relative to basePath for matching
627 // Make path relative to basePath for matching
635 relPath, err := filepath.Rel(basePath, path)
628 relPath, err := filepath.Rel(basePath, path)
636 if err != nil {
629 if err != nil {
637− slog.Error("Error getting relative path", "path", path, "basePath", basePath, "error", err)
630+ slog.Error("Error getting relative path", "path", path, "basePath", basePath, "error", err, "server", w.name)
638 return false
631 return false
639 }
632 }
640 relPath = filepath.ToSlash(relPath)
633 relPath = filepath.ToSlash(relPath)