Add files using upload-large-folder tool
Browse files- projects/ui/crush/internal/home/home.go +42 -0
- projects/ui/crush/internal/home/home_test.go +26 -0
- projects/ui/crush/internal/log/http.go +128 -0
- projects/ui/crush/internal/log/http_test.go +73 -0
- projects/ui/crush/internal/log/log.go +70 -0
- projects/ui/crush/internal/lsp/caps.go +112 -0
- projects/ui/crush/internal/lsp/client.go +753 -0
- projects/ui/crush/internal/lsp/client_test.go +93 -0
- projects/ui/crush/internal/lsp/handlers.go +119 -0
- projects/ui/crush/internal/lsp/language.go +132 -0
- projects/ui/crush/internal/lsp/methods.go +554 -0
- projects/ui/crush/internal/lsp/protocol.go +48 -0
- projects/ui/crush/internal/lsp/transport.go +284 -0
- projects/ui/crush/internal/message/attachment.go +8 -0
- projects/ui/crush/internal/message/content.go +386 -0
- projects/ui/crush/internal/message/message.go +282 -0
- projects/ui/crush/internal/permission/permission.go +234 -0
- projects/ui/crush/internal/permission/permission_test.go +247 -0
- projects/ui/crush/internal/pubsub/broker.go +118 -0
- projects/ui/crush/internal/pubsub/events.go +28 -0
projects/ui/crush/internal/home/home.go
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package home
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"log/slog"
|
| 5 |
+
"os"
|
| 6 |
+
"path/filepath"
|
| 7 |
+
"strings"
|
| 8 |
+
"sync"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
// Dir returns the users home directory, or if it fails, tries to create a new
|
| 12 |
+
// temporary directory and use that instead.
|
| 13 |
+
var Dir = sync.OnceValue(func() string {
|
| 14 |
+
home, err := os.UserHomeDir()
|
| 15 |
+
if err == nil {
|
| 16 |
+
slog.Debug("user home directory", "home", home)
|
| 17 |
+
return home
|
| 18 |
+
}
|
| 19 |
+
tmp, err := os.MkdirTemp("crush", "")
|
| 20 |
+
if err != nil {
|
| 21 |
+
slog.Error("could not find the user home directory")
|
| 22 |
+
return ""
|
| 23 |
+
}
|
| 24 |
+
slog.Warn("could not find the user home directory, using a temporary one", "home", tmp)
|
| 25 |
+
return tmp
|
| 26 |
+
})
|
| 27 |
+
|
| 28 |
+
// Short replaces the actual home path from [Dir] with `~`.
|
| 29 |
+
func Short(p string) string {
|
| 30 |
+
if !strings.HasPrefix(p, Dir()) || Dir() == "" {
|
| 31 |
+
return p
|
| 32 |
+
}
|
| 33 |
+
return filepath.Join("~", strings.TrimPrefix(p, Dir()))
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
// Long replaces the `~` with actual home path from [Dir].
|
| 37 |
+
func Long(p string) string {
|
| 38 |
+
if !strings.HasPrefix(p, "~") || Dir() == "" {
|
| 39 |
+
return p
|
| 40 |
+
}
|
| 41 |
+
return strings.Replace(p, "~", Dir(), 1)
|
| 42 |
+
}
|
projects/ui/crush/internal/home/home_test.go
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package home
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"path/filepath"
|
| 5 |
+
"testing"
|
| 6 |
+
|
| 7 |
+
"github.com/stretchr/testify/require"
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
func TestDir(t *testing.T) {
|
| 11 |
+
require.NotEmpty(t, Dir())
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
func TestShort(t *testing.T) {
|
| 15 |
+
d := filepath.Join(Dir(), "documents", "file.txt")
|
| 16 |
+
require.Equal(t, filepath.FromSlash("~/documents/file.txt"), Short(d))
|
| 17 |
+
ad := filepath.FromSlash("/absolute/path/file.txt")
|
| 18 |
+
require.Equal(t, ad, Short(ad))
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
func TestLong(t *testing.T) {
|
| 22 |
+
d := filepath.FromSlash("~/documents/file.txt")
|
| 23 |
+
require.Equal(t, filepath.Join(Dir(), "documents", "file.txt"), Long(d))
|
| 24 |
+
ad := filepath.FromSlash("/absolute/path/file.txt")
|
| 25 |
+
require.Equal(t, ad, Long(ad))
|
| 26 |
+
}
|
projects/ui/crush/internal/log/http.go
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package log
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"bytes"
|
| 5 |
+
"context"
|
| 6 |
+
"encoding/json"
|
| 7 |
+
"io"
|
| 8 |
+
"log/slog"
|
| 9 |
+
"net/http"
|
| 10 |
+
"strings"
|
| 11 |
+
"time"
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
// NewHTTPClient creates an HTTP client with debug logging enabled when debug mode is on.
|
| 15 |
+
func NewHTTPClient() *http.Client {
|
| 16 |
+
if !slog.Default().Enabled(context.TODO(), slog.LevelDebug) {
|
| 17 |
+
return http.DefaultClient
|
| 18 |
+
}
|
| 19 |
+
return &http.Client{
|
| 20 |
+
Transport: &HTTPRoundTripLogger{
|
| 21 |
+
Transport: http.DefaultTransport,
|
| 22 |
+
},
|
| 23 |
+
}
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
// HTTPRoundTripLogger is an http.RoundTripper that logs requests and responses.
|
| 27 |
+
type HTTPRoundTripLogger struct {
|
| 28 |
+
Transport http.RoundTripper
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
// RoundTrip implements http.RoundTripper interface with logging.
|
| 32 |
+
func (h *HTTPRoundTripLogger) RoundTrip(req *http.Request) (*http.Response, error) {
|
| 33 |
+
var err error
|
| 34 |
+
var save io.ReadCloser
|
| 35 |
+
save, req.Body, err = drainBody(req.Body)
|
| 36 |
+
if err != nil {
|
| 37 |
+
slog.Error(
|
| 38 |
+
"HTTP request failed",
|
| 39 |
+
"method", req.Method,
|
| 40 |
+
"url", req.URL,
|
| 41 |
+
"error", err,
|
| 42 |
+
)
|
| 43 |
+
return nil, err
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
slog.Debug(
|
| 47 |
+
"HTTP Request",
|
| 48 |
+
"method", req.Method,
|
| 49 |
+
"url", req.URL,
|
| 50 |
+
"body", bodyToString(save),
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
start := time.Now()
|
| 54 |
+
resp, err := h.Transport.RoundTrip(req)
|
| 55 |
+
duration := time.Since(start)
|
| 56 |
+
if err != nil {
|
| 57 |
+
slog.Error(
|
| 58 |
+
"HTTP request failed",
|
| 59 |
+
"method", req.Method,
|
| 60 |
+
"url", req.URL,
|
| 61 |
+
"duration_ms", duration.Milliseconds(),
|
| 62 |
+
"error", err,
|
| 63 |
+
)
|
| 64 |
+
return resp, err
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
save, resp.Body, err = drainBody(resp.Body)
|
| 68 |
+
slog.Debug(
|
| 69 |
+
"HTTP Response",
|
| 70 |
+
"status_code", resp.StatusCode,
|
| 71 |
+
"status", resp.Status,
|
| 72 |
+
"headers", formatHeaders(resp.Header),
|
| 73 |
+
"body", bodyToString(save),
|
| 74 |
+
"content_length", resp.ContentLength,
|
| 75 |
+
"duration_ms", duration.Milliseconds(),
|
| 76 |
+
"error", err,
|
| 77 |
+
)
|
| 78 |
+
return resp, err
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
func bodyToString(body io.ReadCloser) string {
|
| 82 |
+
if body == nil {
|
| 83 |
+
return ""
|
| 84 |
+
}
|
| 85 |
+
src, err := io.ReadAll(body)
|
| 86 |
+
if err != nil {
|
| 87 |
+
slog.Error("Failed to read body", "error", err)
|
| 88 |
+
return ""
|
| 89 |
+
}
|
| 90 |
+
var b bytes.Buffer
|
| 91 |
+
if json.Compact(&b, bytes.TrimSpace(src)) != nil {
|
| 92 |
+
// not json probably
|
| 93 |
+
return string(src)
|
| 94 |
+
}
|
| 95 |
+
return b.String()
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
// formatHeaders formats HTTP headers for logging, filtering out sensitive information.
|
| 99 |
+
func formatHeaders(headers http.Header) map[string][]string {
|
| 100 |
+
filtered := make(map[string][]string)
|
| 101 |
+
for key, values := range headers {
|
| 102 |
+
lowerKey := strings.ToLower(key)
|
| 103 |
+
// Filter out sensitive headers
|
| 104 |
+
if strings.Contains(lowerKey, "authorization") ||
|
| 105 |
+
strings.Contains(lowerKey, "api-key") ||
|
| 106 |
+
strings.Contains(lowerKey, "token") ||
|
| 107 |
+
strings.Contains(lowerKey, "secret") {
|
| 108 |
+
filtered[key] = []string{"[REDACTED]"}
|
| 109 |
+
} else {
|
| 110 |
+
filtered[key] = values
|
| 111 |
+
}
|
| 112 |
+
}
|
| 113 |
+
return filtered
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
func drainBody(b io.ReadCloser) (r1, r2 io.ReadCloser, err error) {
|
| 117 |
+
if b == nil || b == http.NoBody {
|
| 118 |
+
return http.NoBody, http.NoBody, nil
|
| 119 |
+
}
|
| 120 |
+
var buf bytes.Buffer
|
| 121 |
+
if _, err = buf.ReadFrom(b); err != nil {
|
| 122 |
+
return nil, b, err
|
| 123 |
+
}
|
| 124 |
+
if err = b.Close(); err != nil {
|
| 125 |
+
return nil, b, err
|
| 126 |
+
}
|
| 127 |
+
return io.NopCloser(&buf), io.NopCloser(bytes.NewReader(buf.Bytes())), nil
|
| 128 |
+
}
|
projects/ui/crush/internal/log/http_test.go
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package log
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"net/http"
|
| 5 |
+
"net/http/httptest"
|
| 6 |
+
"strings"
|
| 7 |
+
"testing"
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
func TestHTTPRoundTripLogger(t *testing.T) {
|
| 11 |
+
// Create a test server that returns a 500 error
|
| 12 |
+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
| 13 |
+
w.Header().Set("Content-Type", "application/json")
|
| 14 |
+
w.Header().Set("X-Custom-Header", "test-value")
|
| 15 |
+
w.WriteHeader(http.StatusInternalServerError)
|
| 16 |
+
w.Write([]byte(`{"error": "Internal server error", "code": 500}`))
|
| 17 |
+
}))
|
| 18 |
+
defer server.Close()
|
| 19 |
+
|
| 20 |
+
// Create HTTP client with logging
|
| 21 |
+
client := NewHTTPClient()
|
| 22 |
+
|
| 23 |
+
// Make a request
|
| 24 |
+
req, err := http.NewRequestWithContext(
|
| 25 |
+
t.Context(),
|
| 26 |
+
http.MethodPost,
|
| 27 |
+
server.URL,
|
| 28 |
+
strings.NewReader(`{"test": "data"}`),
|
| 29 |
+
)
|
| 30 |
+
if err != nil {
|
| 31 |
+
t.Fatal(err)
|
| 32 |
+
}
|
| 33 |
+
req.Header.Set("Content-Type", "application/json")
|
| 34 |
+
req.Header.Set("Authorization", "Bearer secret-token")
|
| 35 |
+
|
| 36 |
+
resp, err := client.Do(req)
|
| 37 |
+
if err != nil {
|
| 38 |
+
t.Fatal(err)
|
| 39 |
+
}
|
| 40 |
+
defer resp.Body.Close()
|
| 41 |
+
|
| 42 |
+
// Verify response
|
| 43 |
+
if resp.StatusCode != http.StatusInternalServerError {
|
| 44 |
+
t.Errorf("Expected status code 500, got %d", resp.StatusCode)
|
| 45 |
+
}
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
func TestFormatHeaders(t *testing.T) {
|
| 49 |
+
headers := http.Header{
|
| 50 |
+
"Content-Type": []string{"application/json"},
|
| 51 |
+
"Authorization": []string{"Bearer secret-token"},
|
| 52 |
+
"X-API-Key": []string{"api-key-123"},
|
| 53 |
+
"User-Agent": []string{"test-agent"},
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
formatted := formatHeaders(headers)
|
| 57 |
+
|
| 58 |
+
// Check that sensitive headers are redacted
|
| 59 |
+
if formatted["Authorization"][0] != "[REDACTED]" {
|
| 60 |
+
t.Error("Authorization header should be redacted")
|
| 61 |
+
}
|
| 62 |
+
if formatted["X-API-Key"][0] != "[REDACTED]" {
|
| 63 |
+
t.Error("X-API-Key header should be redacted")
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
// Check that non-sensitive headers are preserved
|
| 67 |
+
if formatted["Content-Type"][0] != "application/json" {
|
| 68 |
+
t.Error("Content-Type header should be preserved")
|
| 69 |
+
}
|
| 70 |
+
if formatted["User-Agent"][0] != "test-agent" {
|
| 71 |
+
t.Error("User-Agent header should be preserved")
|
| 72 |
+
}
|
| 73 |
+
}
|
projects/ui/crush/internal/log/log.go
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package log
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"fmt"
|
| 5 |
+
"log/slog"
|
| 6 |
+
"os"
|
| 7 |
+
"runtime/debug"
|
| 8 |
+
"sync"
|
| 9 |
+
"sync/atomic"
|
| 10 |
+
"time"
|
| 11 |
+
|
| 12 |
+
"gopkg.in/natefinch/lumberjack.v2"
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
var (
|
| 16 |
+
initOnce sync.Once
|
| 17 |
+
initialized atomic.Bool
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
func Setup(logFile string, debug bool) {
|
| 21 |
+
initOnce.Do(func() {
|
| 22 |
+
logRotator := &lumberjack.Logger{
|
| 23 |
+
Filename: logFile,
|
| 24 |
+
MaxSize: 10, // Max size in MB
|
| 25 |
+
MaxBackups: 0, // Number of backups
|
| 26 |
+
MaxAge: 30, // Days
|
| 27 |
+
Compress: false, // Enable compression
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
level := slog.LevelInfo
|
| 31 |
+
if debug {
|
| 32 |
+
level = slog.LevelDebug
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
logger := slog.NewJSONHandler(logRotator, &slog.HandlerOptions{
|
| 36 |
+
Level: level,
|
| 37 |
+
AddSource: true,
|
| 38 |
+
})
|
| 39 |
+
|
| 40 |
+
slog.SetDefault(slog.New(logger))
|
| 41 |
+
initialized.Store(true)
|
| 42 |
+
})
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
func Initialized() bool {
|
| 46 |
+
return initialized.Load()
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
func RecoverPanic(name string, cleanup func()) {
|
| 50 |
+
if r := recover(); r != nil {
|
| 51 |
+
// Create a timestamped panic log file
|
| 52 |
+
timestamp := time.Now().Format("20060102-150405")
|
| 53 |
+
filename := fmt.Sprintf("crush-panic-%s-%s.log", name, timestamp)
|
| 54 |
+
|
| 55 |
+
file, err := os.Create(filename)
|
| 56 |
+
if err == nil {
|
| 57 |
+
defer file.Close()
|
| 58 |
+
|
| 59 |
+
// Write panic information and stack trace
|
| 60 |
+
fmt.Fprintf(file, "Panic in %s: %v\n\n", name, r)
|
| 61 |
+
fmt.Fprintf(file, "Time: %s\n\n", time.Now().Format(time.RFC3339))
|
| 62 |
+
fmt.Fprintf(file, "Stack Trace:\n%s\n", debug.Stack())
|
| 63 |
+
|
| 64 |
+
// Execute cleanup function if provided
|
| 65 |
+
if cleanup != nil {
|
| 66 |
+
cleanup()
|
| 67 |
+
}
|
| 68 |
+
}
|
| 69 |
+
}
|
| 70 |
+
}
|
projects/ui/crush/internal/lsp/caps.go
ADDED
|
@@ -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: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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package lsp
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"bufio"
|
| 5 |
+
"context"
|
| 6 |
+
"encoding/json"
|
| 7 |
+
"fmt"
|
| 8 |
+
"io"
|
| 9 |
+
"log/slog"
|
| 10 |
+
"maps"
|
| 11 |
+
"os"
|
| 12 |
+
"os/exec"
|
| 13 |
+
"path/filepath"
|
| 14 |
+
"slices"
|
| 15 |
+
"strings"
|
| 16 |
+
"sync"
|
| 17 |
+
"sync/atomic"
|
| 18 |
+
"time"
|
| 19 |
+
|
| 20 |
+
"github.com/charmbracelet/crush/internal/config"
|
| 21 |
+
"github.com/charmbracelet/crush/internal/log"
|
| 22 |
+
"github.com/charmbracelet/crush/internal/lsp/protocol"
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
type Client struct {
|
| 26 |
+
Cmd *exec.Cmd
|
| 27 |
+
stdin io.WriteCloser
|
| 28 |
+
stdout *bufio.Reader
|
| 29 |
+
stderr io.ReadCloser
|
| 30 |
+
|
| 31 |
+
// Client name for identification
|
| 32 |
+
name string
|
| 33 |
+
|
| 34 |
+
// File types this LSP server handles (e.g., .go, .rs, .py)
|
| 35 |
+
fileTypes []string
|
| 36 |
+
|
| 37 |
+
// Diagnostic change callback
|
| 38 |
+
onDiagnosticsChanged func(name string, count int)
|
| 39 |
+
|
| 40 |
+
// Request ID counter
|
| 41 |
+
nextID atomic.Int32
|
| 42 |
+
|
| 43 |
+
// Response handlers
|
| 44 |
+
handlers map[int32]chan *Message
|
| 45 |
+
handlersMu sync.RWMutex
|
| 46 |
+
|
| 47 |
+
// Server request handlers
|
| 48 |
+
serverRequestHandlers map[string]ServerRequestHandler
|
| 49 |
+
serverHandlersMu sync.RWMutex
|
| 50 |
+
|
| 51 |
+
// Notification handlers
|
| 52 |
+
notificationHandlers map[string]NotificationHandler
|
| 53 |
+
notificationMu sync.RWMutex
|
| 54 |
+
|
| 55 |
+
// Diagnostic cache
|
| 56 |
+
diagnostics map[protocol.DocumentURI][]protocol.Diagnostic
|
| 57 |
+
diagnosticsMu sync.RWMutex
|
| 58 |
+
|
| 59 |
+
// Files are currently opened by the LSP
|
| 60 |
+
openFiles map[string]*OpenFileInfo
|
| 61 |
+
openFilesMu sync.RWMutex
|
| 62 |
+
|
| 63 |
+
// Server state
|
| 64 |
+
serverState atomic.Value
|
| 65 |
+
|
| 66 |
+
// Server capabilities as returned by initialize
|
| 67 |
+
caps protocol.ServerCapabilities
|
| 68 |
+
capsMu sync.RWMutex
|
| 69 |
+
capsSet atomic.Bool
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
// NewClient creates a new LSP client.
|
| 73 |
+
func NewClient(ctx context.Context, name string, config config.LSPConfig) (*Client, error) {
|
| 74 |
+
cmd := exec.CommandContext(ctx, config.Command, config.Args...)
|
| 75 |
+
|
| 76 |
+
// Copy env
|
| 77 |
+
cmd.Env = slices.Concat(os.Environ(), config.ResolvedEnv())
|
| 78 |
+
|
| 79 |
+
stdin, err := cmd.StdinPipe()
|
| 80 |
+
if err != nil {
|
| 81 |
+
return nil, fmt.Errorf("failed to create stdin pipe: %w", err)
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
stdout, err := cmd.StdoutPipe()
|
| 85 |
+
if err != nil {
|
| 86 |
+
return nil, fmt.Errorf("failed to create stdout pipe: %w", err)
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
stderr, err := cmd.StderrPipe()
|
| 90 |
+
if err != nil {
|
| 91 |
+
return nil, fmt.Errorf("failed to create stderr pipe: %w", err)
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
client := &Client{
|
| 95 |
+
Cmd: cmd,
|
| 96 |
+
name: name,
|
| 97 |
+
fileTypes: config.FileTypes,
|
| 98 |
+
stdin: stdin,
|
| 99 |
+
stdout: bufio.NewReader(stdout),
|
| 100 |
+
stderr: stderr,
|
| 101 |
+
handlers: make(map[int32]chan *Message),
|
| 102 |
+
notificationHandlers: make(map[string]NotificationHandler),
|
| 103 |
+
serverRequestHandlers: make(map[string]ServerRequestHandler),
|
| 104 |
+
diagnostics: make(map[protocol.DocumentURI][]protocol.Diagnostic),
|
| 105 |
+
openFiles: make(map[string]*OpenFileInfo),
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
// Initialize server state
|
| 109 |
+
client.serverState.Store(StateStarting)
|
| 110 |
+
|
| 111 |
+
// Start the LSP server process
|
| 112 |
+
if err := cmd.Start(); err != nil {
|
| 113 |
+
return nil, fmt.Errorf("failed to start LSP server: %w", err)
|
| 114 |
+
}
|
| 115 |
+
|
| 116 |
+
// Handle stderr in a separate goroutine
|
| 117 |
+
go func() {
|
| 118 |
+
scanner := bufio.NewScanner(stderr)
|
| 119 |
+
for scanner.Scan() {
|
| 120 |
+
slog.Error("LSP Server", "err", scanner.Text())
|
| 121 |
+
}
|
| 122 |
+
if err := scanner.Err(); err != nil {
|
| 123 |
+
slog.Error("Error reading", "err", err)
|
| 124 |
+
}
|
| 125 |
+
}()
|
| 126 |
+
|
| 127 |
+
// Start message handling loop
|
| 128 |
+
go func() {
|
| 129 |
+
defer log.RecoverPanic("LSP-message-handler", func() {
|
| 130 |
+
slog.Error("LSP message handler crashed, LSP functionality may be impaired")
|
| 131 |
+
})
|
| 132 |
+
client.handleMessages()
|
| 133 |
+
}()
|
| 134 |
+
|
| 135 |
+
return client, nil
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
func (c *Client) RegisterNotificationHandler(method string, handler NotificationHandler) {
|
| 139 |
+
c.notificationMu.Lock()
|
| 140 |
+
defer c.notificationMu.Unlock()
|
| 141 |
+
c.notificationHandlers[method] = handler
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
func (c *Client) RegisterServerRequestHandler(method string, handler ServerRequestHandler) {
|
| 145 |
+
c.serverHandlersMu.Lock()
|
| 146 |
+
defer c.serverHandlersMu.Unlock()
|
| 147 |
+
c.serverRequestHandlers[method] = handler
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
func (c *Client) InitializeLSPClient(ctx context.Context, workspaceDir string) (*protocol.InitializeResult, error) {
|
| 151 |
+
initParams := protocol.ParamInitialize{
|
| 152 |
+
WorkspaceFoldersInitializeParams: protocol.WorkspaceFoldersInitializeParams{
|
| 153 |
+
WorkspaceFolders: []protocol.WorkspaceFolder{
|
| 154 |
+
{
|
| 155 |
+
URI: protocol.URI(protocol.URIFromPath(workspaceDir)),
|
| 156 |
+
Name: workspaceDir,
|
| 157 |
+
},
|
| 158 |
+
},
|
| 159 |
+
},
|
| 160 |
+
|
| 161 |
+
XInitializeParams: protocol.XInitializeParams{
|
| 162 |
+
ProcessID: int32(os.Getpid()),
|
| 163 |
+
ClientInfo: &protocol.ClientInfo{
|
| 164 |
+
Name: "mcp-language-server",
|
| 165 |
+
Version: "0.1.0",
|
| 166 |
+
},
|
| 167 |
+
RootPath: workspaceDir,
|
| 168 |
+
RootURI: protocol.URIFromPath(workspaceDir),
|
| 169 |
+
Capabilities: protocol.ClientCapabilities{
|
| 170 |
+
Workspace: protocol.WorkspaceClientCapabilities{
|
| 171 |
+
Configuration: true,
|
| 172 |
+
DidChangeConfiguration: protocol.DidChangeConfigurationClientCapabilities{
|
| 173 |
+
DynamicRegistration: true,
|
| 174 |
+
},
|
| 175 |
+
DidChangeWatchedFiles: protocol.DidChangeWatchedFilesClientCapabilities{
|
| 176 |
+
DynamicRegistration: true,
|
| 177 |
+
RelativePatternSupport: true,
|
| 178 |
+
},
|
| 179 |
+
},
|
| 180 |
+
TextDocument: protocol.TextDocumentClientCapabilities{
|
| 181 |
+
Synchronization: &protocol.TextDocumentSyncClientCapabilities{
|
| 182 |
+
DynamicRegistration: true,
|
| 183 |
+
DidSave: true,
|
| 184 |
+
},
|
| 185 |
+
Completion: protocol.CompletionClientCapabilities{
|
| 186 |
+
CompletionItem: protocol.ClientCompletionItemOptions{},
|
| 187 |
+
},
|
| 188 |
+
CodeLens: &protocol.CodeLensClientCapabilities{
|
| 189 |
+
DynamicRegistration: true,
|
| 190 |
+
},
|
| 191 |
+
DocumentSymbol: protocol.DocumentSymbolClientCapabilities{},
|
| 192 |
+
CodeAction: protocol.CodeActionClientCapabilities{
|
| 193 |
+
CodeActionLiteralSupport: protocol.ClientCodeActionLiteralOptions{
|
| 194 |
+
CodeActionKind: protocol.ClientCodeActionKindOptions{
|
| 195 |
+
ValueSet: []protocol.CodeActionKind{},
|
| 196 |
+
},
|
| 197 |
+
},
|
| 198 |
+
},
|
| 199 |
+
PublishDiagnostics: protocol.PublishDiagnosticsClientCapabilities{
|
| 200 |
+
VersionSupport: true,
|
| 201 |
+
},
|
| 202 |
+
SemanticTokens: protocol.SemanticTokensClientCapabilities{
|
| 203 |
+
Requests: protocol.ClientSemanticTokensRequestOptions{
|
| 204 |
+
Range: &protocol.Or_ClientSemanticTokensRequestOptions_range{},
|
| 205 |
+
Full: &protocol.Or_ClientSemanticTokensRequestOptions_full{},
|
| 206 |
+
},
|
| 207 |
+
TokenTypes: []string{},
|
| 208 |
+
TokenModifiers: []string{},
|
| 209 |
+
Formats: []protocol.TokenFormat{},
|
| 210 |
+
},
|
| 211 |
+
},
|
| 212 |
+
Window: protocol.WindowClientCapabilities{},
|
| 213 |
+
},
|
| 214 |
+
InitializationOptions: map[string]any{
|
| 215 |
+
"codelenses": map[string]bool{
|
| 216 |
+
"generate": true,
|
| 217 |
+
"regenerate_cgo": true,
|
| 218 |
+
"test": true,
|
| 219 |
+
"tidy": true,
|
| 220 |
+
"upgrade_dependency": true,
|
| 221 |
+
"vendor": true,
|
| 222 |
+
"vulncheck": false,
|
| 223 |
+
},
|
| 224 |
+
},
|
| 225 |
+
},
|
| 226 |
+
}
|
| 227 |
+
|
| 228 |
+
result, err := c.Initialize(ctx, initParams)
|
| 229 |
+
if err != nil {
|
| 230 |
+
return nil, fmt.Errorf("initialize failed: %w", err)
|
| 231 |
+
}
|
| 232 |
+
|
| 233 |
+
c.setCapabilities(result.Capabilities)
|
| 234 |
+
|
| 235 |
+
if err := c.Initialized(ctx, protocol.InitializedParams{}); err != nil {
|
| 236 |
+
return nil, fmt.Errorf("initialized notification failed: %w", err)
|
| 237 |
+
}
|
| 238 |
+
|
| 239 |
+
// Register handlers
|
| 240 |
+
c.RegisterServerRequestHandler("workspace/applyEdit", HandleApplyEdit)
|
| 241 |
+
c.RegisterServerRequestHandler("workspace/configuration", HandleWorkspaceConfiguration)
|
| 242 |
+
c.RegisterServerRequestHandler("client/registerCapability", HandleRegisterCapability)
|
| 243 |
+
c.RegisterNotificationHandler("window/showMessage", HandleServerMessage)
|
| 244 |
+
c.RegisterNotificationHandler("textDocument/publishDiagnostics", func(params json.RawMessage) {
|
| 245 |
+
HandleDiagnostics(c, params)
|
| 246 |
+
})
|
| 247 |
+
|
| 248 |
+
return &result, nil
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
func (c *Client) Close() error {
|
| 252 |
+
// Try to close all open files first
|
| 253 |
+
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
| 254 |
+
defer cancel()
|
| 255 |
+
|
| 256 |
+
// Attempt to close files but continue shutdown regardless
|
| 257 |
+
c.CloseAllFiles(ctx)
|
| 258 |
+
|
| 259 |
+
// Close stdin to signal the server
|
| 260 |
+
if err := c.stdin.Close(); err != nil {
|
| 261 |
+
return fmt.Errorf("failed to close stdin: %w", err)
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
// Use a channel to handle the Wait with timeout
|
| 265 |
+
done := make(chan error, 1)
|
| 266 |
+
go func() {
|
| 267 |
+
done <- c.Cmd.Wait()
|
| 268 |
+
}()
|
| 269 |
+
|
| 270 |
+
// Wait for process to exit with timeout
|
| 271 |
+
select {
|
| 272 |
+
case err := <-done:
|
| 273 |
+
return err
|
| 274 |
+
case <-time.After(2 * time.Second):
|
| 275 |
+
// If we timeout, try to kill the process
|
| 276 |
+
if err := c.Cmd.Process.Kill(); err != nil {
|
| 277 |
+
return fmt.Errorf("failed to kill process: %w", err)
|
| 278 |
+
}
|
| 279 |
+
return fmt.Errorf("process killed after timeout")
|
| 280 |
+
}
|
| 281 |
+
}
|
| 282 |
+
|
| 283 |
+
type ServerState int
|
| 284 |
+
|
| 285 |
+
const (
|
| 286 |
+
StateStarting ServerState = iota
|
| 287 |
+
StateReady
|
| 288 |
+
StateError
|
| 289 |
+
)
|
| 290 |
+
|
| 291 |
+
// GetServerState returns the current state of the LSP server
|
| 292 |
+
func (c *Client) GetServerState() ServerState {
|
| 293 |
+
if val := c.serverState.Load(); val != nil {
|
| 294 |
+
return val.(ServerState)
|
| 295 |
+
}
|
| 296 |
+
return StateStarting
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
// SetServerState sets the current state of the LSP server
|
| 300 |
+
func (c *Client) SetServerState(state ServerState) {
|
| 301 |
+
c.serverState.Store(state)
|
| 302 |
+
}
|
| 303 |
+
|
| 304 |
+
// GetName returns the name of the LSP client
|
| 305 |
+
func (c *Client) GetName() string {
|
| 306 |
+
return c.name
|
| 307 |
+
}
|
| 308 |
+
|
| 309 |
+
// SetDiagnosticsCallback sets the callback function for diagnostic changes
|
| 310 |
+
func (c *Client) SetDiagnosticsCallback(callback func(name string, count int)) {
|
| 311 |
+
c.onDiagnosticsChanged = callback
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
// WaitForServerReady waits for the server to be ready by polling the server
|
| 315 |
+
// with a simple request until it responds successfully or times out
|
| 316 |
+
func (c *Client) WaitForServerReady(ctx context.Context) error {
|
| 317 |
+
cfg := config.Get()
|
| 318 |
+
|
| 319 |
+
// Set initial state
|
| 320 |
+
c.SetServerState(StateStarting)
|
| 321 |
+
|
| 322 |
+
// Create a context with timeout
|
| 323 |
+
ctx, cancel := context.WithTimeout(ctx, 30*time.Second)
|
| 324 |
+
defer cancel()
|
| 325 |
+
|
| 326 |
+
// Try to ping the server with a simple request
|
| 327 |
+
ticker := time.NewTicker(500 * time.Millisecond)
|
| 328 |
+
defer ticker.Stop()
|
| 329 |
+
|
| 330 |
+
if cfg.Options.DebugLSP {
|
| 331 |
+
slog.Debug("Waiting for LSP server to be ready...")
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
c.openKeyConfigFiles(ctx)
|
| 335 |
+
|
| 336 |
+
for {
|
| 337 |
+
select {
|
| 338 |
+
case <-ctx.Done():
|
| 339 |
+
c.SetServerState(StateError)
|
| 340 |
+
return fmt.Errorf("timeout waiting for LSP server to be ready")
|
| 341 |
+
case <-ticker.C:
|
| 342 |
+
// Try a ping method appropriate for this server type
|
| 343 |
+
if err := c.ping(ctx); err != nil {
|
| 344 |
+
if cfg.Options.DebugLSP {
|
| 345 |
+
slog.Debug("LSP server not ready yet", "error", err, "server", c.name)
|
| 346 |
+
}
|
| 347 |
+
continue
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
// Server responded successfully
|
| 351 |
+
c.SetServerState(StateReady)
|
| 352 |
+
if cfg.Options.DebugLSP {
|
| 353 |
+
slog.Debug("LSP server is ready")
|
| 354 |
+
}
|
| 355 |
+
return nil
|
| 356 |
+
}
|
| 357 |
+
}
|
| 358 |
+
}
|
| 359 |
+
|
| 360 |
+
// ServerType represents the type of LSP server
|
| 361 |
+
type ServerType int
|
| 362 |
+
|
| 363 |
+
const (
|
| 364 |
+
ServerTypeUnknown ServerType = iota
|
| 365 |
+
ServerTypeGo
|
| 366 |
+
ServerTypeTypeScript
|
| 367 |
+
ServerTypeRust
|
| 368 |
+
ServerTypePython
|
| 369 |
+
ServerTypeGeneric
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
// detectServerType tries to determine what type of LSP server we're dealing with
|
| 373 |
+
func (c *Client) detectServerType() ServerType {
|
| 374 |
+
if c.Cmd == nil {
|
| 375 |
+
return ServerTypeUnknown
|
| 376 |
+
}
|
| 377 |
+
|
| 378 |
+
cmdPath := strings.ToLower(c.Cmd.Path)
|
| 379 |
+
|
| 380 |
+
switch {
|
| 381 |
+
case strings.Contains(cmdPath, "gopls"):
|
| 382 |
+
return ServerTypeGo
|
| 383 |
+
case strings.Contains(cmdPath, "typescript") || strings.Contains(cmdPath, "vtsls") || strings.Contains(cmdPath, "tsserver"):
|
| 384 |
+
return ServerTypeTypeScript
|
| 385 |
+
case strings.Contains(cmdPath, "rust-analyzer"):
|
| 386 |
+
return ServerTypeRust
|
| 387 |
+
case strings.Contains(cmdPath, "pyright") || strings.Contains(cmdPath, "pylsp") || strings.Contains(cmdPath, "python"):
|
| 388 |
+
return ServerTypePython
|
| 389 |
+
default:
|
| 390 |
+
return ServerTypeGeneric
|
| 391 |
+
}
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
+
// openKeyConfigFiles opens important configuration files that help initialize the server
|
| 395 |
+
func (c *Client) openKeyConfigFiles(ctx context.Context) {
|
| 396 |
+
workDir := config.Get().WorkingDir()
|
| 397 |
+
serverType := c.detectServerType()
|
| 398 |
+
|
| 399 |
+
var filesToOpen []string
|
| 400 |
+
|
| 401 |
+
switch serverType {
|
| 402 |
+
case ServerTypeTypeScript:
|
| 403 |
+
// TypeScript servers need these config files to properly initialize
|
| 404 |
+
filesToOpen = []string{
|
| 405 |
+
filepath.Join(workDir, "tsconfig.json"),
|
| 406 |
+
filepath.Join(workDir, "package.json"),
|
| 407 |
+
filepath.Join(workDir, "jsconfig.json"),
|
| 408 |
+
}
|
| 409 |
+
|
| 410 |
+
// Also find and open a few TypeScript files to help the server initialize
|
| 411 |
+
c.openTypeScriptFiles(ctx, workDir)
|
| 412 |
+
case ServerTypeGo:
|
| 413 |
+
filesToOpen = []string{
|
| 414 |
+
filepath.Join(workDir, "go.mod"),
|
| 415 |
+
filepath.Join(workDir, "go.sum"),
|
| 416 |
+
}
|
| 417 |
+
case ServerTypeRust:
|
| 418 |
+
filesToOpen = []string{
|
| 419 |
+
filepath.Join(workDir, "Cargo.toml"),
|
| 420 |
+
filepath.Join(workDir, "Cargo.lock"),
|
| 421 |
+
}
|
| 422 |
+
}
|
| 423 |
+
|
| 424 |
+
// Try to open each file, ignoring errors if they don't exist
|
| 425 |
+
for _, file := range filesToOpen {
|
| 426 |
+
if _, err := os.Stat(file); err == nil {
|
| 427 |
+
// File exists, try to open it
|
| 428 |
+
if err := c.OpenFile(ctx, file); err != nil {
|
| 429 |
+
slog.Debug("Failed to open key config file", "file", file, "error", err)
|
| 430 |
+
} else {
|
| 431 |
+
slog.Debug("Opened key config file for initialization", "file", file)
|
| 432 |
+
}
|
| 433 |
+
}
|
| 434 |
+
}
|
| 435 |
+
}
|
| 436 |
+
|
| 437 |
+
// ping sends a ping request...
|
| 438 |
+
func (c *Client) ping(ctx context.Context) error {
|
| 439 |
+
if _, err := c.Symbol(ctx, protocol.WorkspaceSymbolParams{}); err == nil {
|
| 440 |
+
return nil
|
| 441 |
+
}
|
| 442 |
+
// This is a very lightweight request that should work for most servers
|
| 443 |
+
return c.Notify(ctx, "$/cancelRequest", protocol.CancelParams{ID: "1"})
|
| 444 |
+
}
|
| 445 |
+
|
| 446 |
+
// openTypeScriptFiles finds and opens TypeScript files to help initialize the server
|
| 447 |
+
func (c *Client) openTypeScriptFiles(ctx context.Context, workDir string) {
|
| 448 |
+
cfg := config.Get()
|
| 449 |
+
filesOpened := 0
|
| 450 |
+
maxFilesToOpen := 5 // Limit to a reasonable number of files
|
| 451 |
+
|
| 452 |
+
// Find and open TypeScript files
|
| 453 |
+
err := filepath.WalkDir(workDir, func(path string, d os.DirEntry, err error) error {
|
| 454 |
+
if err != nil {
|
| 455 |
+
return err
|
| 456 |
+
}
|
| 457 |
+
|
| 458 |
+
// Skip directories and non-TypeScript files
|
| 459 |
+
if d.IsDir() {
|
| 460 |
+
// Skip common directories to avoid wasting time
|
| 461 |
+
if shouldSkipDir(path) {
|
| 462 |
+
return filepath.SkipDir
|
| 463 |
+
}
|
| 464 |
+
return nil
|
| 465 |
+
}
|
| 466 |
+
|
| 467 |
+
// Check if we've opened enough files
|
| 468 |
+
if filesOpened >= maxFilesToOpen {
|
| 469 |
+
return filepath.SkipAll
|
| 470 |
+
}
|
| 471 |
+
|
| 472 |
+
// Check file extension
|
| 473 |
+
ext := filepath.Ext(path)
|
| 474 |
+
if ext == ".ts" || ext == ".tsx" || ext == ".js" || ext == ".jsx" {
|
| 475 |
+
// Try to open the file
|
| 476 |
+
if err := c.OpenFile(ctx, path); err == nil {
|
| 477 |
+
filesOpened++
|
| 478 |
+
if cfg.Options.DebugLSP {
|
| 479 |
+
slog.Debug("Opened TypeScript file for initialization", "file", path)
|
| 480 |
+
}
|
| 481 |
+
}
|
| 482 |
+
}
|
| 483 |
+
|
| 484 |
+
return nil
|
| 485 |
+
})
|
| 486 |
+
|
| 487 |
+
if err != nil && cfg.Options.DebugLSP {
|
| 488 |
+
slog.Debug("Error walking directory for TypeScript files", "error", err)
|
| 489 |
+
}
|
| 490 |
+
|
| 491 |
+
if cfg.Options.DebugLSP {
|
| 492 |
+
slog.Debug("Opened TypeScript files for initialization", "count", filesOpened)
|
| 493 |
+
}
|
| 494 |
+
}
|
| 495 |
+
|
| 496 |
+
// shouldSkipDir returns true if the directory should be skipped during file search
|
| 497 |
+
func shouldSkipDir(path string) bool {
|
| 498 |
+
dirName := filepath.Base(path)
|
| 499 |
+
|
| 500 |
+
// Skip hidden directories
|
| 501 |
+
if strings.HasPrefix(dirName, ".") {
|
| 502 |
+
return true
|
| 503 |
+
}
|
| 504 |
+
|
| 505 |
+
// Skip common directories that won't contain relevant source files
|
| 506 |
+
skipDirs := map[string]bool{
|
| 507 |
+
"node_modules": true,
|
| 508 |
+
"dist": true,
|
| 509 |
+
"build": true,
|
| 510 |
+
"coverage": true,
|
| 511 |
+
"vendor": true,
|
| 512 |
+
"target": true,
|
| 513 |
+
}
|
| 514 |
+
|
| 515 |
+
return skipDirs[dirName]
|
| 516 |
+
}
|
| 517 |
+
|
| 518 |
+
type OpenFileInfo struct {
|
| 519 |
+
Version int32
|
| 520 |
+
URI protocol.DocumentURI
|
| 521 |
+
}
|
| 522 |
+
|
| 523 |
+
// HandlesFile checks if this LSP client handles the given file based on its
|
| 524 |
+
// extension.
|
| 525 |
+
func (c *Client) HandlesFile(path string) bool {
|
| 526 |
+
// If no file types are specified, handle all files (backward compatibility)
|
| 527 |
+
if len(c.fileTypes) == 0 {
|
| 528 |
+
return true
|
| 529 |
+
}
|
| 530 |
+
|
| 531 |
+
name := strings.ToLower(filepath.Base(path))
|
| 532 |
+
for _, filetpe := range c.fileTypes {
|
| 533 |
+
suffix := strings.ToLower(filetpe)
|
| 534 |
+
if !strings.HasPrefix(suffix, ".") {
|
| 535 |
+
suffix = "." + suffix
|
| 536 |
+
}
|
| 537 |
+
if strings.HasSuffix(name, suffix) {
|
| 538 |
+
slog.Debug("handles file", "name", c.name, "file", name, "filetype", filetpe)
|
| 539 |
+
return true
|
| 540 |
+
}
|
| 541 |
+
}
|
| 542 |
+
slog.Debug("doesn't handle file", "name", c.name, "file", name)
|
| 543 |
+
return false
|
| 544 |
+
}
|
| 545 |
+
|
| 546 |
+
func (c *Client) OpenFile(ctx context.Context, filepath string) error {
|
| 547 |
+
if !c.HandlesFile(filepath) {
|
| 548 |
+
return nil
|
| 549 |
+
}
|
| 550 |
+
|
| 551 |
+
uri := string(protocol.URIFromPath(filepath))
|
| 552 |
+
|
| 553 |
+
c.openFilesMu.Lock()
|
| 554 |
+
if _, exists := c.openFiles[uri]; exists {
|
| 555 |
+
c.openFilesMu.Unlock()
|
| 556 |
+
return nil // Already open
|
| 557 |
+
}
|
| 558 |
+
c.openFilesMu.Unlock()
|
| 559 |
+
|
| 560 |
+
// Skip files that do not exist or cannot be read
|
| 561 |
+
content, err := os.ReadFile(filepath)
|
| 562 |
+
if err != nil {
|
| 563 |
+
return fmt.Errorf("error reading file: %w", err)
|
| 564 |
+
}
|
| 565 |
+
|
| 566 |
+
params := protocol.DidOpenTextDocumentParams{
|
| 567 |
+
TextDocument: protocol.TextDocumentItem{
|
| 568 |
+
URI: protocol.DocumentURI(uri),
|
| 569 |
+
LanguageID: DetectLanguageID(uri),
|
| 570 |
+
Version: 1,
|
| 571 |
+
Text: string(content),
|
| 572 |
+
},
|
| 573 |
+
}
|
| 574 |
+
|
| 575 |
+
if err := c.DidOpen(ctx, params); err != nil {
|
| 576 |
+
return err
|
| 577 |
+
}
|
| 578 |
+
|
| 579 |
+
c.openFilesMu.Lock()
|
| 580 |
+
c.openFiles[uri] = &OpenFileInfo{
|
| 581 |
+
Version: 1,
|
| 582 |
+
URI: protocol.DocumentURI(uri),
|
| 583 |
+
}
|
| 584 |
+
c.openFilesMu.Unlock()
|
| 585 |
+
|
| 586 |
+
return nil
|
| 587 |
+
}
|
| 588 |
+
|
| 589 |
+
func (c *Client) NotifyChange(ctx context.Context, filepath string) error {
|
| 590 |
+
uri := string(protocol.URIFromPath(filepath))
|
| 591 |
+
|
| 592 |
+
content, err := os.ReadFile(filepath)
|
| 593 |
+
if err != nil {
|
| 594 |
+
return fmt.Errorf("error reading file: %w", err)
|
| 595 |
+
}
|
| 596 |
+
|
| 597 |
+
c.openFilesMu.Lock()
|
| 598 |
+
fileInfo, isOpen := c.openFiles[uri]
|
| 599 |
+
if !isOpen {
|
| 600 |
+
c.openFilesMu.Unlock()
|
| 601 |
+
return fmt.Errorf("cannot notify change for unopened file: %s", filepath)
|
| 602 |
+
}
|
| 603 |
+
|
| 604 |
+
// Increment version
|
| 605 |
+
fileInfo.Version++
|
| 606 |
+
version := fileInfo.Version
|
| 607 |
+
c.openFilesMu.Unlock()
|
| 608 |
+
|
| 609 |
+
params := protocol.DidChangeTextDocumentParams{
|
| 610 |
+
TextDocument: protocol.VersionedTextDocumentIdentifier{
|
| 611 |
+
TextDocumentIdentifier: protocol.TextDocumentIdentifier{
|
| 612 |
+
URI: protocol.DocumentURI(uri),
|
| 613 |
+
},
|
| 614 |
+
Version: version,
|
| 615 |
+
},
|
| 616 |
+
ContentChanges: []protocol.TextDocumentContentChangeEvent{
|
| 617 |
+
{
|
| 618 |
+
Value: protocol.TextDocumentContentChangeWholeDocument{
|
| 619 |
+
Text: string(content),
|
| 620 |
+
},
|
| 621 |
+
},
|
| 622 |
+
},
|
| 623 |
+
}
|
| 624 |
+
|
| 625 |
+
return c.DidChange(ctx, params)
|
| 626 |
+
}
|
| 627 |
+
|
| 628 |
+
func (c *Client) CloseFile(ctx context.Context, filepath string) error {
|
| 629 |
+
cfg := config.Get()
|
| 630 |
+
uri := string(protocol.URIFromPath(filepath))
|
| 631 |
+
|
| 632 |
+
c.openFilesMu.Lock()
|
| 633 |
+
if _, exists := c.openFiles[uri]; !exists {
|
| 634 |
+
c.openFilesMu.Unlock()
|
| 635 |
+
return nil // Already closed
|
| 636 |
+
}
|
| 637 |
+
c.openFilesMu.Unlock()
|
| 638 |
+
|
| 639 |
+
params := protocol.DidCloseTextDocumentParams{
|
| 640 |
+
TextDocument: protocol.TextDocumentIdentifier{
|
| 641 |
+
URI: protocol.DocumentURI(uri),
|
| 642 |
+
},
|
| 643 |
+
}
|
| 644 |
+
|
| 645 |
+
if cfg.Options.DebugLSP {
|
| 646 |
+
slog.Debug("Closing file", "file", filepath)
|
| 647 |
+
}
|
| 648 |
+
if err := c.DidClose(ctx, params); err != nil {
|
| 649 |
+
return err
|
| 650 |
+
}
|
| 651 |
+
|
| 652 |
+
c.openFilesMu.Lock()
|
| 653 |
+
delete(c.openFiles, uri)
|
| 654 |
+
c.openFilesMu.Unlock()
|
| 655 |
+
|
| 656 |
+
return nil
|
| 657 |
+
}
|
| 658 |
+
|
| 659 |
+
func (c *Client) IsFileOpen(filepath string) bool {
|
| 660 |
+
uri := string(protocol.URIFromPath(filepath))
|
| 661 |
+
c.openFilesMu.RLock()
|
| 662 |
+
defer c.openFilesMu.RUnlock()
|
| 663 |
+
_, exists := c.openFiles[uri]
|
| 664 |
+
return exists
|
| 665 |
+
}
|
| 666 |
+
|
| 667 |
+
// CloseAllFiles closes all currently open files
|
| 668 |
+
func (c *Client) CloseAllFiles(ctx context.Context) {
|
| 669 |
+
cfg := config.Get()
|
| 670 |
+
c.openFilesMu.Lock()
|
| 671 |
+
filesToClose := make([]string, 0, len(c.openFiles))
|
| 672 |
+
|
| 673 |
+
// First collect all URIs that need to be closed
|
| 674 |
+
for uri := range c.openFiles {
|
| 675 |
+
// Convert URI back to file path using proper URI handling
|
| 676 |
+
filePath, err := protocol.DocumentURI(uri).Path()
|
| 677 |
+
if err != nil {
|
| 678 |
+
slog.Error("Failed to convert URI to path for file closing", "uri", uri, "error", err)
|
| 679 |
+
continue
|
| 680 |
+
}
|
| 681 |
+
filesToClose = append(filesToClose, filePath)
|
| 682 |
+
}
|
| 683 |
+
c.openFilesMu.Unlock()
|
| 684 |
+
|
| 685 |
+
// Then close them all
|
| 686 |
+
for _, filePath := range filesToClose {
|
| 687 |
+
err := c.CloseFile(ctx, filePath)
|
| 688 |
+
if err != nil && cfg.Options.DebugLSP {
|
| 689 |
+
slog.Warn("Error closing file", "file", filePath, "error", err)
|
| 690 |
+
}
|
| 691 |
+
}
|
| 692 |
+
|
| 693 |
+
if cfg.Options.DebugLSP {
|
| 694 |
+
slog.Debug("Closed all files", "files", filesToClose)
|
| 695 |
+
}
|
| 696 |
+
}
|
| 697 |
+
|
| 698 |
+
func (c *Client) GetFileDiagnostics(uri protocol.DocumentURI) []protocol.Diagnostic {
|
| 699 |
+
c.diagnosticsMu.RLock()
|
| 700 |
+
defer c.diagnosticsMu.RUnlock()
|
| 701 |
+
|
| 702 |
+
return c.diagnostics[uri]
|
| 703 |
+
}
|
| 704 |
+
|
| 705 |
+
// GetDiagnostics returns all diagnostics for all files
|
| 706 |
+
func (c *Client) GetDiagnostics() map[protocol.DocumentURI][]protocol.Diagnostic {
|
| 707 |
+
c.diagnosticsMu.RLock()
|
| 708 |
+
defer c.diagnosticsMu.RUnlock()
|
| 709 |
+
|
| 710 |
+
return maps.Clone(c.diagnostics)
|
| 711 |
+
}
|
| 712 |
+
|
| 713 |
+
// OpenFileOnDemand opens a file only if it's not already open
|
| 714 |
+
// This is used for lazy-loading files when they're actually needed
|
| 715 |
+
func (c *Client) OpenFileOnDemand(ctx context.Context, filepath string) error {
|
| 716 |
+
// Check if the file is already open
|
| 717 |
+
if c.IsFileOpen(filepath) {
|
| 718 |
+
return nil
|
| 719 |
+
}
|
| 720 |
+
|
| 721 |
+
// Open the file
|
| 722 |
+
return c.OpenFile(ctx, filepath)
|
| 723 |
+
}
|
| 724 |
+
|
| 725 |
+
// GetDiagnosticsForFile ensures a file is open and returns its diagnostics
|
| 726 |
+
// This is useful for on-demand diagnostics when using lazy loading
|
| 727 |
+
func (c *Client) GetDiagnosticsForFile(ctx context.Context, filepath string) ([]protocol.Diagnostic, error) {
|
| 728 |
+
documentURI := protocol.URIFromPath(filepath)
|
| 729 |
+
|
| 730 |
+
// Make sure the file is open
|
| 731 |
+
if !c.IsFileOpen(filepath) {
|
| 732 |
+
if err := c.OpenFile(ctx, filepath); err != nil {
|
| 733 |
+
return nil, fmt.Errorf("failed to open file for diagnostics: %w", err)
|
| 734 |
+
}
|
| 735 |
+
|
| 736 |
+
// Give the LSP server a moment to process the file
|
| 737 |
+
time.Sleep(100 * time.Millisecond)
|
| 738 |
+
}
|
| 739 |
+
|
| 740 |
+
// Get diagnostics
|
| 741 |
+
c.diagnosticsMu.RLock()
|
| 742 |
+
diagnostics := c.diagnostics[documentURI]
|
| 743 |
+
c.diagnosticsMu.RUnlock()
|
| 744 |
+
|
| 745 |
+
return diagnostics, nil
|
| 746 |
+
}
|
| 747 |
+
|
| 748 |
+
// ClearDiagnosticsForURI removes diagnostics for a specific URI from the cache
|
| 749 |
+
func (c *Client) ClearDiagnosticsForURI(uri protocol.DocumentURI) {
|
| 750 |
+
c.diagnosticsMu.Lock()
|
| 751 |
+
defer c.diagnosticsMu.Unlock()
|
| 752 |
+
delete(c.diagnostics, uri)
|
| 753 |
+
}
|
projects/ui/crush/internal/lsp/client_test.go
ADDED
|
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package lsp
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"testing"
|
| 5 |
+
|
| 6 |
+
"github.com/stretchr/testify/require"
|
| 7 |
+
)
|
| 8 |
+
|
| 9 |
+
func TestHandlesFile(t *testing.T) {
|
| 10 |
+
tests := []struct {
|
| 11 |
+
name string
|
| 12 |
+
fileTypes []string
|
| 13 |
+
filepath string
|
| 14 |
+
expected bool
|
| 15 |
+
}{
|
| 16 |
+
{
|
| 17 |
+
name: "no file types specified - handles all files",
|
| 18 |
+
fileTypes: nil,
|
| 19 |
+
filepath: "test.go",
|
| 20 |
+
expected: true,
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
name: "empty file types - handles all files",
|
| 24 |
+
fileTypes: []string{},
|
| 25 |
+
filepath: "test.go",
|
| 26 |
+
expected: true,
|
| 27 |
+
},
|
| 28 |
+
{
|
| 29 |
+
name: "matches .go extension",
|
| 30 |
+
fileTypes: []string{".go"},
|
| 31 |
+
filepath: "main.go",
|
| 32 |
+
expected: true,
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
name: "matches go extension without dot",
|
| 36 |
+
fileTypes: []string{"go"},
|
| 37 |
+
filepath: "main.go",
|
| 38 |
+
expected: true,
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
name: "matches one of multiple extensions",
|
| 42 |
+
fileTypes: []string{".js", ".ts", ".tsx"},
|
| 43 |
+
filepath: "component.tsx",
|
| 44 |
+
expected: true,
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
name: "does not match extension",
|
| 48 |
+
fileTypes: []string{".go", ".rs"},
|
| 49 |
+
filepath: "script.sh",
|
| 50 |
+
expected: false,
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
name: "matches with full path",
|
| 54 |
+
fileTypes: []string{".sh"},
|
| 55 |
+
filepath: "/usr/local/bin/script.sh",
|
| 56 |
+
expected: true,
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
name: "case insensitive matching",
|
| 60 |
+
fileTypes: []string{".GO"},
|
| 61 |
+
filepath: "main.go",
|
| 62 |
+
expected: true,
|
| 63 |
+
},
|
| 64 |
+
{
|
| 65 |
+
name: "bash file types",
|
| 66 |
+
fileTypes: []string{".sh", ".bash", ".zsh", ".ksh"},
|
| 67 |
+
filepath: "script.sh",
|
| 68 |
+
expected: true,
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
name: "bash should not handle go files",
|
| 72 |
+
fileTypes: []string{".sh", ".bash", ".zsh", ".ksh"},
|
| 73 |
+
filepath: "main.go",
|
| 74 |
+
expected: false,
|
| 75 |
+
},
|
| 76 |
+
{
|
| 77 |
+
name: "bash should not handle json files",
|
| 78 |
+
fileTypes: []string{".sh", ".bash", ".zsh", ".ksh"},
|
| 79 |
+
filepath: "config.json",
|
| 80 |
+
expected: false,
|
| 81 |
+
},
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
for _, tt := range tests {
|
| 85 |
+
t.Run(tt.name, func(t *testing.T) {
|
| 86 |
+
client := &Client{
|
| 87 |
+
fileTypes: tt.fileTypes,
|
| 88 |
+
}
|
| 89 |
+
result := client.HandlesFile(tt.filepath)
|
| 90 |
+
require.Equal(t, tt.expected, result)
|
| 91 |
+
})
|
| 92 |
+
}
|
| 93 |
+
}
|
projects/ui/crush/internal/lsp/handlers.go
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package lsp
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"encoding/json"
|
| 5 |
+
"log/slog"
|
| 6 |
+
|
| 7 |
+
"github.com/charmbracelet/crush/internal/config"
|
| 8 |
+
|
| 9 |
+
"github.com/charmbracelet/crush/internal/lsp/protocol"
|
| 10 |
+
"github.com/charmbracelet/crush/internal/lsp/util"
|
| 11 |
+
)
|
| 12 |
+
|
| 13 |
+
// Requests
|
| 14 |
+
|
| 15 |
+
func HandleWorkspaceConfiguration(params json.RawMessage) (any, error) {
|
| 16 |
+
return []map[string]any{{}}, nil
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
func HandleRegisterCapability(params json.RawMessage) (any, error) {
|
| 20 |
+
var registerParams protocol.RegistrationParams
|
| 21 |
+
if err := json.Unmarshal(params, ®isterParams); err != nil {
|
| 22 |
+
slog.Error("Error unmarshaling registration params", "error", err)
|
| 23 |
+
return nil, err
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
for _, reg := range registerParams.Registrations {
|
| 27 |
+
switch reg.Method {
|
| 28 |
+
case "workspace/didChangeWatchedFiles":
|
| 29 |
+
// Parse the registration options
|
| 30 |
+
optionsJSON, err := json.Marshal(reg.RegisterOptions)
|
| 31 |
+
if err != nil {
|
| 32 |
+
slog.Error("Error marshaling registration options", "error", err)
|
| 33 |
+
continue
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
var options protocol.DidChangeWatchedFilesRegistrationOptions
|
| 37 |
+
if err := json.Unmarshal(optionsJSON, &options); err != nil {
|
| 38 |
+
slog.Error("Error unmarshaling registration options", "error", err)
|
| 39 |
+
continue
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
// Store the file watchers registrations
|
| 43 |
+
notifyFileWatchRegistration(reg.ID, options.Watchers)
|
| 44 |
+
}
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
return nil, nil
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
func HandleApplyEdit(params json.RawMessage) (any, error) {
|
| 51 |
+
var edit protocol.ApplyWorkspaceEditParams
|
| 52 |
+
if err := json.Unmarshal(params, &edit); err != nil {
|
| 53 |
+
return nil, err
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
err := util.ApplyWorkspaceEdit(edit.Edit)
|
| 57 |
+
if err != nil {
|
| 58 |
+
slog.Error("Error applying workspace edit", "error", err)
|
| 59 |
+
return protocol.ApplyWorkspaceEditResult{Applied: false, FailureReason: err.Error()}, nil
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
return protocol.ApplyWorkspaceEditResult{Applied: true}, nil
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
// FileWatchRegistrationHandler is a function that will be called when file watch registrations are received
|
| 66 |
+
type FileWatchRegistrationHandler func(id string, watchers []protocol.FileSystemWatcher)
|
| 67 |
+
|
| 68 |
+
// fileWatchHandler holds the current handler for file watch registrations
|
| 69 |
+
var fileWatchHandler FileWatchRegistrationHandler
|
| 70 |
+
|
| 71 |
+
// RegisterFileWatchHandler sets the handler for file watch registrations
|
| 72 |
+
func RegisterFileWatchHandler(handler FileWatchRegistrationHandler) {
|
| 73 |
+
fileWatchHandler = handler
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
// notifyFileWatchRegistration notifies the handler about new file watch registrations
|
| 77 |
+
func notifyFileWatchRegistration(id string, watchers []protocol.FileSystemWatcher) {
|
| 78 |
+
if fileWatchHandler != nil {
|
| 79 |
+
fileWatchHandler(id, watchers)
|
| 80 |
+
}
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
// Notifications
|
| 84 |
+
|
| 85 |
+
func HandleServerMessage(params json.RawMessage) {
|
| 86 |
+
cfg := config.Get()
|
| 87 |
+
var msg struct {
|
| 88 |
+
Type int `json:"type"`
|
| 89 |
+
Message string `json:"message"`
|
| 90 |
+
}
|
| 91 |
+
if err := json.Unmarshal(params, &msg); err == nil {
|
| 92 |
+
if cfg.Options.DebugLSP {
|
| 93 |
+
slog.Debug("Server message", "type", msg.Type, "message", msg.Message)
|
| 94 |
+
}
|
| 95 |
+
}
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
func HandleDiagnostics(client *Client, params json.RawMessage) {
|
| 99 |
+
var diagParams protocol.PublishDiagnosticsParams
|
| 100 |
+
if err := json.Unmarshal(params, &diagParams); err != nil {
|
| 101 |
+
slog.Error("Error unmarshaling diagnostics params", "error", err)
|
| 102 |
+
return
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
client.diagnosticsMu.Lock()
|
| 106 |
+
client.diagnostics[diagParams.URI] = diagParams.Diagnostics
|
| 107 |
+
|
| 108 |
+
// Calculate total diagnostic count
|
| 109 |
+
totalCount := 0
|
| 110 |
+
for _, diagnostics := range client.diagnostics {
|
| 111 |
+
totalCount += len(diagnostics)
|
| 112 |
+
}
|
| 113 |
+
client.diagnosticsMu.Unlock()
|
| 114 |
+
|
| 115 |
+
// Trigger callback if set
|
| 116 |
+
if client.onDiagnosticsChanged != nil {
|
| 117 |
+
client.onDiagnosticsChanged(client.name, totalCount)
|
| 118 |
+
}
|
| 119 |
+
}
|
projects/ui/crush/internal/lsp/language.go
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package lsp
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"path/filepath"
|
| 5 |
+
"strings"
|
| 6 |
+
|
| 7 |
+
"github.com/charmbracelet/crush/internal/lsp/protocol"
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
func DetectLanguageID(uri string) protocol.LanguageKind {
|
| 11 |
+
ext := strings.ToLower(filepath.Ext(uri))
|
| 12 |
+
switch ext {
|
| 13 |
+
case ".abap":
|
| 14 |
+
return protocol.LangABAP
|
| 15 |
+
case ".bat":
|
| 16 |
+
return protocol.LangWindowsBat
|
| 17 |
+
case ".bib", ".bibtex":
|
| 18 |
+
return protocol.LangBibTeX
|
| 19 |
+
case ".clj":
|
| 20 |
+
return protocol.LangClojure
|
| 21 |
+
case ".coffee":
|
| 22 |
+
return protocol.LangCoffeescript
|
| 23 |
+
case ".c":
|
| 24 |
+
return protocol.LangC
|
| 25 |
+
case ".cpp", ".cxx", ".cc", ".c++":
|
| 26 |
+
return protocol.LangCPP
|
| 27 |
+
case ".cs":
|
| 28 |
+
return protocol.LangCSharp
|
| 29 |
+
case ".css":
|
| 30 |
+
return protocol.LangCSS
|
| 31 |
+
case ".d":
|
| 32 |
+
return protocol.LangD
|
| 33 |
+
case ".pas", ".pascal":
|
| 34 |
+
return protocol.LangDelphi
|
| 35 |
+
case ".diff", ".patch":
|
| 36 |
+
return protocol.LangDiff
|
| 37 |
+
case ".dart":
|
| 38 |
+
return protocol.LangDart
|
| 39 |
+
case ".dockerfile":
|
| 40 |
+
return protocol.LangDockerfile
|
| 41 |
+
case ".ex", ".exs":
|
| 42 |
+
return protocol.LangElixir
|
| 43 |
+
case ".erl", ".hrl":
|
| 44 |
+
return protocol.LangErlang
|
| 45 |
+
case ".fs", ".fsi", ".fsx", ".fsscript":
|
| 46 |
+
return protocol.LangFSharp
|
| 47 |
+
case ".gitcommit":
|
| 48 |
+
return protocol.LangGitCommit
|
| 49 |
+
case ".gitrebase":
|
| 50 |
+
return protocol.LangGitRebase
|
| 51 |
+
case ".go":
|
| 52 |
+
return protocol.LangGo
|
| 53 |
+
case ".groovy":
|
| 54 |
+
return protocol.LangGroovy
|
| 55 |
+
case ".hbs", ".handlebars":
|
| 56 |
+
return protocol.LangHandlebars
|
| 57 |
+
case ".hs":
|
| 58 |
+
return protocol.LangHaskell
|
| 59 |
+
case ".html", ".htm":
|
| 60 |
+
return protocol.LangHTML
|
| 61 |
+
case ".ini":
|
| 62 |
+
return protocol.LangIni
|
| 63 |
+
case ".java":
|
| 64 |
+
return protocol.LangJava
|
| 65 |
+
case ".js":
|
| 66 |
+
return protocol.LangJavaScript
|
| 67 |
+
case ".jsx":
|
| 68 |
+
return protocol.LangJavaScriptReact
|
| 69 |
+
case ".json":
|
| 70 |
+
return protocol.LangJSON
|
| 71 |
+
case ".tex", ".latex":
|
| 72 |
+
return protocol.LangLaTeX
|
| 73 |
+
case ".less":
|
| 74 |
+
return protocol.LangLess
|
| 75 |
+
case ".lua":
|
| 76 |
+
return protocol.LangLua
|
| 77 |
+
case ".makefile", "makefile":
|
| 78 |
+
return protocol.LangMakefile
|
| 79 |
+
case ".md", ".markdown":
|
| 80 |
+
return protocol.LangMarkdown
|
| 81 |
+
case ".m":
|
| 82 |
+
return protocol.LangObjectiveC
|
| 83 |
+
case ".mm":
|
| 84 |
+
return protocol.LangObjectiveCPP
|
| 85 |
+
case ".pl":
|
| 86 |
+
return protocol.LangPerl
|
| 87 |
+
case ".pm":
|
| 88 |
+
return protocol.LangPerl6
|
| 89 |
+
case ".php":
|
| 90 |
+
return protocol.LangPHP
|
| 91 |
+
case ".ps1", ".psm1":
|
| 92 |
+
return protocol.LangPowershell
|
| 93 |
+
case ".pug", ".jade":
|
| 94 |
+
return protocol.LangPug
|
| 95 |
+
case ".py":
|
| 96 |
+
return protocol.LangPython
|
| 97 |
+
case ".r":
|
| 98 |
+
return protocol.LangR
|
| 99 |
+
case ".cshtml", ".razor":
|
| 100 |
+
return protocol.LangRazor
|
| 101 |
+
case ".rb":
|
| 102 |
+
return protocol.LangRuby
|
| 103 |
+
case ".rs":
|
| 104 |
+
return protocol.LangRust
|
| 105 |
+
case ".scss":
|
| 106 |
+
return protocol.LangSCSS
|
| 107 |
+
case ".sass":
|
| 108 |
+
return protocol.LangSASS
|
| 109 |
+
case ".scala":
|
| 110 |
+
return protocol.LangScala
|
| 111 |
+
case ".shader":
|
| 112 |
+
return protocol.LangShaderLab
|
| 113 |
+
case ".sh", ".bash", ".zsh", ".ksh":
|
| 114 |
+
return protocol.LangShellScript
|
| 115 |
+
case ".sql":
|
| 116 |
+
return protocol.LangSQL
|
| 117 |
+
case ".swift":
|
| 118 |
+
return protocol.LangSwift
|
| 119 |
+
case ".ts":
|
| 120 |
+
return protocol.LangTypeScript
|
| 121 |
+
case ".tsx":
|
| 122 |
+
return protocol.LangTypeScriptReact
|
| 123 |
+
case ".xml":
|
| 124 |
+
return protocol.LangXML
|
| 125 |
+
case ".xsl":
|
| 126 |
+
return protocol.LangXSL
|
| 127 |
+
case ".yaml", ".yml":
|
| 128 |
+
return protocol.LangYAML
|
| 129 |
+
default:
|
| 130 |
+
return protocol.LanguageKind("") // Unknown language
|
| 131 |
+
}
|
| 132 |
+
}
|
projects/ui/crush/internal/lsp/methods.go
ADDED
|
@@ -0,0 +1,554 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// Generated code. Do not edit
|
| 2 |
+
package lsp
|
| 3 |
+
|
| 4 |
+
import (
|
| 5 |
+
"context"
|
| 6 |
+
|
| 7 |
+
"github.com/charmbracelet/crush/internal/lsp/protocol"
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
// Implementation sends a textDocument/implementation request to the LSP server.
|
| 11 |
+
// A request to resolve the implementation locations of a symbol at a given text document position. The request's parameter is of type TextDocumentPositionParams the response is of type Definition or a Thenable that resolves to such.
|
| 12 |
+
func (c *Client) Implementation(ctx context.Context, params protocol.ImplementationParams) (protocol.Or_Result_textDocument_implementation, error) {
|
| 13 |
+
var result protocol.Or_Result_textDocument_implementation
|
| 14 |
+
err := c.Call(ctx, "textDocument/implementation", params, &result)
|
| 15 |
+
return result, err
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
// TypeDefinition sends a textDocument/typeDefinition request to the LSP server.
|
| 19 |
+
// A request to resolve the type definition locations of a symbol at a given text document position. The request's parameter is of type TextDocumentPositionParams the response is of type Definition or a Thenable that resolves to such.
|
| 20 |
+
func (c *Client) TypeDefinition(ctx context.Context, params protocol.TypeDefinitionParams) (protocol.Or_Result_textDocument_typeDefinition, error) {
|
| 21 |
+
var result protocol.Or_Result_textDocument_typeDefinition
|
| 22 |
+
err := c.Call(ctx, "textDocument/typeDefinition", params, &result)
|
| 23 |
+
return result, err
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
// DocumentColor sends a textDocument/documentColor request to the LSP server.
|
| 27 |
+
// A request to list all color symbols found in a given text document. The request's parameter is of type DocumentColorParams the response is of type ColorInformation ColorInformation[] or a Thenable that resolves to such.
|
| 28 |
+
func (c *Client) DocumentColor(ctx context.Context, params protocol.DocumentColorParams) ([]protocol.ColorInformation, error) {
|
| 29 |
+
var result []protocol.ColorInformation
|
| 30 |
+
err := c.Call(ctx, "textDocument/documentColor", params, &result)
|
| 31 |
+
return result, err
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
// ColorPresentation sends a textDocument/colorPresentation request to the LSP server.
|
| 35 |
+
// A request to list all presentation for a color. The request's parameter is of type ColorPresentationParams the response is of type ColorInformation ColorInformation[] or a Thenable that resolves to such.
|
| 36 |
+
func (c *Client) ColorPresentation(ctx context.Context, params protocol.ColorPresentationParams) ([]protocol.ColorPresentation, error) {
|
| 37 |
+
var result []protocol.ColorPresentation
|
| 38 |
+
err := c.Call(ctx, "textDocument/colorPresentation", params, &result)
|
| 39 |
+
return result, err
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
// FoldingRange sends a textDocument/foldingRange request to the LSP server.
|
| 43 |
+
// A request to provide folding ranges in a document. The request's parameter is of type FoldingRangeParams, the response is of type FoldingRangeList or a Thenable that resolves to such.
|
| 44 |
+
func (c *Client) FoldingRange(ctx context.Context, params protocol.FoldingRangeParams) ([]protocol.FoldingRange, error) {
|
| 45 |
+
var result []protocol.FoldingRange
|
| 46 |
+
err := c.Call(ctx, "textDocument/foldingRange", params, &result)
|
| 47 |
+
return result, err
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
// Declaration sends a textDocument/declaration request to the LSP server.
|
| 51 |
+
// A request to resolve the type definition locations of a symbol at a given text document position. The request's parameter is of type TextDocumentPositionParams the response is of type Declaration or a typed array of DeclarationLink or a Thenable that resolves to such.
|
| 52 |
+
func (c *Client) Declaration(ctx context.Context, params protocol.DeclarationParams) (protocol.Or_Result_textDocument_declaration, error) {
|
| 53 |
+
var result protocol.Or_Result_textDocument_declaration
|
| 54 |
+
err := c.Call(ctx, "textDocument/declaration", params, &result)
|
| 55 |
+
return result, err
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
// SelectionRange sends a textDocument/selectionRange request to the LSP server.
|
| 59 |
+
// A request to provide selection ranges in a document. The request's parameter is of type SelectionRangeParams, the response is of type SelectionRange SelectionRange[] or a Thenable that resolves to such.
|
| 60 |
+
func (c *Client) SelectionRange(ctx context.Context, params protocol.SelectionRangeParams) ([]protocol.SelectionRange, error) {
|
| 61 |
+
var result []protocol.SelectionRange
|
| 62 |
+
err := c.Call(ctx, "textDocument/selectionRange", params, &result)
|
| 63 |
+
return result, err
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
// PrepareCallHierarchy sends a textDocument/prepareCallHierarchy request to the LSP server.
|
| 67 |
+
// A request to result a CallHierarchyItem in a document at a given position. Can be used as an input to an incoming or outgoing call hierarchy. Since 3.16.0
|
| 68 |
+
func (c *Client) PrepareCallHierarchy(ctx context.Context, params protocol.CallHierarchyPrepareParams) ([]protocol.CallHierarchyItem, error) {
|
| 69 |
+
var result []protocol.CallHierarchyItem
|
| 70 |
+
err := c.Call(ctx, "textDocument/prepareCallHierarchy", params, &result)
|
| 71 |
+
return result, err
|
| 72 |
+
}
|
| 73 |
+
|
| 74 |
+
// IncomingCalls sends a callHierarchy/incomingCalls request to the LSP server.
|
| 75 |
+
// A request to resolve the incoming calls for a given CallHierarchyItem. Since 3.16.0
|
| 76 |
+
func (c *Client) IncomingCalls(ctx context.Context, params protocol.CallHierarchyIncomingCallsParams) ([]protocol.CallHierarchyIncomingCall, error) {
|
| 77 |
+
var result []protocol.CallHierarchyIncomingCall
|
| 78 |
+
err := c.Call(ctx, "callHierarchy/incomingCalls", params, &result)
|
| 79 |
+
return result, err
|
| 80 |
+
}
|
| 81 |
+
|
| 82 |
+
// OutgoingCalls sends a callHierarchy/outgoingCalls request to the LSP server.
|
| 83 |
+
// A request to resolve the outgoing calls for a given CallHierarchyItem. Since 3.16.0
|
| 84 |
+
func (c *Client) OutgoingCalls(ctx context.Context, params protocol.CallHierarchyOutgoingCallsParams) ([]protocol.CallHierarchyOutgoingCall, error) {
|
| 85 |
+
var result []protocol.CallHierarchyOutgoingCall
|
| 86 |
+
err := c.Call(ctx, "callHierarchy/outgoingCalls", params, &result)
|
| 87 |
+
return result, err
|
| 88 |
+
}
|
| 89 |
+
|
| 90 |
+
// SemanticTokensFull sends a textDocument/semanticTokens/full request to the LSP server.
|
| 91 |
+
// Since 3.16.0
|
| 92 |
+
func (c *Client) SemanticTokensFull(ctx context.Context, params protocol.SemanticTokensParams) (protocol.SemanticTokens, error) {
|
| 93 |
+
var result protocol.SemanticTokens
|
| 94 |
+
err := c.Call(ctx, "textDocument/semanticTokens/full", params, &result)
|
| 95 |
+
return result, err
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
// SemanticTokensFullDelta sends a textDocument/semanticTokens/full/delta request to the LSP server.
|
| 99 |
+
// Since 3.16.0
|
| 100 |
+
func (c *Client) SemanticTokensFullDelta(ctx context.Context, params protocol.SemanticTokensDeltaParams) (protocol.Or_Result_textDocument_semanticTokens_full_delta, error) {
|
| 101 |
+
var result protocol.Or_Result_textDocument_semanticTokens_full_delta
|
| 102 |
+
err := c.Call(ctx, "textDocument/semanticTokens/full/delta", params, &result)
|
| 103 |
+
return result, err
|
| 104 |
+
}
|
| 105 |
+
|
| 106 |
+
// SemanticTokensRange sends a textDocument/semanticTokens/range request to the LSP server.
|
| 107 |
+
// Since 3.16.0
|
| 108 |
+
func (c *Client) SemanticTokensRange(ctx context.Context, params protocol.SemanticTokensRangeParams) (protocol.SemanticTokens, error) {
|
| 109 |
+
var result protocol.SemanticTokens
|
| 110 |
+
err := c.Call(ctx, "textDocument/semanticTokens/range", params, &result)
|
| 111 |
+
return result, err
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
// LinkedEditingRange sends a textDocument/linkedEditingRange request to the LSP server.
|
| 115 |
+
// A request to provide ranges that can be edited together. Since 3.16.0
|
| 116 |
+
func (c *Client) LinkedEditingRange(ctx context.Context, params protocol.LinkedEditingRangeParams) (protocol.LinkedEditingRanges, error) {
|
| 117 |
+
var result protocol.LinkedEditingRanges
|
| 118 |
+
err := c.Call(ctx, "textDocument/linkedEditingRange", params, &result)
|
| 119 |
+
return result, err
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
// WillCreateFiles sends a workspace/willCreateFiles request to the LSP server.
|
| 123 |
+
// The will create files request is sent from the client to the server before files are actually created as long as the creation is triggered from within the client. The request can return a WorkspaceEdit which will be applied to workspace before the files are created. Hence the WorkspaceEdit can not manipulate the content of the file to be created. Since 3.16.0
|
| 124 |
+
func (c *Client) WillCreateFiles(ctx context.Context, params protocol.CreateFilesParams) (protocol.WorkspaceEdit, error) {
|
| 125 |
+
var result protocol.WorkspaceEdit
|
| 126 |
+
err := c.Call(ctx, "workspace/willCreateFiles", params, &result)
|
| 127 |
+
return result, err
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
// WillRenameFiles sends a workspace/willRenameFiles request to the LSP server.
|
| 131 |
+
// The will rename files request is sent from the client to the server before files are actually renamed as long as the rename is triggered from within the client. Since 3.16.0
|
| 132 |
+
func (c *Client) WillRenameFiles(ctx context.Context, params protocol.RenameFilesParams) (protocol.WorkspaceEdit, error) {
|
| 133 |
+
var result protocol.WorkspaceEdit
|
| 134 |
+
err := c.Call(ctx, "workspace/willRenameFiles", params, &result)
|
| 135 |
+
return result, err
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
// WillDeleteFiles sends a workspace/willDeleteFiles request to the LSP server.
|
| 139 |
+
// The did delete files notification is sent from the client to the server when files were deleted from within the client. Since 3.16.0
|
| 140 |
+
func (c *Client) WillDeleteFiles(ctx context.Context, params protocol.DeleteFilesParams) (protocol.WorkspaceEdit, error) {
|
| 141 |
+
var result protocol.WorkspaceEdit
|
| 142 |
+
err := c.Call(ctx, "workspace/willDeleteFiles", params, &result)
|
| 143 |
+
return result, err
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
// Moniker sends a textDocument/moniker request to the LSP server.
|
| 147 |
+
// A request to get the moniker of a symbol at a given text document position. The request parameter is of type TextDocumentPositionParams. The response is of type Moniker Moniker[] or null.
|
| 148 |
+
func (c *Client) Moniker(ctx context.Context, params protocol.MonikerParams) ([]protocol.Moniker, error) {
|
| 149 |
+
var result []protocol.Moniker
|
| 150 |
+
err := c.Call(ctx, "textDocument/moniker", params, &result)
|
| 151 |
+
return result, err
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
// PrepareTypeHierarchy sends a textDocument/prepareTypeHierarchy request to the LSP server.
|
| 155 |
+
// A request to result a TypeHierarchyItem in a document at a given position. Can be used as an input to a subtypes or supertypes type hierarchy. Since 3.17.0
|
| 156 |
+
func (c *Client) PrepareTypeHierarchy(ctx context.Context, params protocol.TypeHierarchyPrepareParams) ([]protocol.TypeHierarchyItem, error) {
|
| 157 |
+
var result []protocol.TypeHierarchyItem
|
| 158 |
+
err := c.Call(ctx, "textDocument/prepareTypeHierarchy", params, &result)
|
| 159 |
+
return result, err
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
// Supertypes sends a typeHierarchy/supertypes request to the LSP server.
|
| 163 |
+
// A request to resolve the supertypes for a given TypeHierarchyItem. Since 3.17.0
|
| 164 |
+
func (c *Client) Supertypes(ctx context.Context, params protocol.TypeHierarchySupertypesParams) ([]protocol.TypeHierarchyItem, error) {
|
| 165 |
+
var result []protocol.TypeHierarchyItem
|
| 166 |
+
err := c.Call(ctx, "typeHierarchy/supertypes", params, &result)
|
| 167 |
+
return result, err
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
// Subtypes sends a typeHierarchy/subtypes request to the LSP server.
|
| 171 |
+
// A request to resolve the subtypes for a given TypeHierarchyItem. Since 3.17.0
|
| 172 |
+
func (c *Client) Subtypes(ctx context.Context, params protocol.TypeHierarchySubtypesParams) ([]protocol.TypeHierarchyItem, error) {
|
| 173 |
+
var result []protocol.TypeHierarchyItem
|
| 174 |
+
err := c.Call(ctx, "typeHierarchy/subtypes", params, &result)
|
| 175 |
+
return result, err
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
// InlineValue sends a textDocument/inlineValue request to the LSP server.
|
| 179 |
+
// A request to provide inline values in a document. The request's parameter is of type InlineValueParams, the response is of type InlineValue InlineValue[] or a Thenable that resolves to such. Since 3.17.0
|
| 180 |
+
func (c *Client) InlineValue(ctx context.Context, params protocol.InlineValueParams) ([]protocol.InlineValue, error) {
|
| 181 |
+
var result []protocol.InlineValue
|
| 182 |
+
err := c.Call(ctx, "textDocument/inlineValue", params, &result)
|
| 183 |
+
return result, err
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
// InlayHint sends a textDocument/inlayHint request to the LSP server.
|
| 187 |
+
// A request to provide inlay hints in a document. The request's parameter is of type InlayHintsParams, the response is of type InlayHint InlayHint[] or a Thenable that resolves to such. Since 3.17.0
|
| 188 |
+
func (c *Client) InlayHint(ctx context.Context, params protocol.InlayHintParams) ([]protocol.InlayHint, error) {
|
| 189 |
+
var result []protocol.InlayHint
|
| 190 |
+
err := c.Call(ctx, "textDocument/inlayHint", params, &result)
|
| 191 |
+
return result, err
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
// Resolve sends a inlayHint/resolve request to the LSP server.
|
| 195 |
+
// A request to resolve additional properties for an inlay hint. The request's parameter is of type InlayHint, the response is of type InlayHint or a Thenable that resolves to such. Since 3.17.0
|
| 196 |
+
func (c *Client) Resolve(ctx context.Context, params protocol.InlayHint) (protocol.InlayHint, error) {
|
| 197 |
+
var result protocol.InlayHint
|
| 198 |
+
err := c.Call(ctx, "inlayHint/resolve", params, &result)
|
| 199 |
+
return result, err
|
| 200 |
+
}
|
| 201 |
+
|
| 202 |
+
// Diagnostic sends a textDocument/diagnostic request to the LSP server.
|
| 203 |
+
// The document diagnostic request definition. Since 3.17.0
|
| 204 |
+
func (c *Client) Diagnostic(ctx context.Context, params protocol.DocumentDiagnosticParams) (protocol.DocumentDiagnosticReport, error) {
|
| 205 |
+
var result protocol.DocumentDiagnosticReport
|
| 206 |
+
err := c.Call(ctx, "textDocument/diagnostic", params, &result)
|
| 207 |
+
return result, err
|
| 208 |
+
}
|
| 209 |
+
|
| 210 |
+
// DiagnosticWorkspace sends a workspace/diagnostic request to the LSP server.
|
| 211 |
+
// The workspace diagnostic request definition. Since 3.17.0
|
| 212 |
+
func (c *Client) DiagnosticWorkspace(ctx context.Context, params protocol.WorkspaceDiagnosticParams) (protocol.WorkspaceDiagnosticReport, error) {
|
| 213 |
+
var result protocol.WorkspaceDiagnosticReport
|
| 214 |
+
err := c.Call(ctx, "workspace/diagnostic", params, &result)
|
| 215 |
+
return result, err
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
// InlineCompletion sends a textDocument/inlineCompletion request to the LSP server.
|
| 219 |
+
// A request to provide inline completions in a document. The request's parameter is of type InlineCompletionParams, the response is of type InlineCompletion InlineCompletion[] or a Thenable that resolves to such. Since 3.18.0 PROPOSED
|
| 220 |
+
func (c *Client) InlineCompletion(ctx context.Context, params protocol.InlineCompletionParams) (protocol.Or_Result_textDocument_inlineCompletion, error) {
|
| 221 |
+
var result protocol.Or_Result_textDocument_inlineCompletion
|
| 222 |
+
err := c.Call(ctx, "textDocument/inlineCompletion", params, &result)
|
| 223 |
+
return result, err
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
// TextDocumentContent sends a workspace/textDocumentContent request to the LSP server.
|
| 227 |
+
// The workspace/textDocumentContent request is sent from the client to the server to request the content of a text document. Since 3.18.0 PROPOSED
|
| 228 |
+
func (c *Client) TextDocumentContent(ctx context.Context, params protocol.TextDocumentContentParams) (string, error) {
|
| 229 |
+
var result string
|
| 230 |
+
err := c.Call(ctx, "workspace/textDocumentContent", params, &result)
|
| 231 |
+
return result, err
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
// Initialize sends a initialize request to the LSP server.
|
| 235 |
+
// The initialize request is sent from the client to the server. It is sent once as the request after starting up the server. The requests parameter is of type InitializeParams the response if of type InitializeResult of a Thenable that resolves to such.
|
| 236 |
+
func (c *Client) Initialize(ctx context.Context, params protocol.ParamInitialize) (protocol.InitializeResult, error) {
|
| 237 |
+
var result protocol.InitializeResult
|
| 238 |
+
err := c.Call(ctx, "initialize", params, &result)
|
| 239 |
+
return result, err
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
// Shutdown sends a shutdown request to the LSP server.
|
| 243 |
+
// A shutdown request is sent from the client to the server. It is sent once when the client decides to shutdown the server. The only notification that is sent after a shutdown request is the exit event.
|
| 244 |
+
func (c *Client) Shutdown(ctx context.Context) error {
|
| 245 |
+
return c.Call(ctx, "shutdown", nil, nil)
|
| 246 |
+
}
|
| 247 |
+
|
| 248 |
+
// WillSaveWaitUntil sends a textDocument/willSaveWaitUntil request to the LSP server.
|
| 249 |
+
// A document will save request is sent from the client to the server before the document is actually saved. The request can return an array of TextEdits which will be applied to the text document before it is saved. Please note that clients might drop results if computing the text edits took too long or if a server constantly fails on this request. This is done to keep the save fast and reliable.
|
| 250 |
+
func (c *Client) WillSaveWaitUntil(ctx context.Context, params protocol.WillSaveTextDocumentParams) ([]protocol.TextEdit, error) {
|
| 251 |
+
var result []protocol.TextEdit
|
| 252 |
+
err := c.Call(ctx, "textDocument/willSaveWaitUntil", params, &result)
|
| 253 |
+
return result, err
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
// Completion sends a textDocument/completion request to the LSP server.
|
| 257 |
+
// Request to request completion at a given text document position. The request's parameter is of type TextDocumentPosition the response is of type CompletionItem CompletionItem[] or CompletionList or a Thenable that resolves to such. The request can delay the computation of the CompletionItem.detail detail and CompletionItem.documentation documentation properties to the completionItem/resolve request. However, properties that are needed for the initial sorting and filtering, like sortText, filterText, insertText, and textEdit, must not be changed during resolve.
|
| 258 |
+
func (c *Client) Completion(ctx context.Context, params protocol.CompletionParams) (protocol.Or_Result_textDocument_completion, error) {
|
| 259 |
+
var result protocol.Or_Result_textDocument_completion
|
| 260 |
+
err := c.Call(ctx, "textDocument/completion", params, &result)
|
| 261 |
+
return result, err
|
| 262 |
+
}
|
| 263 |
+
|
| 264 |
+
// ResolveCompletionItem sends a completionItem/resolve request to the LSP server.
|
| 265 |
+
// Request to resolve additional information for a given completion item.The request's parameter is of type CompletionItem the response is of type CompletionItem or a Thenable that resolves to such.
|
| 266 |
+
func (c *Client) ResolveCompletionItem(ctx context.Context, params protocol.CompletionItem) (protocol.CompletionItem, error) {
|
| 267 |
+
var result protocol.CompletionItem
|
| 268 |
+
err := c.Call(ctx, "completionItem/resolve", params, &result)
|
| 269 |
+
return result, err
|
| 270 |
+
}
|
| 271 |
+
|
| 272 |
+
// Hover sends a textDocument/hover request to the LSP server.
|
| 273 |
+
// Request to request hover information at a given text document position. The request's parameter is of type TextDocumentPosition the response is of type Hover or a Thenable that resolves to such.
|
| 274 |
+
func (c *Client) Hover(ctx context.Context, params protocol.HoverParams) (protocol.Hover, error) {
|
| 275 |
+
var result protocol.Hover
|
| 276 |
+
err := c.Call(ctx, "textDocument/hover", params, &result)
|
| 277 |
+
return result, err
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
// SignatureHelp sends a textDocument/signatureHelp request to the LSP server.
|
| 281 |
+
func (c *Client) SignatureHelp(ctx context.Context, params protocol.SignatureHelpParams) (protocol.SignatureHelp, error) {
|
| 282 |
+
var result protocol.SignatureHelp
|
| 283 |
+
err := c.Call(ctx, "textDocument/signatureHelp", params, &result)
|
| 284 |
+
return result, err
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
// Definition sends a textDocument/definition request to the LSP server.
|
| 288 |
+
// A request to resolve the definition location of a symbol at a given text document position. The request's parameter is of type TextDocumentPosition the response is of either type Definition or a typed array of DefinitionLink or a Thenable that resolves to such.
|
| 289 |
+
func (c *Client) Definition(ctx context.Context, params protocol.DefinitionParams) (protocol.Or_Result_textDocument_definition, error) {
|
| 290 |
+
var result protocol.Or_Result_textDocument_definition
|
| 291 |
+
err := c.Call(ctx, "textDocument/definition", params, &result)
|
| 292 |
+
return result, err
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
// References sends a textDocument/references request to the LSP server.
|
| 296 |
+
// A request to resolve project-wide references for the symbol denoted by the given text document position. The request's parameter is of type ReferenceParams the response is of type Location Location[] or a Thenable that resolves to such.
|
| 297 |
+
func (c *Client) References(ctx context.Context, params protocol.ReferenceParams) ([]protocol.Location, error) {
|
| 298 |
+
var result []protocol.Location
|
| 299 |
+
err := c.Call(ctx, "textDocument/references", params, &result)
|
| 300 |
+
return result, err
|
| 301 |
+
}
|
| 302 |
+
|
| 303 |
+
// DocumentHighlight sends a textDocument/documentHighlight request to the LSP server.
|
| 304 |
+
// Request to resolve a DocumentHighlight for a given text document position. The request's parameter is of type TextDocumentPosition the request response is an array of type DocumentHighlight or a Thenable that resolves to such.
|
| 305 |
+
func (c *Client) DocumentHighlight(ctx context.Context, params protocol.DocumentHighlightParams) ([]protocol.DocumentHighlight, error) {
|
| 306 |
+
var result []protocol.DocumentHighlight
|
| 307 |
+
err := c.Call(ctx, "textDocument/documentHighlight", params, &result)
|
| 308 |
+
return result, err
|
| 309 |
+
}
|
| 310 |
+
|
| 311 |
+
// DocumentSymbol sends a textDocument/documentSymbol request to the LSP server.
|
| 312 |
+
// A request to list all symbols found in a given text document. The request's parameter is of type TextDocumentIdentifier the response is of type SymbolInformation SymbolInformation[] or a Thenable that resolves to such.
|
| 313 |
+
func (c *Client) DocumentSymbol(ctx context.Context, params protocol.DocumentSymbolParams) (protocol.Or_Result_textDocument_documentSymbol, error) {
|
| 314 |
+
var result protocol.Or_Result_textDocument_documentSymbol
|
| 315 |
+
err := c.Call(ctx, "textDocument/documentSymbol", params, &result)
|
| 316 |
+
return result, err
|
| 317 |
+
}
|
| 318 |
+
|
| 319 |
+
// CodeAction sends a textDocument/codeAction request to the LSP server.
|
| 320 |
+
// A request to provide commands for the given text document and range.
|
| 321 |
+
func (c *Client) CodeAction(ctx context.Context, params protocol.CodeActionParams) ([]protocol.Or_Result_textDocument_codeAction_Item0_Elem, error) {
|
| 322 |
+
var result []protocol.Or_Result_textDocument_codeAction_Item0_Elem
|
| 323 |
+
err := c.Call(ctx, "textDocument/codeAction", params, &result)
|
| 324 |
+
return result, err
|
| 325 |
+
}
|
| 326 |
+
|
| 327 |
+
// ResolveCodeAction sends a codeAction/resolve request to the LSP server.
|
| 328 |
+
// Request to resolve additional information for a given code action.The request's parameter is of type CodeAction the response is of type CodeAction or a Thenable that resolves to such.
|
| 329 |
+
func (c *Client) ResolveCodeAction(ctx context.Context, params protocol.CodeAction) (protocol.CodeAction, error) {
|
| 330 |
+
var result protocol.CodeAction
|
| 331 |
+
err := c.Call(ctx, "codeAction/resolve", params, &result)
|
| 332 |
+
return result, err
|
| 333 |
+
}
|
| 334 |
+
|
| 335 |
+
// Symbol sends a workspace/symbol request to the LSP server.
|
| 336 |
+
// A request to list project-wide symbols matching the query string given by the WorkspaceSymbolParams. The response is of type SymbolInformation SymbolInformation[] or a Thenable that resolves to such. Since 3.17.0 - support for WorkspaceSymbol in the returned data. Clients need to advertise support for WorkspaceSymbols via the client capability workspace.symbol.resolveSupport.
|
| 337 |
+
func (c *Client) Symbol(ctx context.Context, params protocol.WorkspaceSymbolParams) (protocol.Or_Result_workspace_symbol, error) {
|
| 338 |
+
var result protocol.Or_Result_workspace_symbol
|
| 339 |
+
err := c.Call(ctx, "workspace/symbol", params, &result)
|
| 340 |
+
return result, err
|
| 341 |
+
}
|
| 342 |
+
|
| 343 |
+
// ResolveWorkspaceSymbol sends a workspaceSymbol/resolve request to the LSP server.
|
| 344 |
+
// A request to resolve the range inside the workspace symbol's location. Since 3.17.0
|
| 345 |
+
func (c *Client) ResolveWorkspaceSymbol(ctx context.Context, params protocol.WorkspaceSymbol) (protocol.WorkspaceSymbol, error) {
|
| 346 |
+
var result protocol.WorkspaceSymbol
|
| 347 |
+
err := c.Call(ctx, "workspaceSymbol/resolve", params, &result)
|
| 348 |
+
return result, err
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
// CodeLens sends a textDocument/codeLens request to the LSP server.
|
| 352 |
+
// A request to provide code lens for the given text document.
|
| 353 |
+
func (c *Client) CodeLens(ctx context.Context, params protocol.CodeLensParams) ([]protocol.CodeLens, error) {
|
| 354 |
+
var result []protocol.CodeLens
|
| 355 |
+
err := c.Call(ctx, "textDocument/codeLens", params, &result)
|
| 356 |
+
return result, err
|
| 357 |
+
}
|
| 358 |
+
|
| 359 |
+
// ResolveCodeLens sends a codeLens/resolve request to the LSP server.
|
| 360 |
+
// A request to resolve a command for a given code lens.
|
| 361 |
+
func (c *Client) ResolveCodeLens(ctx context.Context, params protocol.CodeLens) (protocol.CodeLens, error) {
|
| 362 |
+
var result protocol.CodeLens
|
| 363 |
+
err := c.Call(ctx, "codeLens/resolve", params, &result)
|
| 364 |
+
return result, err
|
| 365 |
+
}
|
| 366 |
+
|
| 367 |
+
// DocumentLink sends a textDocument/documentLink request to the LSP server.
|
| 368 |
+
// A request to provide document links
|
| 369 |
+
func (c *Client) DocumentLink(ctx context.Context, params protocol.DocumentLinkParams) ([]protocol.DocumentLink, error) {
|
| 370 |
+
var result []protocol.DocumentLink
|
| 371 |
+
err := c.Call(ctx, "textDocument/documentLink", params, &result)
|
| 372 |
+
return result, err
|
| 373 |
+
}
|
| 374 |
+
|
| 375 |
+
// ResolveDocumentLink sends a documentLink/resolve request to the LSP server.
|
| 376 |
+
// Request to resolve additional information for a given document link. The request's parameter is of type DocumentLink the response is of type DocumentLink or a Thenable that resolves to such.
|
| 377 |
+
func (c *Client) ResolveDocumentLink(ctx context.Context, params protocol.DocumentLink) (protocol.DocumentLink, error) {
|
| 378 |
+
var result protocol.DocumentLink
|
| 379 |
+
err := c.Call(ctx, "documentLink/resolve", params, &result)
|
| 380 |
+
return result, err
|
| 381 |
+
}
|
| 382 |
+
|
| 383 |
+
// Formatting sends a textDocument/formatting request to the LSP server.
|
| 384 |
+
// A request to format a whole document.
|
| 385 |
+
func (c *Client) Formatting(ctx context.Context, params protocol.DocumentFormattingParams) ([]protocol.TextEdit, error) {
|
| 386 |
+
var result []protocol.TextEdit
|
| 387 |
+
err := c.Call(ctx, "textDocument/formatting", params, &result)
|
| 388 |
+
return result, err
|
| 389 |
+
}
|
| 390 |
+
|
| 391 |
+
// RangeFormatting sends a textDocument/rangeFormatting request to the LSP server.
|
| 392 |
+
// A request to format a range in a document.
|
| 393 |
+
func (c *Client) RangeFormatting(ctx context.Context, params protocol.DocumentRangeFormattingParams) ([]protocol.TextEdit, error) {
|
| 394 |
+
var result []protocol.TextEdit
|
| 395 |
+
err := c.Call(ctx, "textDocument/rangeFormatting", params, &result)
|
| 396 |
+
return result, err
|
| 397 |
+
}
|
| 398 |
+
|
| 399 |
+
// RangesFormatting sends a textDocument/rangesFormatting request to the LSP server.
|
| 400 |
+
// A request to format ranges in a document. Since 3.18.0 PROPOSED
|
| 401 |
+
func (c *Client) RangesFormatting(ctx context.Context, params protocol.DocumentRangesFormattingParams) ([]protocol.TextEdit, error) {
|
| 402 |
+
var result []protocol.TextEdit
|
| 403 |
+
err := c.Call(ctx, "textDocument/rangesFormatting", params, &result)
|
| 404 |
+
return result, err
|
| 405 |
+
}
|
| 406 |
+
|
| 407 |
+
// OnTypeFormatting sends a textDocument/onTypeFormatting request to the LSP server.
|
| 408 |
+
// A request to format a document on type.
|
| 409 |
+
func (c *Client) OnTypeFormatting(ctx context.Context, params protocol.DocumentOnTypeFormattingParams) ([]protocol.TextEdit, error) {
|
| 410 |
+
var result []protocol.TextEdit
|
| 411 |
+
err := c.Call(ctx, "textDocument/onTypeFormatting", params, &result)
|
| 412 |
+
return result, err
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
// Rename sends a textDocument/rename request to the LSP server.
|
| 416 |
+
// A request to rename a symbol.
|
| 417 |
+
func (c *Client) Rename(ctx context.Context, params protocol.RenameParams) (protocol.WorkspaceEdit, error) {
|
| 418 |
+
var result protocol.WorkspaceEdit
|
| 419 |
+
err := c.Call(ctx, "textDocument/rename", params, &result)
|
| 420 |
+
return result, err
|
| 421 |
+
}
|
| 422 |
+
|
| 423 |
+
// PrepareRename sends a textDocument/prepareRename request to the LSP server.
|
| 424 |
+
// A request to test and perform the setup necessary for a rename. Since 3.16 - support for default behavior
|
| 425 |
+
func (c *Client) PrepareRename(ctx context.Context, params protocol.PrepareRenameParams) (protocol.PrepareRenameResult, error) {
|
| 426 |
+
var result protocol.PrepareRenameResult
|
| 427 |
+
err := c.Call(ctx, "textDocument/prepareRename", params, &result)
|
| 428 |
+
return result, err
|
| 429 |
+
}
|
| 430 |
+
|
| 431 |
+
// ExecuteCommand sends a workspace/executeCommand request to the LSP server.
|
| 432 |
+
// A request send from the client to the server to execute a command. The request might return a workspace edit which the client will apply to the workspace.
|
| 433 |
+
func (c *Client) ExecuteCommand(ctx context.Context, params protocol.ExecuteCommandParams) (any, error) {
|
| 434 |
+
var result any
|
| 435 |
+
err := c.Call(ctx, "workspace/executeCommand", params, &result)
|
| 436 |
+
return result, err
|
| 437 |
+
}
|
| 438 |
+
|
| 439 |
+
// DidChangeWorkspaceFolders sends a workspace/didChangeWorkspaceFolders notification to the LSP server.
|
| 440 |
+
// The workspace/didChangeWorkspaceFolders notification is sent from the client to the server when the workspace folder configuration changes.
|
| 441 |
+
func (c *Client) DidChangeWorkspaceFolders(ctx context.Context, params protocol.DidChangeWorkspaceFoldersParams) error {
|
| 442 |
+
return c.Notify(ctx, "workspace/didChangeWorkspaceFolders", params)
|
| 443 |
+
}
|
| 444 |
+
|
| 445 |
+
// WorkDoneProgressCancel sends a window/workDoneProgress/cancel notification to the LSP server.
|
| 446 |
+
// The window/workDoneProgress/cancel notification is sent from the client to the server to cancel a progress initiated on the server side.
|
| 447 |
+
func (c *Client) WorkDoneProgressCancel(ctx context.Context, params protocol.WorkDoneProgressCancelParams) error {
|
| 448 |
+
return c.Notify(ctx, "window/workDoneProgress/cancel", params)
|
| 449 |
+
}
|
| 450 |
+
|
| 451 |
+
// DidCreateFiles sends a workspace/didCreateFiles notification to the LSP server.
|
| 452 |
+
// The did create files notification is sent from the client to the server when files were created from within the client. Since 3.16.0
|
| 453 |
+
func (c *Client) DidCreateFiles(ctx context.Context, params protocol.CreateFilesParams) error {
|
| 454 |
+
return c.Notify(ctx, "workspace/didCreateFiles", params)
|
| 455 |
+
}
|
| 456 |
+
|
| 457 |
+
// DidRenameFiles sends a workspace/didRenameFiles notification to the LSP server.
|
| 458 |
+
// The did rename files notification is sent from the client to the server when files were renamed from within the client. Since 3.16.0
|
| 459 |
+
func (c *Client) DidRenameFiles(ctx context.Context, params protocol.RenameFilesParams) error {
|
| 460 |
+
return c.Notify(ctx, "workspace/didRenameFiles", params)
|
| 461 |
+
}
|
| 462 |
+
|
| 463 |
+
// DidDeleteFiles sends a workspace/didDeleteFiles notification to the LSP server.
|
| 464 |
+
// The will delete files request is sent from the client to the server before files are actually deleted as long as the deletion is triggered from within the client. Since 3.16.0
|
| 465 |
+
func (c *Client) DidDeleteFiles(ctx context.Context, params protocol.DeleteFilesParams) error {
|
| 466 |
+
return c.Notify(ctx, "workspace/didDeleteFiles", params)
|
| 467 |
+
}
|
| 468 |
+
|
| 469 |
+
// DidOpenNotebookDocument sends a notebookDocument/didOpen notification to the LSP server.
|
| 470 |
+
// A notification sent when a notebook opens. Since 3.17.0
|
| 471 |
+
func (c *Client) DidOpenNotebookDocument(ctx context.Context, params protocol.DidOpenNotebookDocumentParams) error {
|
| 472 |
+
return c.Notify(ctx, "notebookDocument/didOpen", params)
|
| 473 |
+
}
|
| 474 |
+
|
| 475 |
+
// DidChangeNotebookDocument sends a notebookDocument/didChange notification to the LSP server.
|
| 476 |
+
func (c *Client) DidChangeNotebookDocument(ctx context.Context, params protocol.DidChangeNotebookDocumentParams) error {
|
| 477 |
+
return c.Notify(ctx, "notebookDocument/didChange", params)
|
| 478 |
+
}
|
| 479 |
+
|
| 480 |
+
// DidSaveNotebookDocument sends a notebookDocument/didSave notification to the LSP server.
|
| 481 |
+
// A notification sent when a notebook document is saved. Since 3.17.0
|
| 482 |
+
func (c *Client) DidSaveNotebookDocument(ctx context.Context, params protocol.DidSaveNotebookDocumentParams) error {
|
| 483 |
+
return c.Notify(ctx, "notebookDocument/didSave", params)
|
| 484 |
+
}
|
| 485 |
+
|
| 486 |
+
// DidCloseNotebookDocument sends a notebookDocument/didClose notification to the LSP server.
|
| 487 |
+
// A notification sent when a notebook closes. Since 3.17.0
|
| 488 |
+
func (c *Client) DidCloseNotebookDocument(ctx context.Context, params protocol.DidCloseNotebookDocumentParams) error {
|
| 489 |
+
return c.Notify(ctx, "notebookDocument/didClose", params)
|
| 490 |
+
}
|
| 491 |
+
|
| 492 |
+
// Initialized sends a initialized notification to the LSP server.
|
| 493 |
+
// The initialized notification is sent from the client to the server after the client is fully initialized and the server is allowed to send requests from the server to the client.
|
| 494 |
+
func (c *Client) Initialized(ctx context.Context, params protocol.InitializedParams) error {
|
| 495 |
+
return c.Notify(ctx, "initialized", params)
|
| 496 |
+
}
|
| 497 |
+
|
| 498 |
+
// Exit sends a exit notification to the LSP server.
|
| 499 |
+
// The exit event is sent from the client to the server to ask the server to exit its process.
|
| 500 |
+
func (c *Client) Exit(ctx context.Context) error {
|
| 501 |
+
return c.Notify(ctx, "exit", nil)
|
| 502 |
+
}
|
| 503 |
+
|
| 504 |
+
// DidChangeConfiguration sends a workspace/didChangeConfiguration notification to the LSP server.
|
| 505 |
+
// The configuration change notification is sent from the client to the server when the client's configuration has changed. The notification contains the changed configuration as defined by the language client.
|
| 506 |
+
func (c *Client) DidChangeConfiguration(ctx context.Context, params protocol.DidChangeConfigurationParams) error {
|
| 507 |
+
return c.Notify(ctx, "workspace/didChangeConfiguration", params)
|
| 508 |
+
}
|
| 509 |
+
|
| 510 |
+
// DidOpen sends a textDocument/didOpen notification to the LSP server.
|
| 511 |
+
// The document open notification is sent from the client to the server to signal newly opened text documents. The document's truth is now managed by the client and the server must not try to read the document's truth using the document's uri. Open in this sense means it is managed by the client. It doesn't necessarily mean that its content is presented in an editor. An open notification must not be sent more than once without a corresponding close notification send before. This means open and close notification must be balanced and the max open count is one.
|
| 512 |
+
func (c *Client) DidOpen(ctx context.Context, params protocol.DidOpenTextDocumentParams) error {
|
| 513 |
+
return c.Notify(ctx, "textDocument/didOpen", params)
|
| 514 |
+
}
|
| 515 |
+
|
| 516 |
+
// DidChange sends a textDocument/didChange notification to the LSP server.
|
| 517 |
+
// The document change notification is sent from the client to the server to signal changes to a text document.
|
| 518 |
+
func (c *Client) DidChange(ctx context.Context, params protocol.DidChangeTextDocumentParams) error {
|
| 519 |
+
return c.Notify(ctx, "textDocument/didChange", params)
|
| 520 |
+
}
|
| 521 |
+
|
| 522 |
+
// DidClose sends a textDocument/didClose notification to the LSP server.
|
| 523 |
+
// The document close notification is sent from the client to the server when the document got closed in the client. The document's truth now exists where the document's uri points to (e.g. if the document's uri is a file uri the truth now exists on disk). As with the open notification the close notification is about managing the document's content. Receiving a close notification doesn't mean that the document was open in an editor before. A close notification requires a previous open notification to be sent.
|
| 524 |
+
func (c *Client) DidClose(ctx context.Context, params protocol.DidCloseTextDocumentParams) error {
|
| 525 |
+
return c.Notify(ctx, "textDocument/didClose", params)
|
| 526 |
+
}
|
| 527 |
+
|
| 528 |
+
// DidSave sends a textDocument/didSave notification to the LSP server.
|
| 529 |
+
// The document save notification is sent from the client to the server when the document got saved in the client.
|
| 530 |
+
func (c *Client) DidSave(ctx context.Context, params protocol.DidSaveTextDocumentParams) error {
|
| 531 |
+
return c.Notify(ctx, "textDocument/didSave", params)
|
| 532 |
+
}
|
| 533 |
+
|
| 534 |
+
// WillSave sends a textDocument/willSave notification to the LSP server.
|
| 535 |
+
// A document will save notification is sent from the client to the server before the document is actually saved.
|
| 536 |
+
func (c *Client) WillSave(ctx context.Context, params protocol.WillSaveTextDocumentParams) error {
|
| 537 |
+
return c.Notify(ctx, "textDocument/willSave", params)
|
| 538 |
+
}
|
| 539 |
+
|
| 540 |
+
// DidChangeWatchedFiles sends a workspace/didChangeWatchedFiles notification to the LSP server.
|
| 541 |
+
// The watched files notification is sent from the client to the server when the client detects changes to file watched by the language client.
|
| 542 |
+
func (c *Client) DidChangeWatchedFiles(ctx context.Context, params protocol.DidChangeWatchedFilesParams) error {
|
| 543 |
+
return c.Notify(ctx, "workspace/didChangeWatchedFiles", params)
|
| 544 |
+
}
|
| 545 |
+
|
| 546 |
+
// SetTrace sends a $/setTrace notification to the LSP server.
|
| 547 |
+
func (c *Client) SetTrace(ctx context.Context, params protocol.SetTraceParams) error {
|
| 548 |
+
return c.Notify(ctx, "$/setTrace", params)
|
| 549 |
+
}
|
| 550 |
+
|
| 551 |
+
// Progress sends a $/progress notification to the LSP server.
|
| 552 |
+
func (c *Client) Progress(ctx context.Context, params protocol.ProgressParams) error {
|
| 553 |
+
return c.Notify(ctx, "$/progress", params)
|
| 554 |
+
}
|
projects/ui/crush/internal/lsp/protocol.go
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package lsp
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"encoding/json"
|
| 5 |
+
)
|
| 6 |
+
|
| 7 |
+
// Message represents a JSON-RPC 2.0 message
|
| 8 |
+
type Message struct {
|
| 9 |
+
JSONRPC string `json:"jsonrpc"`
|
| 10 |
+
ID int32 `json:"id,omitempty"`
|
| 11 |
+
Method string `json:"method,omitempty"`
|
| 12 |
+
Params json.RawMessage `json:"params,omitempty"`
|
| 13 |
+
Result json.RawMessage `json:"result,omitempty"`
|
| 14 |
+
Error *ResponseError `json:"error,omitempty"`
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
// ResponseError represents a JSON-RPC 2.0 error
|
| 18 |
+
type ResponseError struct {
|
| 19 |
+
Code int `json:"code"`
|
| 20 |
+
Message string `json:"message"`
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
func NewRequest(id int32, method string, params any) (*Message, error) {
|
| 24 |
+
paramsJSON, err := json.Marshal(params)
|
| 25 |
+
if err != nil {
|
| 26 |
+
return nil, err
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
return &Message{
|
| 30 |
+
JSONRPC: "2.0",
|
| 31 |
+
ID: id,
|
| 32 |
+
Method: method,
|
| 33 |
+
Params: paramsJSON,
|
| 34 |
+
}, nil
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
func NewNotification(method string, params any) (*Message, error) {
|
| 38 |
+
paramsJSON, err := json.Marshal(params)
|
| 39 |
+
if err != nil {
|
| 40 |
+
return nil, err
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
return &Message{
|
| 44 |
+
JSONRPC: "2.0",
|
| 45 |
+
Method: method,
|
| 46 |
+
Params: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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package lsp
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"bufio"
|
| 5 |
+
"context"
|
| 6 |
+
"encoding/json"
|
| 7 |
+
"fmt"
|
| 8 |
+
"io"
|
| 9 |
+
"log/slog"
|
| 10 |
+
"strings"
|
| 11 |
+
|
| 12 |
+
"github.com/charmbracelet/crush/internal/config"
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
// WriteMessage writes an LSP message to the given writer
|
| 16 |
+
func WriteMessage(w io.Writer, msg *Message) error {
|
| 17 |
+
data, err := json.Marshal(msg)
|
| 18 |
+
if err != nil {
|
| 19 |
+
return fmt.Errorf("failed to marshal message: %w", err)
|
| 20 |
+
}
|
| 21 |
+
cfg := config.Get()
|
| 22 |
+
|
| 23 |
+
if cfg.Options.DebugLSP {
|
| 24 |
+
slog.Debug("Sending message to server", "method", msg.Method, "id", msg.ID)
|
| 25 |
+
}
|
| 26 |
+
|
| 27 |
+
_, err = fmt.Fprintf(w, "Content-Length: %d\r\n\r\n", len(data))
|
| 28 |
+
if err != nil {
|
| 29 |
+
return fmt.Errorf("failed to write header: %w", err)
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
_, err = w.Write(data)
|
| 33 |
+
if err != nil {
|
| 34 |
+
return fmt.Errorf("failed to write message: %w", err)
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
return nil
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
// ReadMessage reads a single LSP message from the given reader
|
| 41 |
+
func ReadMessage(r *bufio.Reader) (*Message, error) {
|
| 42 |
+
cfg := config.Get()
|
| 43 |
+
// Read headers
|
| 44 |
+
var contentLength int
|
| 45 |
+
for {
|
| 46 |
+
line, err := r.ReadString('\n')
|
| 47 |
+
if err != nil {
|
| 48 |
+
return nil, fmt.Errorf("failed to read header: %w", err)
|
| 49 |
+
}
|
| 50 |
+
line = strings.TrimSpace(line)
|
| 51 |
+
|
| 52 |
+
if cfg.Options.DebugLSP {
|
| 53 |
+
slog.Debug("Received header", "line", line)
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
if line == "" {
|
| 57 |
+
break // End of headers
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
if strings.HasPrefix(line, "Content-Length: ") {
|
| 61 |
+
_, err := fmt.Sscanf(line, "Content-Length: %d", &contentLength)
|
| 62 |
+
if err != nil {
|
| 63 |
+
return nil, fmt.Errorf("invalid Content-Length: %w", err)
|
| 64 |
+
}
|
| 65 |
+
}
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
if cfg.Options.DebugLSP {
|
| 69 |
+
slog.Debug("Content-Length", "length", contentLength)
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
// Read content
|
| 73 |
+
content := make([]byte, contentLength)
|
| 74 |
+
_, err := io.ReadFull(r, content)
|
| 75 |
+
if err != nil {
|
| 76 |
+
return nil, fmt.Errorf("failed to read content: %w", err)
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
if cfg.Options.DebugLSP {
|
| 80 |
+
slog.Debug("Received content", "content", string(content))
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
// Parse message
|
| 84 |
+
var msg Message
|
| 85 |
+
if err := json.Unmarshal(content, &msg); err != nil {
|
| 86 |
+
return nil, fmt.Errorf("failed to unmarshal message: %w", err)
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
return &msg, nil
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
// handleMessages reads and dispatches messages in a loop
|
| 93 |
+
func (c *Client) handleMessages() {
|
| 94 |
+
cfg := config.Get()
|
| 95 |
+
for {
|
| 96 |
+
msg, err := ReadMessage(c.stdout)
|
| 97 |
+
if err != nil {
|
| 98 |
+
if cfg.Options.DebugLSP {
|
| 99 |
+
slog.Error("Error reading message", "error", err)
|
| 100 |
+
}
|
| 101 |
+
return
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
// Handle server->client request (has both Method and ID)
|
| 105 |
+
if msg.Method != "" && msg.ID != 0 {
|
| 106 |
+
if cfg.Options.DebugLSP {
|
| 107 |
+
slog.Debug("Received request from server", "method", msg.Method, "id", msg.ID)
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
response := &Message{
|
| 111 |
+
JSONRPC: "2.0",
|
| 112 |
+
ID: msg.ID,
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
// Look up handler for this method
|
| 116 |
+
c.serverHandlersMu.RLock()
|
| 117 |
+
handler, ok := c.serverRequestHandlers[msg.Method]
|
| 118 |
+
c.serverHandlersMu.RUnlock()
|
| 119 |
+
|
| 120 |
+
if ok {
|
| 121 |
+
result, err := handler(msg.Params)
|
| 122 |
+
if err != nil {
|
| 123 |
+
response.Error = &ResponseError{
|
| 124 |
+
Code: -32603,
|
| 125 |
+
Message: err.Error(),
|
| 126 |
+
}
|
| 127 |
+
} else {
|
| 128 |
+
rawJSON, err := json.Marshal(result)
|
| 129 |
+
if err != nil {
|
| 130 |
+
response.Error = &ResponseError{
|
| 131 |
+
Code: -32603,
|
| 132 |
+
Message: fmt.Sprintf("failed to marshal response: %v", err),
|
| 133 |
+
}
|
| 134 |
+
} else {
|
| 135 |
+
response.Result = rawJSON
|
| 136 |
+
}
|
| 137 |
+
}
|
| 138 |
+
} else {
|
| 139 |
+
response.Error = &ResponseError{
|
| 140 |
+
Code: -32601,
|
| 141 |
+
Message: fmt.Sprintf("method not found: %s", msg.Method),
|
| 142 |
+
}
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
// Send response back to server
|
| 146 |
+
if err := WriteMessage(c.stdin, response); err != nil {
|
| 147 |
+
slog.Error("Error sending response to server", "error", err)
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
continue
|
| 151 |
+
}
|
| 152 |
+
|
| 153 |
+
// Handle notification (has Method but no ID)
|
| 154 |
+
if msg.Method != "" && msg.ID == 0 {
|
| 155 |
+
c.notificationMu.RLock()
|
| 156 |
+
handler, ok := c.notificationHandlers[msg.Method]
|
| 157 |
+
c.notificationMu.RUnlock()
|
| 158 |
+
|
| 159 |
+
if ok {
|
| 160 |
+
if cfg.Options.DebugLSP {
|
| 161 |
+
slog.Debug("Handling notification", "method", msg.Method)
|
| 162 |
+
}
|
| 163 |
+
go handler(msg.Params)
|
| 164 |
+
} else if cfg.Options.DebugLSP {
|
| 165 |
+
slog.Debug("No handler for notification", "method", msg.Method)
|
| 166 |
+
}
|
| 167 |
+
continue
|
| 168 |
+
}
|
| 169 |
+
|
| 170 |
+
// Handle response to our request (has ID but no Method)
|
| 171 |
+
if msg.ID != 0 && msg.Method == "" {
|
| 172 |
+
c.handlersMu.RLock()
|
| 173 |
+
ch, ok := c.handlers[msg.ID]
|
| 174 |
+
c.handlersMu.RUnlock()
|
| 175 |
+
|
| 176 |
+
if ok {
|
| 177 |
+
if cfg.Options.DebugLSP {
|
| 178 |
+
slog.Debug("Received response for request", "id", msg.ID)
|
| 179 |
+
}
|
| 180 |
+
ch <- msg
|
| 181 |
+
close(ch)
|
| 182 |
+
} else if cfg.Options.DebugLSP {
|
| 183 |
+
slog.Debug("No handler for response", "id", msg.ID)
|
| 184 |
+
}
|
| 185 |
+
}
|
| 186 |
+
}
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
// Call makes a request and waits for the response
|
| 190 |
+
func (c *Client) Call(ctx context.Context, method string, params any, result any) error {
|
| 191 |
+
if !c.IsMethodSupported(method) {
|
| 192 |
+
return fmt.Errorf("method not supported by server: %s", method)
|
| 193 |
+
}
|
| 194 |
+
id := c.nextID.Add(1)
|
| 195 |
+
|
| 196 |
+
cfg := config.Get()
|
| 197 |
+
if cfg.Options.DebugLSP {
|
| 198 |
+
slog.Debug("Making call", "method", method, "id", id)
|
| 199 |
+
}
|
| 200 |
+
|
| 201 |
+
msg, err := NewRequest(id, method, params)
|
| 202 |
+
if err != nil {
|
| 203 |
+
return fmt.Errorf("failed to create request: %w", err)
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
// Create response channel
|
| 207 |
+
ch := make(chan *Message, 1)
|
| 208 |
+
c.handlersMu.Lock()
|
| 209 |
+
c.handlers[id] = ch
|
| 210 |
+
c.handlersMu.Unlock()
|
| 211 |
+
|
| 212 |
+
defer func() {
|
| 213 |
+
c.handlersMu.Lock()
|
| 214 |
+
delete(c.handlers, id)
|
| 215 |
+
c.handlersMu.Unlock()
|
| 216 |
+
}()
|
| 217 |
+
|
| 218 |
+
// Send request
|
| 219 |
+
if err := WriteMessage(c.stdin, msg); err != nil {
|
| 220 |
+
return fmt.Errorf("failed to send request: %w", err)
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
if cfg.Options.DebugLSP {
|
| 224 |
+
slog.Debug("Request sent", "method", method, "id", id)
|
| 225 |
+
}
|
| 226 |
+
|
| 227 |
+
// Wait for response
|
| 228 |
+
select {
|
| 229 |
+
case <-ctx.Done():
|
| 230 |
+
return ctx.Err()
|
| 231 |
+
case resp := <-ch:
|
| 232 |
+
if cfg.Options.DebugLSP {
|
| 233 |
+
slog.Debug("Received response", "id", id)
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
if resp.Error != nil {
|
| 237 |
+
return fmt.Errorf("request failed: %s (code: %d)", resp.Error.Message, resp.Error.Code)
|
| 238 |
+
}
|
| 239 |
+
|
| 240 |
+
if result != nil {
|
| 241 |
+
// If result is a json.RawMessage, just copy the raw bytes
|
| 242 |
+
if rawMsg, ok := result.(*json.RawMessage); ok {
|
| 243 |
+
*rawMsg = resp.Result
|
| 244 |
+
return nil
|
| 245 |
+
}
|
| 246 |
+
// Otherwise unmarshal into the provided type
|
| 247 |
+
if err := json.Unmarshal(resp.Result, result); err != nil {
|
| 248 |
+
return fmt.Errorf("failed to unmarshal result: %w", err)
|
| 249 |
+
}
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
return nil
|
| 253 |
+
}
|
| 254 |
+
}
|
| 255 |
+
|
| 256 |
+
// Notify sends a notification (a request without an ID that doesn't expect a response)
|
| 257 |
+
func (c *Client) Notify(ctx context.Context, method string, params any) error {
|
| 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 |
+
}
|
| 265 |
+
if cfg.Options.DebugLSP {
|
| 266 |
+
slog.Debug("Sending notification", "method", method)
|
| 267 |
+
}
|
| 268 |
+
|
| 269 |
+
msg, err := NewNotification(method, params)
|
| 270 |
+
if err != nil {
|
| 271 |
+
return fmt.Errorf("failed to create notification: %w", err)
|
| 272 |
+
}
|
| 273 |
+
|
| 274 |
+
if err := WriteMessage(c.stdin, msg); err != nil {
|
| 275 |
+
return fmt.Errorf("failed to send notification: %w", err)
|
| 276 |
+
}
|
| 277 |
+
|
| 278 |
+
return nil
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
type (
|
| 282 |
+
NotificationHandler func(params json.RawMessage)
|
| 283 |
+
ServerRequestHandler func(params json.RawMessage) (any, error)
|
| 284 |
+
)
|
projects/ui/crush/internal/message/attachment.go
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package message
|
| 2 |
+
|
| 3 |
+
type Attachment struct {
|
| 4 |
+
FilePath string
|
| 5 |
+
FileName string
|
| 6 |
+
MimeType string
|
| 7 |
+
Content []byte
|
| 8 |
+
}
|
projects/ui/crush/internal/message/content.go
ADDED
|
@@ -0,0 +1,386 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 14 |
+
Assistant MessageRole = "assistant"
|
| 15 |
+
User MessageRole = "user"
|
| 16 |
+
System MessageRole = "system"
|
| 17 |
+
Tool MessageRole = "tool"
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
+
type FinishReason string
|
| 21 |
+
|
| 22 |
+
const (
|
| 23 |
+
FinishReasonEndTurn FinishReason = "end_turn"
|
| 24 |
+
FinishReasonMaxTokens FinishReason = "max_tokens"
|
| 25 |
+
FinishReasonToolUse FinishReason = "tool_use"
|
| 26 |
+
FinishReasonCanceled FinishReason = "canceled"
|
| 27 |
+
FinishReasonError FinishReason = "error"
|
| 28 |
+
FinishReasonPermissionDenied FinishReason = "permission_denied"
|
| 29 |
+
|
| 30 |
+
// Should never happen
|
| 31 |
+
FinishReasonUnknown FinishReason = "unknown"
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
type ContentPart interface {
|
| 35 |
+
isPart()
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
type ReasoningContent struct {
|
| 39 |
+
Thinking string `json:"thinking"`
|
| 40 |
+
Signature string `json:"signature"`
|
| 41 |
+
StartedAt int64 `json:"started_at,omitempty"`
|
| 42 |
+
FinishedAt int64 `json:"finished_at,omitempty"`
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
func (tc ReasoningContent) String() string {
|
| 46 |
+
return tc.Thinking
|
| 47 |
+
}
|
| 48 |
+
func (ReasoningContent) isPart() {}
|
| 49 |
+
|
| 50 |
+
type TextContent struct {
|
| 51 |
+
Text string `json:"text"`
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
func (tc TextContent) String() string {
|
| 55 |
+
return tc.Text
|
| 56 |
+
}
|
| 57 |
+
|
| 58 |
+
func (TextContent) isPart() {}
|
| 59 |
+
|
| 60 |
+
type ImageURLContent struct {
|
| 61 |
+
URL string `json:"url"`
|
| 62 |
+
Detail string `json:"detail,omitempty"`
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
func (iuc ImageURLContent) String() string {
|
| 66 |
+
return iuc.URL
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
func (ImageURLContent) isPart() {}
|
| 70 |
+
|
| 71 |
+
type BinaryContent struct {
|
| 72 |
+
Path string
|
| 73 |
+
MIMEType string
|
| 74 |
+
Data []byte
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
func (bc BinaryContent) String(p catwalk.InferenceProvider) string {
|
| 78 |
+
base64Encoded := base64.StdEncoding.EncodeToString(bc.Data)
|
| 79 |
+
if p == catwalk.InferenceProviderOpenAI {
|
| 80 |
+
return "data:" + bc.MIMEType + ";base64," + base64Encoded
|
| 81 |
+
}
|
| 82 |
+
return base64Encoded
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
func (BinaryContent) isPart() {}
|
| 86 |
+
|
| 87 |
+
type ToolCall struct {
|
| 88 |
+
ID string `json:"id"`
|
| 89 |
+
Name string `json:"name"`
|
| 90 |
+
Input string `json:"input"`
|
| 91 |
+
Type string `json:"type"`
|
| 92 |
+
Finished bool `json:"finished"`
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
func (ToolCall) isPart() {}
|
| 96 |
+
|
| 97 |
+
type ToolResult struct {
|
| 98 |
+
ToolCallID string `json:"tool_call_id"`
|
| 99 |
+
Name string `json:"name"`
|
| 100 |
+
Content string `json:"content"`
|
| 101 |
+
Metadata string `json:"metadata"`
|
| 102 |
+
IsError bool `json:"is_error"`
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
func (ToolResult) isPart() {}
|
| 106 |
+
|
| 107 |
+
type Finish struct {
|
| 108 |
+
Reason FinishReason `json:"reason"`
|
| 109 |
+
Time int64 `json:"time"`
|
| 110 |
+
Message string `json:"message,omitempty"`
|
| 111 |
+
Details string `json:"details,omitempty"`
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
func (Finish) isPart() {}
|
| 115 |
+
|
| 116 |
+
type Message struct {
|
| 117 |
+
ID string
|
| 118 |
+
Role MessageRole
|
| 119 |
+
SessionID string
|
| 120 |
+
Parts []ContentPart
|
| 121 |
+
Model string
|
| 122 |
+
Provider string
|
| 123 |
+
CreatedAt int64
|
| 124 |
+
UpdatedAt int64
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
func (m *Message) Content() TextContent {
|
| 128 |
+
for _, part := range m.Parts {
|
| 129 |
+
if c, ok := part.(TextContent); ok {
|
| 130 |
+
return c
|
| 131 |
+
}
|
| 132 |
+
}
|
| 133 |
+
return TextContent{}
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
func (m *Message) ReasoningContent() ReasoningContent {
|
| 137 |
+
for _, part := range m.Parts {
|
| 138 |
+
if c, ok := part.(ReasoningContent); ok {
|
| 139 |
+
return c
|
| 140 |
+
}
|
| 141 |
+
}
|
| 142 |
+
return ReasoningContent{}
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
func (m *Message) ImageURLContent() []ImageURLContent {
|
| 146 |
+
imageURLContents := make([]ImageURLContent, 0)
|
| 147 |
+
for _, part := range m.Parts {
|
| 148 |
+
if c, ok := part.(ImageURLContent); ok {
|
| 149 |
+
imageURLContents = append(imageURLContents, c)
|
| 150 |
+
}
|
| 151 |
+
}
|
| 152 |
+
return imageURLContents
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
func (m *Message) BinaryContent() []BinaryContent {
|
| 156 |
+
binaryContents := make([]BinaryContent, 0)
|
| 157 |
+
for _, part := range m.Parts {
|
| 158 |
+
if c, ok := part.(BinaryContent); ok {
|
| 159 |
+
binaryContents = append(binaryContents, c)
|
| 160 |
+
}
|
| 161 |
+
}
|
| 162 |
+
return binaryContents
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
func (m *Message) ToolCalls() []ToolCall {
|
| 166 |
+
toolCalls := make([]ToolCall, 0)
|
| 167 |
+
for _, part := range m.Parts {
|
| 168 |
+
if c, ok := part.(ToolCall); ok {
|
| 169 |
+
toolCalls = append(toolCalls, c)
|
| 170 |
+
}
|
| 171 |
+
}
|
| 172 |
+
return toolCalls
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
func (m *Message) ToolResults() []ToolResult {
|
| 176 |
+
toolResults := make([]ToolResult, 0)
|
| 177 |
+
for _, part := range m.Parts {
|
| 178 |
+
if c, ok := part.(ToolResult); ok {
|
| 179 |
+
toolResults = append(toolResults, c)
|
| 180 |
+
}
|
| 181 |
+
}
|
| 182 |
+
return toolResults
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
func (m *Message) IsFinished() bool {
|
| 186 |
+
for _, part := range m.Parts {
|
| 187 |
+
if _, ok := part.(Finish); ok {
|
| 188 |
+
return true
|
| 189 |
+
}
|
| 190 |
+
}
|
| 191 |
+
return false
|
| 192 |
+
}
|
| 193 |
+
|
| 194 |
+
func (m *Message) FinishPart() *Finish {
|
| 195 |
+
for _, part := range m.Parts {
|
| 196 |
+
if c, ok := part.(Finish); ok {
|
| 197 |
+
return &c
|
| 198 |
+
}
|
| 199 |
+
}
|
| 200 |
+
return nil
|
| 201 |
+
}
|
| 202 |
+
|
| 203 |
+
func (m *Message) FinishReason() FinishReason {
|
| 204 |
+
for _, part := range m.Parts {
|
| 205 |
+
if c, ok := part.(Finish); ok {
|
| 206 |
+
return c.Reason
|
| 207 |
+
}
|
| 208 |
+
}
|
| 209 |
+
return ""
|
| 210 |
+
}
|
| 211 |
+
|
| 212 |
+
func (m *Message) IsThinking() bool {
|
| 213 |
+
if m.ReasoningContent().Thinking != "" && m.Content().Text == "" && !m.IsFinished() {
|
| 214 |
+
return true
|
| 215 |
+
}
|
| 216 |
+
return false
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
func (m *Message) AppendContent(delta string) {
|
| 220 |
+
found := false
|
| 221 |
+
for i, part := range m.Parts {
|
| 222 |
+
if c, ok := part.(TextContent); ok {
|
| 223 |
+
m.Parts[i] = TextContent{Text: c.Text + delta}
|
| 224 |
+
found = true
|
| 225 |
+
}
|
| 226 |
+
}
|
| 227 |
+
if !found {
|
| 228 |
+
m.Parts = append(m.Parts, TextContent{Text: delta})
|
| 229 |
+
}
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
func (m *Message) AppendReasoningContent(delta string) {
|
| 233 |
+
found := false
|
| 234 |
+
for i, part := range m.Parts {
|
| 235 |
+
if c, ok := part.(ReasoningContent); ok {
|
| 236 |
+
m.Parts[i] = ReasoningContent{
|
| 237 |
+
Thinking: c.Thinking + delta,
|
| 238 |
+
Signature: c.Signature,
|
| 239 |
+
StartedAt: c.StartedAt,
|
| 240 |
+
FinishedAt: c.FinishedAt,
|
| 241 |
+
}
|
| 242 |
+
found = true
|
| 243 |
+
}
|
| 244 |
+
}
|
| 245 |
+
if !found {
|
| 246 |
+
m.Parts = append(m.Parts, ReasoningContent{
|
| 247 |
+
Thinking: delta,
|
| 248 |
+
StartedAt: time.Now().Unix(),
|
| 249 |
+
})
|
| 250 |
+
}
|
| 251 |
+
}
|
| 252 |
+
|
| 253 |
+
func (m *Message) AppendReasoningSignature(signature string) {
|
| 254 |
+
for i, part := range m.Parts {
|
| 255 |
+
if c, ok := part.(ReasoningContent); ok {
|
| 256 |
+
m.Parts[i] = ReasoningContent{
|
| 257 |
+
Thinking: c.Thinking,
|
| 258 |
+
Signature: c.Signature + signature,
|
| 259 |
+
StartedAt: c.StartedAt,
|
| 260 |
+
FinishedAt: c.FinishedAt,
|
| 261 |
+
}
|
| 262 |
+
return
|
| 263 |
+
}
|
| 264 |
+
}
|
| 265 |
+
m.Parts = append(m.Parts, ReasoningContent{Signature: signature})
|
| 266 |
+
}
|
| 267 |
+
|
| 268 |
+
func (m *Message) FinishThinking() {
|
| 269 |
+
for i, part := range m.Parts {
|
| 270 |
+
if c, ok := part.(ReasoningContent); ok {
|
| 271 |
+
if c.FinishedAt == 0 {
|
| 272 |
+
m.Parts[i] = ReasoningContent{
|
| 273 |
+
Thinking: c.Thinking,
|
| 274 |
+
Signature: c.Signature,
|
| 275 |
+
StartedAt: c.StartedAt,
|
| 276 |
+
FinishedAt: time.Now().Unix(),
|
| 277 |
+
}
|
| 278 |
+
}
|
| 279 |
+
return
|
| 280 |
+
}
|
| 281 |
+
}
|
| 282 |
+
}
|
| 283 |
+
|
| 284 |
+
func (m *Message) ThinkingDuration() time.Duration {
|
| 285 |
+
reasoning := m.ReasoningContent()
|
| 286 |
+
if reasoning.StartedAt == 0 {
|
| 287 |
+
return 0
|
| 288 |
+
}
|
| 289 |
+
|
| 290 |
+
endTime := reasoning.FinishedAt
|
| 291 |
+
if endTime == 0 {
|
| 292 |
+
endTime = time.Now().Unix()
|
| 293 |
+
}
|
| 294 |
+
|
| 295 |
+
return time.Duration(endTime-reasoning.StartedAt) * time.Second
|
| 296 |
+
}
|
| 297 |
+
|
| 298 |
+
func (m *Message) FinishToolCall(toolCallID string) {
|
| 299 |
+
for i, part := range m.Parts {
|
| 300 |
+
if c, ok := part.(ToolCall); ok {
|
| 301 |
+
if c.ID == toolCallID {
|
| 302 |
+
m.Parts[i] = ToolCall{
|
| 303 |
+
ID: c.ID,
|
| 304 |
+
Name: c.Name,
|
| 305 |
+
Input: c.Input,
|
| 306 |
+
Type: c.Type,
|
| 307 |
+
Finished: true,
|
| 308 |
+
}
|
| 309 |
+
return
|
| 310 |
+
}
|
| 311 |
+
}
|
| 312 |
+
}
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
func (m *Message) AppendToolCallInput(toolCallID string, inputDelta string) {
|
| 316 |
+
for i, part := range m.Parts {
|
| 317 |
+
if c, ok := part.(ToolCall); ok {
|
| 318 |
+
if c.ID == toolCallID {
|
| 319 |
+
m.Parts[i] = ToolCall{
|
| 320 |
+
ID: c.ID,
|
| 321 |
+
Name: c.Name,
|
| 322 |
+
Input: c.Input + inputDelta,
|
| 323 |
+
Type: c.Type,
|
| 324 |
+
Finished: c.Finished,
|
| 325 |
+
}
|
| 326 |
+
return
|
| 327 |
+
}
|
| 328 |
+
}
|
| 329 |
+
}
|
| 330 |
+
}
|
| 331 |
+
|
| 332 |
+
func (m *Message) AddToolCall(tc ToolCall) {
|
| 333 |
+
for i, part := range m.Parts {
|
| 334 |
+
if c, ok := part.(ToolCall); ok {
|
| 335 |
+
if c.ID == tc.ID {
|
| 336 |
+
m.Parts[i] = tc
|
| 337 |
+
return
|
| 338 |
+
}
|
| 339 |
+
}
|
| 340 |
+
}
|
| 341 |
+
m.Parts = append(m.Parts, tc)
|
| 342 |
+
}
|
| 343 |
+
|
| 344 |
+
func (m *Message) SetToolCalls(tc []ToolCall) {
|
| 345 |
+
// remove any existing tool call part it could have multiple
|
| 346 |
+
parts := make([]ContentPart, 0)
|
| 347 |
+
for _, part := range m.Parts {
|
| 348 |
+
if _, ok := part.(ToolCall); ok {
|
| 349 |
+
continue
|
| 350 |
+
}
|
| 351 |
+
parts = append(parts, part)
|
| 352 |
+
}
|
| 353 |
+
m.Parts = parts
|
| 354 |
+
for _, toolCall := range tc {
|
| 355 |
+
m.Parts = append(m.Parts, toolCall)
|
| 356 |
+
}
|
| 357 |
+
}
|
| 358 |
+
|
| 359 |
+
func (m *Message) AddToolResult(tr ToolResult) {
|
| 360 |
+
m.Parts = append(m.Parts, tr)
|
| 361 |
+
}
|
| 362 |
+
|
| 363 |
+
func (m *Message) SetToolResults(tr []ToolResult) {
|
| 364 |
+
for _, toolResult := range tr {
|
| 365 |
+
m.Parts = append(m.Parts, toolResult)
|
| 366 |
+
}
|
| 367 |
+
}
|
| 368 |
+
|
| 369 |
+
func (m *Message) AddFinish(reason FinishReason, message, details string) {
|
| 370 |
+
// remove any existing finish part
|
| 371 |
+
for i, part := range m.Parts {
|
| 372 |
+
if _, ok := part.(Finish); ok {
|
| 373 |
+
m.Parts = slices.Delete(m.Parts, i, i+1)
|
| 374 |
+
break
|
| 375 |
+
}
|
| 376 |
+
}
|
| 377 |
+
m.Parts = append(m.Parts, Finish{Reason: reason, Time: time.Now().Unix(), Message: message, Details: details})
|
| 378 |
+
}
|
| 379 |
+
|
| 380 |
+
func (m *Message) AddImageURL(url, detail string) {
|
| 381 |
+
m.Parts = append(m.Parts, ImageURLContent{URL: url, Detail: detail})
|
| 382 |
+
}
|
| 383 |
+
|
| 384 |
+
func (m *Message) AddBinary(mimeType string, data []byte) {
|
| 385 |
+
m.Parts = append(m.Parts, BinaryContent{MIMEType: mimeType, Data: data})
|
| 386 |
+
}
|
projects/ui/crush/internal/message/message.go
ADDED
|
@@ -0,0 +1,282 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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"
|
| 11 |
+
"github.com/charmbracelet/crush/internal/pubsub"
|
| 12 |
+
"github.com/google/uuid"
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
type CreateMessageParams struct {
|
| 16 |
+
Role MessageRole
|
| 17 |
+
Parts []ContentPart
|
| 18 |
+
Model string
|
| 19 |
+
Provider string
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
type Service interface {
|
| 23 |
+
pubsub.Suscriber[Message]
|
| 24 |
+
Create(ctx context.Context, sessionID string, params CreateMessageParams) (Message, error)
|
| 25 |
+
Update(ctx context.Context, message Message) error
|
| 26 |
+
Get(ctx context.Context, id string) (Message, error)
|
| 27 |
+
List(ctx context.Context, sessionID string) ([]Message, error)
|
| 28 |
+
Delete(ctx context.Context, id string) error
|
| 29 |
+
DeleteSessionMessages(ctx context.Context, sessionID string) error
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
type service struct {
|
| 33 |
+
*pubsub.Broker[Message]
|
| 34 |
+
q db.Querier
|
| 35 |
+
}
|
| 36 |
+
|
| 37 |
+
func NewService(q db.Querier) Service {
|
| 38 |
+
return &service{
|
| 39 |
+
Broker: pubsub.NewBroker[Message](),
|
| 40 |
+
q: q,
|
| 41 |
+
}
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
func (s *service) Delete(ctx context.Context, id string) error {
|
| 45 |
+
message, err := s.Get(ctx, id)
|
| 46 |
+
if err != nil {
|
| 47 |
+
return err
|
| 48 |
+
}
|
| 49 |
+
err = s.q.DeleteMessage(ctx, message.ID)
|
| 50 |
+
if err != nil {
|
| 51 |
+
return err
|
| 52 |
+
}
|
| 53 |
+
s.Publish(pubsub.DeletedEvent, message)
|
| 54 |
+
return nil
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
func (s *service) Create(ctx context.Context, sessionID string, params CreateMessageParams) (Message, error) {
|
| 58 |
+
if params.Role != Assistant {
|
| 59 |
+
params.Parts = append(params.Parts, Finish{
|
| 60 |
+
Reason: "stop",
|
| 61 |
+
})
|
| 62 |
+
}
|
| 63 |
+
partsJSON, err := marshallParts(params.Parts)
|
| 64 |
+
if err != nil {
|
| 65 |
+
return Message{}, err
|
| 66 |
+
}
|
| 67 |
+
dbMessage, err := s.q.CreateMessage(ctx, db.CreateMessageParams{
|
| 68 |
+
ID: uuid.New().String(),
|
| 69 |
+
SessionID: sessionID,
|
| 70 |
+
Role: string(params.Role),
|
| 71 |
+
Parts: string(partsJSON),
|
| 72 |
+
Model: sql.NullString{String: string(params.Model), Valid: true},
|
| 73 |
+
Provider: sql.NullString{String: params.Provider, Valid: params.Provider != ""},
|
| 74 |
+
})
|
| 75 |
+
if err != nil {
|
| 76 |
+
return Message{}, err
|
| 77 |
+
}
|
| 78 |
+
message, err := s.fromDBItem(dbMessage)
|
| 79 |
+
if err != nil {
|
| 80 |
+
return Message{}, err
|
| 81 |
+
}
|
| 82 |
+
s.Publish(pubsub.CreatedEvent, message)
|
| 83 |
+
return message, nil
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
func (s *service) DeleteSessionMessages(ctx context.Context, sessionID string) error {
|
| 87 |
+
messages, err := s.List(ctx, sessionID)
|
| 88 |
+
if err != nil {
|
| 89 |
+
return err
|
| 90 |
+
}
|
| 91 |
+
for _, message := range messages {
|
| 92 |
+
if message.SessionID == sessionID {
|
| 93 |
+
err = s.Delete(ctx, message.ID)
|
| 94 |
+
if err != nil {
|
| 95 |
+
return err
|
| 96 |
+
}
|
| 97 |
+
}
|
| 98 |
+
}
|
| 99 |
+
return nil
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
func (s *service) Update(ctx context.Context, message Message) error {
|
| 103 |
+
parts, err := marshallParts(message.Parts)
|
| 104 |
+
if err != nil {
|
| 105 |
+
return err
|
| 106 |
+
}
|
| 107 |
+
finishedAt := sql.NullInt64{}
|
| 108 |
+
if f := message.FinishPart(); f != nil {
|
| 109 |
+
finishedAt.Int64 = f.Time
|
| 110 |
+
finishedAt.Valid = true
|
| 111 |
+
}
|
| 112 |
+
err = s.q.UpdateMessage(ctx, db.UpdateMessageParams{
|
| 113 |
+
ID: message.ID,
|
| 114 |
+
Parts: string(parts),
|
| 115 |
+
FinishedAt: finishedAt,
|
| 116 |
+
})
|
| 117 |
+
if err != nil {
|
| 118 |
+
return err
|
| 119 |
+
}
|
| 120 |
+
message.UpdatedAt = time.Now().Unix()
|
| 121 |
+
s.Publish(pubsub.UpdatedEvent, message)
|
| 122 |
+
return nil
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
func (s *service) Get(ctx context.Context, id string) (Message, error) {
|
| 126 |
+
dbMessage, err := s.q.GetMessage(ctx, id)
|
| 127 |
+
if err != nil {
|
| 128 |
+
return Message{}, err
|
| 129 |
+
}
|
| 130 |
+
return s.fromDBItem(dbMessage)
|
| 131 |
+
}
|
| 132 |
+
|
| 133 |
+
func (s *service) List(ctx context.Context, sessionID string) ([]Message, error) {
|
| 134 |
+
dbMessages, err := s.q.ListMessagesBySession(ctx, sessionID)
|
| 135 |
+
if err != nil {
|
| 136 |
+
return nil, err
|
| 137 |
+
}
|
| 138 |
+
messages := make([]Message, len(dbMessages))
|
| 139 |
+
for i, dbMessage := range dbMessages {
|
| 140 |
+
messages[i], err = s.fromDBItem(dbMessage)
|
| 141 |
+
if err != nil {
|
| 142 |
+
return nil, err
|
| 143 |
+
}
|
| 144 |
+
}
|
| 145 |
+
return messages, nil
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
func (s *service) fromDBItem(item db.Message) (Message, error) {
|
| 149 |
+
parts, err := unmarshallParts([]byte(item.Parts))
|
| 150 |
+
if err != nil {
|
| 151 |
+
return Message{}, err
|
| 152 |
+
}
|
| 153 |
+
return Message{
|
| 154 |
+
ID: item.ID,
|
| 155 |
+
SessionID: item.SessionID,
|
| 156 |
+
Role: MessageRole(item.Role),
|
| 157 |
+
Parts: parts,
|
| 158 |
+
Model: item.Model.String,
|
| 159 |
+
Provider: item.Provider.String,
|
| 160 |
+
CreatedAt: item.CreatedAt,
|
| 161 |
+
UpdatedAt: item.UpdatedAt,
|
| 162 |
+
}, nil
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
type partType string
|
| 166 |
+
|
| 167 |
+
const (
|
| 168 |
+
reasoningType partType = "reasoning"
|
| 169 |
+
textType partType = "text"
|
| 170 |
+
imageURLType partType = "image_url"
|
| 171 |
+
binaryType partType = "binary"
|
| 172 |
+
toolCallType partType = "tool_call"
|
| 173 |
+
toolResultType partType = "tool_result"
|
| 174 |
+
finishType partType = "finish"
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
type partWrapper struct {
|
| 178 |
+
Type partType `json:"type"`
|
| 179 |
+
Data ContentPart `json:"data"`
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
func marshallParts(parts []ContentPart) ([]byte, error) {
|
| 183 |
+
wrappedParts := make([]partWrapper, len(parts))
|
| 184 |
+
|
| 185 |
+
for i, part := range parts {
|
| 186 |
+
var typ partType
|
| 187 |
+
|
| 188 |
+
switch part.(type) {
|
| 189 |
+
case ReasoningContent:
|
| 190 |
+
typ = reasoningType
|
| 191 |
+
case TextContent:
|
| 192 |
+
typ = textType
|
| 193 |
+
case ImageURLContent:
|
| 194 |
+
typ = imageURLType
|
| 195 |
+
case BinaryContent:
|
| 196 |
+
typ = binaryType
|
| 197 |
+
case ToolCall:
|
| 198 |
+
typ = toolCallType
|
| 199 |
+
case ToolResult:
|
| 200 |
+
typ = toolResultType
|
| 201 |
+
case Finish:
|
| 202 |
+
typ = finishType
|
| 203 |
+
default:
|
| 204 |
+
return nil, fmt.Errorf("unknown part type: %T", part)
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
wrappedParts[i] = partWrapper{
|
| 208 |
+
Type: typ,
|
| 209 |
+
Data: part,
|
| 210 |
+
}
|
| 211 |
+
}
|
| 212 |
+
return json.Marshal(wrappedParts)
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
func unmarshallParts(data []byte) ([]ContentPart, error) {
|
| 216 |
+
temp := []json.RawMessage{}
|
| 217 |
+
|
| 218 |
+
if err := json.Unmarshal(data, &temp); err != nil {
|
| 219 |
+
return nil, err
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
parts := make([]ContentPart, 0)
|
| 223 |
+
|
| 224 |
+
for _, rawPart := range temp {
|
| 225 |
+
var wrapper struct {
|
| 226 |
+
Type partType `json:"type"`
|
| 227 |
+
Data json.RawMessage `json:"data"`
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
if err := json.Unmarshal(rawPart, &wrapper); err != nil {
|
| 231 |
+
return nil, err
|
| 232 |
+
}
|
| 233 |
+
|
| 234 |
+
switch wrapper.Type {
|
| 235 |
+
case reasoningType:
|
| 236 |
+
part := ReasoningContent{}
|
| 237 |
+
if err := json.Unmarshal(wrapper.Data, &part); err != nil {
|
| 238 |
+
return nil, err
|
| 239 |
+
}
|
| 240 |
+
parts = append(parts, part)
|
| 241 |
+
case textType:
|
| 242 |
+
part := TextContent{}
|
| 243 |
+
if err := json.Unmarshal(wrapper.Data, &part); err != nil {
|
| 244 |
+
return nil, err
|
| 245 |
+
}
|
| 246 |
+
parts = append(parts, part)
|
| 247 |
+
case imageURLType:
|
| 248 |
+
part := ImageURLContent{}
|
| 249 |
+
if err := json.Unmarshal(wrapper.Data, &part); err != nil {
|
| 250 |
+
return nil, err
|
| 251 |
+
}
|
| 252 |
+
case binaryType:
|
| 253 |
+
part := BinaryContent{}
|
| 254 |
+
if err := json.Unmarshal(wrapper.Data, &part); err != nil {
|
| 255 |
+
return nil, err
|
| 256 |
+
}
|
| 257 |
+
parts = append(parts, part)
|
| 258 |
+
case toolCallType:
|
| 259 |
+
part := ToolCall{}
|
| 260 |
+
if err := json.Unmarshal(wrapper.Data, &part); err != nil {
|
| 261 |
+
return nil, err
|
| 262 |
+
}
|
| 263 |
+
parts = append(parts, part)
|
| 264 |
+
case toolResultType:
|
| 265 |
+
part := ToolResult{}
|
| 266 |
+
if err := json.Unmarshal(wrapper.Data, &part); err != nil {
|
| 267 |
+
return nil, err
|
| 268 |
+
}
|
| 269 |
+
parts = append(parts, part)
|
| 270 |
+
case finishType:
|
| 271 |
+
part := Finish{}
|
| 272 |
+
if err := json.Unmarshal(wrapper.Data, &part); err != nil {
|
| 273 |
+
return nil, err
|
| 274 |
+
}
|
| 275 |
+
parts = append(parts, part)
|
| 276 |
+
default:
|
| 277 |
+
return nil, fmt.Errorf("unknown part type: %s", wrapper.Type)
|
| 278 |
+
}
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
return parts, nil
|
| 282 |
+
}
|
projects/ui/crush/internal/permission/permission.go
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package permission
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"errors"
|
| 6 |
+
"os"
|
| 7 |
+
"path/filepath"
|
| 8 |
+
"slices"
|
| 9 |
+
"sync"
|
| 10 |
+
|
| 11 |
+
"github.com/charmbracelet/crush/internal/csync"
|
| 12 |
+
"github.com/charmbracelet/crush/internal/pubsub"
|
| 13 |
+
"github.com/google/uuid"
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
var ErrorPermissionDenied = errors.New("permission denied")
|
| 17 |
+
|
| 18 |
+
type CreatePermissionRequest struct {
|
| 19 |
+
SessionID string `json:"session_id"`
|
| 20 |
+
ToolCallID string `json:"tool_call_id"`
|
| 21 |
+
ToolName string `json:"tool_name"`
|
| 22 |
+
Description string `json:"description"`
|
| 23 |
+
Action string `json:"action"`
|
| 24 |
+
Params any `json:"params"`
|
| 25 |
+
Path string `json:"path"`
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
type PermissionNotification struct {
|
| 29 |
+
ToolCallID string `json:"tool_call_id"`
|
| 30 |
+
Granted bool `json:"granted"`
|
| 31 |
+
Denied bool `json:"denied"`
|
| 32 |
+
}
|
| 33 |
+
|
| 34 |
+
type PermissionRequest struct {
|
| 35 |
+
ID string `json:"id"`
|
| 36 |
+
SessionID string `json:"session_id"`
|
| 37 |
+
ToolCallID string `json:"tool_call_id"`
|
| 38 |
+
ToolName string `json:"tool_name"`
|
| 39 |
+
Description string `json:"description"`
|
| 40 |
+
Action string `json:"action"`
|
| 41 |
+
Params any `json:"params"`
|
| 42 |
+
Path string `json:"path"`
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
type Service interface {
|
| 46 |
+
pubsub.Suscriber[PermissionRequest]
|
| 47 |
+
GrantPersistent(permission PermissionRequest)
|
| 48 |
+
Grant(permission PermissionRequest)
|
| 49 |
+
Deny(permission PermissionRequest)
|
| 50 |
+
Request(opts CreatePermissionRequest) bool
|
| 51 |
+
AutoApproveSession(sessionID string)
|
| 52 |
+
SetSkipRequests(skip bool)
|
| 53 |
+
SkipRequests() bool
|
| 54 |
+
SubscribeNotifications(ctx context.Context) <-chan pubsub.Event[PermissionNotification]
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
type permissionService struct {
|
| 58 |
+
*pubsub.Broker[PermissionRequest]
|
| 59 |
+
|
| 60 |
+
notificationBroker *pubsub.Broker[PermissionNotification]
|
| 61 |
+
workingDir string
|
| 62 |
+
sessionPermissions []PermissionRequest
|
| 63 |
+
sessionPermissionsMu sync.RWMutex
|
| 64 |
+
pendingRequests *csync.Map[string, chan bool]
|
| 65 |
+
autoApproveSessions map[string]bool
|
| 66 |
+
autoApproveSessionsMu sync.RWMutex
|
| 67 |
+
skip bool
|
| 68 |
+
allowedTools []string
|
| 69 |
+
|
| 70 |
+
// used to make sure we only process one request at a time
|
| 71 |
+
requestMu sync.Mutex
|
| 72 |
+
activeRequest *PermissionRequest
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
func (s *permissionService) GrantPersistent(permission PermissionRequest) {
|
| 76 |
+
s.notificationBroker.Publish(pubsub.CreatedEvent, PermissionNotification{
|
| 77 |
+
ToolCallID: permission.ToolCallID,
|
| 78 |
+
Granted: true,
|
| 79 |
+
})
|
| 80 |
+
respCh, ok := s.pendingRequests.Get(permission.ID)
|
| 81 |
+
if ok {
|
| 82 |
+
respCh <- true
|
| 83 |
+
}
|
| 84 |
+
|
| 85 |
+
s.sessionPermissionsMu.Lock()
|
| 86 |
+
s.sessionPermissions = append(s.sessionPermissions, permission)
|
| 87 |
+
s.sessionPermissionsMu.Unlock()
|
| 88 |
+
|
| 89 |
+
if s.activeRequest != nil && s.activeRequest.ID == permission.ID {
|
| 90 |
+
s.activeRequest = nil
|
| 91 |
+
}
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
func (s *permissionService) Grant(permission PermissionRequest) {
|
| 95 |
+
s.notificationBroker.Publish(pubsub.CreatedEvent, PermissionNotification{
|
| 96 |
+
ToolCallID: permission.ToolCallID,
|
| 97 |
+
Granted: true,
|
| 98 |
+
})
|
| 99 |
+
respCh, ok := s.pendingRequests.Get(permission.ID)
|
| 100 |
+
if ok {
|
| 101 |
+
respCh <- true
|
| 102 |
+
}
|
| 103 |
+
|
| 104 |
+
if s.activeRequest != nil && s.activeRequest.ID == permission.ID {
|
| 105 |
+
s.activeRequest = nil
|
| 106 |
+
}
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
func (s *permissionService) Deny(permission PermissionRequest) {
|
| 110 |
+
s.notificationBroker.Publish(pubsub.CreatedEvent, PermissionNotification{
|
| 111 |
+
ToolCallID: permission.ToolCallID,
|
| 112 |
+
Granted: false,
|
| 113 |
+
Denied: true,
|
| 114 |
+
})
|
| 115 |
+
respCh, ok := s.pendingRequests.Get(permission.ID)
|
| 116 |
+
if ok {
|
| 117 |
+
respCh <- false
|
| 118 |
+
}
|
| 119 |
+
|
| 120 |
+
if s.activeRequest != nil && s.activeRequest.ID == permission.ID {
|
| 121 |
+
s.activeRequest = nil
|
| 122 |
+
}
|
| 123 |
+
}
|
| 124 |
+
|
| 125 |
+
func (s *permissionService) Request(opts CreatePermissionRequest) bool {
|
| 126 |
+
if s.skip {
|
| 127 |
+
return true
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
// tell the UI that a permission was requested
|
| 131 |
+
s.notificationBroker.Publish(pubsub.CreatedEvent, PermissionNotification{
|
| 132 |
+
ToolCallID: opts.ToolCallID,
|
| 133 |
+
})
|
| 134 |
+
s.requestMu.Lock()
|
| 135 |
+
defer s.requestMu.Unlock()
|
| 136 |
+
|
| 137 |
+
// Check if the tool/action combination is in the allowlist
|
| 138 |
+
commandKey := opts.ToolName + ":" + opts.Action
|
| 139 |
+
if slices.Contains(s.allowedTools, commandKey) || slices.Contains(s.allowedTools, opts.ToolName) {
|
| 140 |
+
return true
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
s.autoApproveSessionsMu.RLock()
|
| 144 |
+
autoApprove := s.autoApproveSessions[opts.SessionID]
|
| 145 |
+
s.autoApproveSessionsMu.RUnlock()
|
| 146 |
+
|
| 147 |
+
if autoApprove {
|
| 148 |
+
return true
|
| 149 |
+
}
|
| 150 |
+
|
| 151 |
+
fileInfo, err := os.Stat(opts.Path)
|
| 152 |
+
dir := opts.Path
|
| 153 |
+
if err == nil {
|
| 154 |
+
if fileInfo.IsDir() {
|
| 155 |
+
dir = opts.Path
|
| 156 |
+
} else {
|
| 157 |
+
dir = filepath.Dir(opts.Path)
|
| 158 |
+
}
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
if dir == "." {
|
| 162 |
+
dir = s.workingDir
|
| 163 |
+
}
|
| 164 |
+
permission := PermissionRequest{
|
| 165 |
+
ID: uuid.New().String(),
|
| 166 |
+
Path: dir,
|
| 167 |
+
SessionID: opts.SessionID,
|
| 168 |
+
ToolCallID: opts.ToolCallID,
|
| 169 |
+
ToolName: opts.ToolName,
|
| 170 |
+
Description: opts.Description,
|
| 171 |
+
Action: opts.Action,
|
| 172 |
+
Params: opts.Params,
|
| 173 |
+
}
|
| 174 |
+
|
| 175 |
+
s.sessionPermissionsMu.RLock()
|
| 176 |
+
for _, p := range s.sessionPermissions {
|
| 177 |
+
if p.ToolName == permission.ToolName && p.Action == permission.Action && p.SessionID == permission.SessionID && p.Path == permission.Path {
|
| 178 |
+
s.sessionPermissionsMu.RUnlock()
|
| 179 |
+
return true
|
| 180 |
+
}
|
| 181 |
+
}
|
| 182 |
+
s.sessionPermissionsMu.RUnlock()
|
| 183 |
+
|
| 184 |
+
s.sessionPermissionsMu.RLock()
|
| 185 |
+
for _, p := range s.sessionPermissions {
|
| 186 |
+
if p.ToolName == permission.ToolName && p.Action == permission.Action && p.SessionID == permission.SessionID && p.Path == permission.Path {
|
| 187 |
+
s.sessionPermissionsMu.RUnlock()
|
| 188 |
+
return true
|
| 189 |
+
}
|
| 190 |
+
}
|
| 191 |
+
s.sessionPermissionsMu.RUnlock()
|
| 192 |
+
|
| 193 |
+
s.activeRequest = &permission
|
| 194 |
+
|
| 195 |
+
respCh := make(chan bool, 1)
|
| 196 |
+
s.pendingRequests.Set(permission.ID, respCh)
|
| 197 |
+
defer s.pendingRequests.Del(permission.ID)
|
| 198 |
+
|
| 199 |
+
// Publish the request
|
| 200 |
+
s.Publish(pubsub.CreatedEvent, permission)
|
| 201 |
+
|
| 202 |
+
return <-respCh
|
| 203 |
+
}
|
| 204 |
+
|
| 205 |
+
func (s *permissionService) AutoApproveSession(sessionID string) {
|
| 206 |
+
s.autoApproveSessionsMu.Lock()
|
| 207 |
+
s.autoApproveSessions[sessionID] = true
|
| 208 |
+
s.autoApproveSessionsMu.Unlock()
|
| 209 |
+
}
|
| 210 |
+
|
| 211 |
+
func (s *permissionService) SubscribeNotifications(ctx context.Context) <-chan pubsub.Event[PermissionNotification] {
|
| 212 |
+
return s.notificationBroker.Subscribe(ctx)
|
| 213 |
+
}
|
| 214 |
+
|
| 215 |
+
func (s *permissionService) SetSkipRequests(skip bool) {
|
| 216 |
+
s.skip = skip
|
| 217 |
+
}
|
| 218 |
+
|
| 219 |
+
func (s *permissionService) SkipRequests() bool {
|
| 220 |
+
return s.skip
|
| 221 |
+
}
|
| 222 |
+
|
| 223 |
+
func NewPermissionService(workingDir string, skip bool, allowedTools []string) Service {
|
| 224 |
+
return &permissionService{
|
| 225 |
+
Broker: pubsub.NewBroker[PermissionRequest](),
|
| 226 |
+
notificationBroker: pubsub.NewBroker[PermissionNotification](),
|
| 227 |
+
workingDir: workingDir,
|
| 228 |
+
sessionPermissions: make([]PermissionRequest, 0),
|
| 229 |
+
autoApproveSessions: make(map[string]bool),
|
| 230 |
+
skip: skip,
|
| 231 |
+
allowedTools: allowedTools,
|
| 232 |
+
pendingRequests: csync.NewMap[string, chan bool](),
|
| 233 |
+
}
|
| 234 |
+
}
|
projects/ui/crush/internal/permission/permission_test.go
ADDED
|
@@ -0,0 +1,247 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package permission
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"sync"
|
| 5 |
+
"testing"
|
| 6 |
+
|
| 7 |
+
"github.com/stretchr/testify/assert"
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
+
func TestPermissionService_AllowedCommands(t *testing.T) {
|
| 11 |
+
tests := []struct {
|
| 12 |
+
name string
|
| 13 |
+
allowedTools []string
|
| 14 |
+
toolName string
|
| 15 |
+
action string
|
| 16 |
+
expected bool
|
| 17 |
+
}{
|
| 18 |
+
{
|
| 19 |
+
name: "tool in allowlist",
|
| 20 |
+
allowedTools: []string{"bash", "view"},
|
| 21 |
+
toolName: "bash",
|
| 22 |
+
action: "execute",
|
| 23 |
+
expected: true,
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
name: "tool:action in allowlist",
|
| 27 |
+
allowedTools: []string{"bash:execute", "edit:create"},
|
| 28 |
+
toolName: "bash",
|
| 29 |
+
action: "execute",
|
| 30 |
+
expected: true,
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
name: "tool not in allowlist",
|
| 34 |
+
allowedTools: []string{"view", "ls"},
|
| 35 |
+
toolName: "bash",
|
| 36 |
+
action: "execute",
|
| 37 |
+
expected: false,
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
name: "tool:action not in allowlist",
|
| 41 |
+
allowedTools: []string{"bash:read", "edit:create"},
|
| 42 |
+
toolName: "bash",
|
| 43 |
+
action: "execute",
|
| 44 |
+
expected: false,
|
| 45 |
+
},
|
| 46 |
+
{
|
| 47 |
+
name: "empty allowlist",
|
| 48 |
+
allowedTools: []string{},
|
| 49 |
+
toolName: "bash",
|
| 50 |
+
action: "execute",
|
| 51 |
+
expected: false,
|
| 52 |
+
},
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
for _, tt := range tests {
|
| 56 |
+
t.Run(tt.name, func(t *testing.T) {
|
| 57 |
+
service := NewPermissionService("/tmp", false, tt.allowedTools)
|
| 58 |
+
|
| 59 |
+
// Create a channel to capture the permission request
|
| 60 |
+
// Since we're testing the allowlist logic, we need to simulate the request
|
| 61 |
+
ps := service.(*permissionService)
|
| 62 |
+
|
| 63 |
+
// Test the allowlist logic directly
|
| 64 |
+
commandKey := tt.toolName + ":" + tt.action
|
| 65 |
+
allowed := false
|
| 66 |
+
for _, cmd := range ps.allowedTools {
|
| 67 |
+
if cmd == commandKey || cmd == tt.toolName {
|
| 68 |
+
allowed = true
|
| 69 |
+
break
|
| 70 |
+
}
|
| 71 |
+
}
|
| 72 |
+
|
| 73 |
+
if allowed != tt.expected {
|
| 74 |
+
t.Errorf("expected %v, got %v for tool %s action %s with allowlist %v",
|
| 75 |
+
tt.expected, allowed, tt.toolName, tt.action, tt.allowedTools)
|
| 76 |
+
}
|
| 77 |
+
})
|
| 78 |
+
}
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
func TestPermissionService_SkipMode(t *testing.T) {
|
| 82 |
+
service := NewPermissionService("/tmp", true, []string{})
|
| 83 |
+
|
| 84 |
+
result := service.Request(CreatePermissionRequest{
|
| 85 |
+
SessionID: "test-session",
|
| 86 |
+
ToolName: "bash",
|
| 87 |
+
Action: "execute",
|
| 88 |
+
Description: "test command",
|
| 89 |
+
Path: "/tmp",
|
| 90 |
+
})
|
| 91 |
+
|
| 92 |
+
if !result {
|
| 93 |
+
t.Error("expected permission to be granted in skip mode")
|
| 94 |
+
}
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
func TestPermissionService_SequentialProperties(t *testing.T) {
|
| 98 |
+
t.Run("Sequential permission requests with persistent grants", func(t *testing.T) {
|
| 99 |
+
service := NewPermissionService("/tmp", false, []string{})
|
| 100 |
+
|
| 101 |
+
req1 := CreatePermissionRequest{
|
| 102 |
+
SessionID: "session1",
|
| 103 |
+
ToolName: "file_tool",
|
| 104 |
+
Description: "Read file",
|
| 105 |
+
Action: "read",
|
| 106 |
+
Params: map[string]string{"file": "test.txt"},
|
| 107 |
+
Path: "/tmp/test.txt",
|
| 108 |
+
}
|
| 109 |
+
|
| 110 |
+
var result1 bool
|
| 111 |
+
var wg sync.WaitGroup
|
| 112 |
+
wg.Add(1)
|
| 113 |
+
|
| 114 |
+
events := service.Subscribe(t.Context())
|
| 115 |
+
|
| 116 |
+
go func() {
|
| 117 |
+
defer wg.Done()
|
| 118 |
+
result1 = service.Request(req1)
|
| 119 |
+
}()
|
| 120 |
+
|
| 121 |
+
var permissionReq PermissionRequest
|
| 122 |
+
event := <-events
|
| 123 |
+
|
| 124 |
+
permissionReq = event.Payload
|
| 125 |
+
service.GrantPersistent(permissionReq)
|
| 126 |
+
|
| 127 |
+
wg.Wait()
|
| 128 |
+
assert.True(t, result1, "First request should be granted")
|
| 129 |
+
|
| 130 |
+
// Second identical request should be automatically approved due to persistent permission
|
| 131 |
+
req2 := CreatePermissionRequest{
|
| 132 |
+
SessionID: "session1",
|
| 133 |
+
ToolName: "file_tool",
|
| 134 |
+
Description: "Read file again",
|
| 135 |
+
Action: "read",
|
| 136 |
+
Params: map[string]string{"file": "test.txt"},
|
| 137 |
+
Path: "/tmp/test.txt",
|
| 138 |
+
}
|
| 139 |
+
result2 := service.Request(req2)
|
| 140 |
+
assert.True(t, result2, "Second request should be auto-approved")
|
| 141 |
+
})
|
| 142 |
+
t.Run("Sequential requests with temporary grants", func(t *testing.T) {
|
| 143 |
+
service := NewPermissionService("/tmp", false, []string{})
|
| 144 |
+
|
| 145 |
+
req := CreatePermissionRequest{
|
| 146 |
+
SessionID: "session2",
|
| 147 |
+
ToolName: "file_tool",
|
| 148 |
+
Description: "Write file",
|
| 149 |
+
Action: "write",
|
| 150 |
+
Params: map[string]string{"file": "test.txt"},
|
| 151 |
+
Path: "/tmp/test.txt",
|
| 152 |
+
}
|
| 153 |
+
|
| 154 |
+
events := service.Subscribe(t.Context())
|
| 155 |
+
var result1 bool
|
| 156 |
+
var wg sync.WaitGroup
|
| 157 |
+
|
| 158 |
+
wg.Go(func() {
|
| 159 |
+
result1 = service.Request(req)
|
| 160 |
+
})
|
| 161 |
+
|
| 162 |
+
var permissionReq PermissionRequest
|
| 163 |
+
event := <-events
|
| 164 |
+
permissionReq = event.Payload
|
| 165 |
+
|
| 166 |
+
service.Grant(permissionReq)
|
| 167 |
+
wg.Wait()
|
| 168 |
+
assert.True(t, result1, "First request should be granted")
|
| 169 |
+
|
| 170 |
+
var result2 bool
|
| 171 |
+
|
| 172 |
+
wg.Go(func() {
|
| 173 |
+
result2 = service.Request(req)
|
| 174 |
+
})
|
| 175 |
+
|
| 176 |
+
event = <-events
|
| 177 |
+
permissionReq = event.Payload
|
| 178 |
+
service.Deny(permissionReq)
|
| 179 |
+
wg.Wait()
|
| 180 |
+
assert.False(t, result2, "Second request should be denied")
|
| 181 |
+
})
|
| 182 |
+
t.Run("Concurrent requests with different outcomes", func(t *testing.T) {
|
| 183 |
+
service := NewPermissionService("/tmp", false, []string{})
|
| 184 |
+
|
| 185 |
+
events := service.Subscribe(t.Context())
|
| 186 |
+
|
| 187 |
+
var wg sync.WaitGroup
|
| 188 |
+
results := make([]bool, 0)
|
| 189 |
+
|
| 190 |
+
requests := []CreatePermissionRequest{
|
| 191 |
+
{
|
| 192 |
+
SessionID: "concurrent1",
|
| 193 |
+
ToolName: "tool1",
|
| 194 |
+
Action: "action1",
|
| 195 |
+
Path: "/tmp/file1.txt",
|
| 196 |
+
Description: "First concurrent request",
|
| 197 |
+
},
|
| 198 |
+
{
|
| 199 |
+
SessionID: "concurrent2",
|
| 200 |
+
ToolName: "tool2",
|
| 201 |
+
Action: "action2",
|
| 202 |
+
Path: "/tmp/file2.txt",
|
| 203 |
+
Description: "Second concurrent request",
|
| 204 |
+
},
|
| 205 |
+
{
|
| 206 |
+
SessionID: "concurrent3",
|
| 207 |
+
ToolName: "tool3",
|
| 208 |
+
Action: "action3",
|
| 209 |
+
Path: "/tmp/file3.txt",
|
| 210 |
+
Description: "Third concurrent request",
|
| 211 |
+
},
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
for i, req := range requests {
|
| 215 |
+
wg.Add(1)
|
| 216 |
+
go func(index int, request CreatePermissionRequest) {
|
| 217 |
+
defer wg.Done()
|
| 218 |
+
results = append(results, service.Request(request))
|
| 219 |
+
}(i, req)
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
for range 3 {
|
| 223 |
+
event := <-events
|
| 224 |
+
switch event.Payload.ToolName {
|
| 225 |
+
case "tool1":
|
| 226 |
+
service.Grant(event.Payload)
|
| 227 |
+
case "tool2":
|
| 228 |
+
service.GrantPersistent(event.Payload)
|
| 229 |
+
case "tool3":
|
| 230 |
+
service.Deny(event.Payload)
|
| 231 |
+
}
|
| 232 |
+
}
|
| 233 |
+
wg.Wait()
|
| 234 |
+
grantedCount := 0
|
| 235 |
+
for _, result := range results {
|
| 236 |
+
if result {
|
| 237 |
+
grantedCount++
|
| 238 |
+
}
|
| 239 |
+
}
|
| 240 |
+
|
| 241 |
+
assert.Equal(t, 2, grantedCount, "Should have 2 granted and 1 denied")
|
| 242 |
+
secondReq := requests[1]
|
| 243 |
+
secondReq.Description = "Repeat of second request"
|
| 244 |
+
result := service.Request(secondReq)
|
| 245 |
+
assert.True(t, result, "Repeated request should be auto-approved due to persistent permission")
|
| 246 |
+
})
|
| 247 |
+
}
|
projects/ui/crush/internal/pubsub/broker.go
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package pubsub
|
| 2 |
+
|
| 3 |
+
import (
|
| 4 |
+
"context"
|
| 5 |
+
"sync"
|
| 6 |
+
)
|
| 7 |
+
|
| 8 |
+
const bufferSize = 64
|
| 9 |
+
|
| 10 |
+
type Broker[T any] struct {
|
| 11 |
+
subs map[chan Event[T]]struct{}
|
| 12 |
+
mu sync.RWMutex
|
| 13 |
+
done chan struct{}
|
| 14 |
+
subCount int
|
| 15 |
+
maxEvents int
|
| 16 |
+
}
|
| 17 |
+
|
| 18 |
+
func NewBroker[T any]() *Broker[T] {
|
| 19 |
+
return NewBrokerWithOptions[T](bufferSize, 1000)
|
| 20 |
+
}
|
| 21 |
+
|
| 22 |
+
func NewBrokerWithOptions[T any](channelBufferSize, maxEvents int) *Broker[T] {
|
| 23 |
+
b := &Broker[T]{
|
| 24 |
+
subs: make(map[chan Event[T]]struct{}),
|
| 25 |
+
done: make(chan struct{}),
|
| 26 |
+
subCount: 0,
|
| 27 |
+
maxEvents: maxEvents,
|
| 28 |
+
}
|
| 29 |
+
return b
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
func (b *Broker[T]) Shutdown() {
|
| 33 |
+
select {
|
| 34 |
+
case <-b.done: // Already closed
|
| 35 |
+
return
|
| 36 |
+
default:
|
| 37 |
+
close(b.done)
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
b.mu.Lock()
|
| 41 |
+
defer b.mu.Unlock()
|
| 42 |
+
|
| 43 |
+
for ch := range b.subs {
|
| 44 |
+
delete(b.subs, ch)
|
| 45 |
+
close(ch)
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
b.subCount = 0
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
func (b *Broker[T]) Subscribe(ctx context.Context) <-chan Event[T] {
|
| 52 |
+
b.mu.Lock()
|
| 53 |
+
defer b.mu.Unlock()
|
| 54 |
+
|
| 55 |
+
select {
|
| 56 |
+
case <-b.done:
|
| 57 |
+
ch := make(chan Event[T])
|
| 58 |
+
close(ch)
|
| 59 |
+
return ch
|
| 60 |
+
default:
|
| 61 |
+
}
|
| 62 |
+
|
| 63 |
+
sub := make(chan Event[T], bufferSize)
|
| 64 |
+
b.subs[sub] = struct{}{}
|
| 65 |
+
b.subCount++
|
| 66 |
+
|
| 67 |
+
go func() {
|
| 68 |
+
<-ctx.Done()
|
| 69 |
+
|
| 70 |
+
b.mu.Lock()
|
| 71 |
+
defer b.mu.Unlock()
|
| 72 |
+
|
| 73 |
+
select {
|
| 74 |
+
case <-b.done:
|
| 75 |
+
return
|
| 76 |
+
default:
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
delete(b.subs, sub)
|
| 80 |
+
close(sub)
|
| 81 |
+
b.subCount--
|
| 82 |
+
}()
|
| 83 |
+
|
| 84 |
+
return sub
|
| 85 |
+
}
|
| 86 |
+
|
| 87 |
+
func (b *Broker[T]) GetSubscriberCount() int {
|
| 88 |
+
b.mu.RLock()
|
| 89 |
+
defer b.mu.RUnlock()
|
| 90 |
+
return b.subCount
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
func (b *Broker[T]) Publish(t EventType, payload T) {
|
| 94 |
+
b.mu.RLock()
|
| 95 |
+
select {
|
| 96 |
+
case <-b.done:
|
| 97 |
+
b.mu.RUnlock()
|
| 98 |
+
return
|
| 99 |
+
default:
|
| 100 |
+
}
|
| 101 |
+
|
| 102 |
+
subscribers := make([]chan Event[T], 0, len(b.subs))
|
| 103 |
+
for sub := range b.subs {
|
| 104 |
+
subscribers = append(subscribers, sub)
|
| 105 |
+
}
|
| 106 |
+
b.mu.RUnlock()
|
| 107 |
+
|
| 108 |
+
event := Event[T]{Type: t, Payload: payload}
|
| 109 |
+
|
| 110 |
+
for _, sub := range subscribers {
|
| 111 |
+
select {
|
| 112 |
+
case sub <- event:
|
| 113 |
+
default:
|
| 114 |
+
// Channel is full, subscriber is slow - skip this event
|
| 115 |
+
// This prevents blocking the publisher
|
| 116 |
+
}
|
| 117 |
+
}
|
| 118 |
+
}
|
projects/ui/crush/internal/pubsub/events.go
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
package pubsub
|
| 2 |
+
|
| 3 |
+
import "context"
|
| 4 |
+
|
| 5 |
+
const (
|
| 6 |
+
CreatedEvent EventType = "created"
|
| 7 |
+
UpdatedEvent EventType = "updated"
|
| 8 |
+
DeletedEvent EventType = "deleted"
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
type Suscriber[T any] interface {
|
| 12 |
+
Subscribe(context.Context) <-chan Event[T]
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
type (
|
| 16 |
+
// EventType identifies the type of event
|
| 17 |
+
EventType string
|
| 18 |
+
|
| 19 |
+
// Event represents an event in the lifecycle of a resource
|
| 20 |
+
Event[T any] struct {
|
| 21 |
+
Type EventType
|
| 22 |
+
Payload T
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
Publisher[T any] interface {
|
| 26 |
+
Publish(EventType, T)
|
| 27 |
+
}
|
| 28 |
+
)
|