xonecas.io
62159
Sy

symb / commit 252d5a7

feat: lsp integration, works in go, who knows about other filetypes

xonecas2026-02-14 252d5a7b10a77defdadecbbfdd15a078b9311a22 parent 5851908

16 files changed

This diff is too big to show in full. The first 1000 lines are below, and every file is listed with its counts.

.gitignore+3−0
@@ -39,3 +39,6 @@ config.local.toml
3939 # Debug files
4040 debug
4141 __debug_bin
42+
43+# LSP test files
44+bad.go
AGENTS.md+0−1
@@ -11,7 +11,6 @@
1111
1212 ## Project info
1313
14-- Always use `docs/TUI_TESTING.md` when working on the TUI. Use golden tests.
1514 - Always use [ELM](https://guide.elm-lang.org/architecture/) architecture.
1615 - Go & Golintci
1716 - [Bubbletea, Bubbles](https://github.com/charmbracelet/bubbletea)
cmd/symb/main.go+12−2
@@ -11,6 +11,7 @@ import (
1111 "github.com/rs/zerolog"
1212 "github.com/rs/zerolog/log"
1313 "github.com/xonecas/symb/internal/config"
14+ "github.com/xonecas/symb/internal/lsp"
1415 "github.com/xonecas/symb/internal/mcp"
1516 "github.com/xonecas/symb/internal/mcp_tools"
1617 "github.com/xonecas/symb/internal/provider"
@@ -92,11 +93,15 @@ func main() {
9293 }
9394 defer proxy.Close()
9495
96+ // Create LSP manager
97+ lspManager := lsp.NewManager()
98+ defer lspManager.StopAll(context.Background())
99+
95100 // Register local tools
96101 fileTracker := mcp_tools.NewFileReadTracker()
97102
98103 openForUserTool := mcp_tools.NewOpenForUserTool()
99- openForUserHandler := mcp_tools.NewOpenForUserHandler(fileTracker)
104+ openForUserHandler := mcp_tools.NewOpenForUserHandler(fileTracker, lspManager)
100105 proxy.RegisterTool(openForUserTool, openForUserHandler.Handle)
101106
102107 grepTool := mcp_tools.NewGrepTool()
@@ -104,7 +109,7 @@ func main() {
104109 proxy.RegisterTool(grepTool, grepHandler)
105110
106111 editTool := mcp_tools.NewEditTool()
107- editHandler := mcp_tools.NewEditHandler(fileTracker)
112+ editHandler := mcp_tools.NewEditHandler(fileTracker, lspManager)
108113 proxy.RegisterTool(editTool, editHandler.Handle)
109114
110115 // Open web cache (SQLite-backed, persisted across sessions).
@@ -157,6 +162,11 @@ func main() {
157162 openForUserHandler.SetProgram(p)
158163 editHandler.SetProgram(p)
159164
165+ // Wire LSP diagnostics callback to TUI
166+ lspManager.SetCallback(func(absPath string, lines map[int]int) {
167+ p.Send(tui.LSPDiagnosticsMsg{FilePath: absPath, Lines: lines})
168+ })
169+
160170 // Run the program
161171 if _, err := p.Run(); err != nil {
162172 fmt.Printf("Error running symb: %v\n", err)
docs/DESIGN.md+4−1
@@ -120,7 +120,8 @@ Left:
120120 Right (right aligned text)
121121
122122 - Network errors to providers (llm, and exa_search), truncated.
123- - Animated icon becomes red until next successful request.
123+ - NOTE: Animated icon becomes red until next successful request.
124+- Current llm provider config name
124125 - Show name and version
125126 - Animated icon.
126127
@@ -185,6 +186,8 @@ LLM input (in the spirit of the app, symbiotic):
185186
186187 ### Tests
187188
189+Logs should be in app data home dir, not in .local
190+
188191 29 tests, all passing. Coverage: hashline 96.7%, filesearch 76%,
189192 mcp_tools 43.2%, tui/editor 42.1%, tui 41.9%.
190193
go.mod+3−0
@@ -10,6 +10,7 @@ require (
1010 github.com/alecthomas/chroma/v2 v2.23.1
1111 github.com/charmbracelet/x/ansi v0.11.6
1212 github.com/charmbracelet/x/exp/golden v0.0.0-20260209194814-eeb2896ac759
13+ github.com/charmbracelet/x/powernap v0.0.0-20260209132835-6b065b8ba62c
1314 github.com/rs/zerolog v1.34.0
1415 github.com/sashabaranov/go-openai v1.41.2
1516 golang.org/x/net v0.50.0
@@ -33,10 +34,12 @@ require (
3334 github.com/mattn/go-colorable v0.1.13 // indirect
3435 github.com/mattn/go-isatty v0.0.20 // indirect
3536 github.com/mattn/go-runewidth v0.0.19 // indirect
37+ github.com/mitchellh/mapstructure v1.5.0 // indirect
3638 github.com/muesli/cancelreader v0.2.2 // indirect
3739 github.com/ncruces/go-strftime v1.0.0 // indirect
3840 github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
3941 github.com/rivo/uniseg v0.4.7 // indirect
42+ github.com/sourcegraph/jsonrpc2 v0.2.1 // indirect
4043 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
4144 golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 // indirect
4245 golang.org/x/sync v0.19.0 // indirect
go.sum+8−0
@@ -22,6 +22,8 @@ github.com/charmbracelet/x/ansi v0.11.6 h1:GhV21SiDz/45W9AnV2R61xZMRri5NlLnl6CVF
2222 github.com/charmbracelet/x/ansi v0.11.6/go.mod h1:2JNYLgQUsyqaiLovhU2Rv/pb8r6ydXKS3NIttu3VGZQ=
2323 github.com/charmbracelet/x/exp/golden v0.0.0-20260209194814-eeb2896ac759 h1:wQKrpioYyZbkqq2V5o9x7D2dDnqZeTgFshM7G2/vmu0=
2424 github.com/charmbracelet/x/exp/golden v0.0.0-20260209194814-eeb2896ac759/go.mod h1:V8n/g3qVKNxr2FR37Y+otCsMySvZr601T0C7coEP0bw=
25+github.com/charmbracelet/x/powernap v0.0.0-20260209132835-6b065b8ba62c h1:6E+Y7WQ6Rnw+FmeXoRBtyCBkPcXS0hSMuws6QBr+nyQ=
26+github.com/charmbracelet/x/powernap v0.0.0-20260209132835-6b065b8ba62c/go.mod h1:cmdl5zlP5mR8TF2Y68UKc7hdGUDiSJ2+4hk0h04Hsx4=
2527 github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
2628 github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
2729 github.com/charmbracelet/x/termios v0.1.1 h1:o3Q2bT8eqzGnGPOYheoYS8eEleT5ZVNYNy8JawjaNZY=
@@ -44,6 +46,8 @@ github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17k
4446 github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
4547 github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
4648 github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
49+github.com/gorilla/websocket v1.4.1 h1:q7AeDBpnBk8AogcD4DSag/Ukw/KV+YhzLj2bP5HvKCM=
50+github.com/gorilla/websocket v1.4.1/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
4751 github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
4852 github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
4953 github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM=
@@ -58,6 +62,8 @@ github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWE
5862 github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
5963 github.com/mattn/go-runewidth v0.0.19 h1:v++JhqYnZuu5jSKrk9RbgF5v4CGUjqRfBm05byFGLdw=
6064 github.com/mattn/go-runewidth v0.0.19/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
65+github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
66+github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
6167 github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELUXHmA=
6268 github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo=
6369 github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
@@ -72,6 +78,8 @@ github.com/rs/zerolog v1.34.0 h1:k43nTLIwcTVQAncfCw4KZ2VY6ukYoZaBPNOE8txlOeY=
7278 github.com/rs/zerolog v1.34.0/go.mod h1:bJsvje4Z08ROH4Nhs5iH600c3IkWhwp44iRc54W6wYQ=
7379 github.com/sashabaranov/go-openai v1.41.2 h1:vfPRBZNMpnqu8ELsclWcAvF19lDNgh1t6TVfFFOPiSM=
7480 github.com/sashabaranov/go-openai v1.41.2/go.mod h1:lj5b/K+zjTSFxVLijLSTDZuP7adOgerWeFyZLUhAKRg=
81+github.com/sourcegraph/jsonrpc2 v0.2.1 h1:2GtljixMQYUYCmIg7W9aF2dFmniq/mOr2T9tFRh6zSQ=
82+github.com/sourcegraph/jsonrpc2 v0.2.1/go.mod h1:ZafdZgk/axhT1cvZAPOhw+95nz2I/Ra5qMlU4gTRwIo=
7583 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavMF/ppJZNG9ZpyihvCd0w101no=
7684 github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
7785 golang.org/x/exp v0.0.0-20251023183803-a4bb9ffd2546 h1:mgKeJMpvi0yx/sU5GsxQ7p6s2wtOnGAHZWCHUM4KGzY=
internal/lsp/client.go+214−0
@@ -0,0 +1,214 @@
1+// Package lsp wraps powernap to provide LSP diagnostics for file mutations.
2+package lsp
3+
4+import (
5+ "context"
6+ "encoding/json"
7+ "fmt"
8+ "os"
9+ "sync"
10+ "time"
11+
12+ powernap "github.com/charmbracelet/x/powernap/pkg/lsp"
13+ "github.com/charmbracelet/x/powernap/pkg/lsp/protocol"
14+ "github.com/rs/zerolog/log"
15+)
16+
17+// Severity constants matching LSP DiagnosticSeverity.
18+const (
19+ SeverityError = 1
20+ SeverityWarning = 2
21+)
22+
23+// Client wraps a powernap LSP client with diagnostics tracking.
24+type Client struct {
25+ inner *powernap.Client
26+ serverID string
27+
28+ mu sync.Mutex
29+ diags map[string][]protocol.Diagnostic // uri -> diagnostics
30+ versions map[string]int // uri -> document version
31+ diagChanged chan struct{} // signaled on publishDiagnostics
32+}
33+
34+// newClient spawns an LSP server and returns a wrapped client.
35+func newClient(serverID string, cfg powernap.ClientConfig) (*Client, error) {
36+ inner, err := powernap.NewClient(cfg)
37+ if err != nil {
38+ return nil, fmt.Errorf("lsp: start %s: %w", serverID, err)
39+ }
40+
41+ c := &Client{
42+ inner: inner,
43+ serverID: serverID,
44+ diags: make(map[string][]protocol.Diagnostic),
45+ versions: make(map[string]int),
46+ diagChanged: make(chan struct{}, 1),
47+ }
48+
49+ // Register publishDiagnostics handler before Initialize.
50+ inner.RegisterNotificationHandler(
51+ "textDocument/publishDiagnostics",
52+ func(_ context.Context, _ string, params json.RawMessage) {
53+ var p protocol.PublishDiagnosticsParams
54+ if err := json.Unmarshal(params, &p); err != nil {
55+ log.Error().Err(err).Msg("lsp: unmarshal diagnostics")
56+ return
57+ }
58+ c.mu.Lock()
59+ c.diags[string(p.URI)] = p.Diagnostics
60+ c.mu.Unlock()
61+
62+ // Non-blocking signal.
63+ select {
64+ case c.diagChanged <- struct{}{}:
65+ default:
66+ }
67+ },
68+ )
69+
70+ // Stub handlers so the server doesn't error on common requests.
71+ inner.RegisterHandler("window/workDoneProgress/create",
72+ func(_ context.Context, _ string, _ json.RawMessage) (any, error) {
73+ return nil, nil
74+ },
75+ )
76+ inner.RegisterNotificationHandler("$/progress",
77+ func(_ context.Context, _ string, _ json.RawMessage) {},
78+ )
79+ inner.RegisterNotificationHandler("window/logMessage",
80+ func(_ context.Context, _ string, _ json.RawMessage) {},
81+ )
82+ inner.RegisterHandler("client/registerCapability",
83+ func(_ context.Context, _ string, _ json.RawMessage) (any, error) {
84+ return nil, nil
85+ },
86+ )
87+
88+ return c, nil
89+}
90+
91+// initialize sends initialize+initialized to the server.
92+func (c *Client) initialize(ctx context.Context) error {
93+ return c.inner.Initialize(ctx, false)
94+}
95+
96+// openFile reads a file from disk and sends textDocument/didOpen.
97+// If already open, sends didChange instead.
98+func (c *Client) openFile(ctx context.Context, absPath string) error {
99+ uri := string(protocol.URIFromPath(absPath))
100+
101+ c.mu.Lock()
102+ _, alreadyOpen := c.versions[uri]
103+ c.mu.Unlock()
104+ if alreadyOpen {
105+ return c.notifyChange(ctx, absPath)
106+ }
107+
108+ data, err := os.ReadFile(absPath)
109+ if err != nil {
110+ return fmt.Errorf("lsp: read %s: %w", absPath, err)
111+ }
112+
113+ lang := powernap.DetectLanguage(absPath)
114+
115+ c.mu.Lock()
116+ c.versions[uri] = 0
117+ c.mu.Unlock()
118+
119+ return c.inner.NotifyDidOpenTextDocument(ctx, uri, string(lang), 0, string(data))
120+}
121+
122+// notifyChange reads a file from disk and sends textDocument/didChange.
123+func (c *Client) notifyChange(ctx context.Context, absPath string) error {
124+ uri := string(protocol.URIFromPath(absPath))
125+
126+ data, err := os.ReadFile(absPath)
127+ if err != nil {
128+ return fmt.Errorf("lsp: read %s: %w", absPath, err)
129+ }
130+
131+ c.mu.Lock()
132+ v := c.versions[uri] + 1
133+ c.versions[uri] = v
134+ c.mu.Unlock()
135+
136+ change := protocol.TextDocumentContentChangeEvent{
137+ Value: protocol.TextDocumentContentChangeWholeDocument{
138+ Text: string(data),
139+ },
140+ }
141+ return c.inner.NotifyDidChangeTextDocument(ctx, uri, v, []protocol.TextDocumentContentChangeEvent{change})
142+}
143+
144+// waitForDiagnostics blocks until diagnostics arrive or timeout expires.
145+func (c *Client) waitForDiagnostics(ctx context.Context, absPath string, timeout time.Duration) []protocol.Diagnostic {
146+ uri := string(protocol.URIFromPath(absPath))
147+ deadline := time.After(timeout)
148+
149+ const debounce = 150 * time.Millisecond
150+ var timer *time.Timer
151+
152+ for {
153+ select {
154+ case <-c.diagChanged:
155+ if timer != nil {
156+ timer.Stop()
157+ }
158+ timer = time.NewTimer(debounce)
159+ case <-timerChan(timer):
160+ c.mu.Lock()
161+ d := c.diags[uri]
162+ c.mu.Unlock()
163+ return d
164+ case <-deadline:
165+ c.mu.Lock()
166+ d := c.diags[uri]
167+ c.mu.Unlock()
168+ return d
169+ case <-ctx.Done():
170+ c.mu.Lock()
171+ d := c.diags[uri]
172+ c.mu.Unlock()
173+ return d
174+ }
175+ }
176+}
177+
178+// close gracefully shuts down the LSP server.
179+func (c *Client) close(ctx context.Context) error {
180+ if err := c.inner.Shutdown(ctx); err != nil {
181+ c.inner.Kill()
182+ return fmt.Errorf("lsp: shutdown %s: %w", c.serverID, err)
183+ }
184+ return c.inner.Exit()
185+}
186+
187+// drainDiagChan drains stale signals before waiting.
188+func (c *Client) drainDiagChan() {
189+ for {
190+ select {
191+ case <-c.diagChanged:
192+ default:
193+ return
194+ }
195+ }
196+}
197+
198+// notifyAndWait opens (or re-notifies) the file and waits for diagnostics.
199+// Uses openFile which handles both didOpen (first time) and didChange (subsequent).
200+func (c *Client) notifyAndWait(ctx context.Context, absPath string, timeout time.Duration) ([]protocol.Diagnostic, error) {
201+ c.drainDiagChan()
202+ if err := c.openFile(ctx, absPath); err != nil {
203+ return nil, err
204+ }
205+ return c.waitForDiagnostics(ctx, absPath, timeout), nil
206+}
207+
208+// timerChan returns the timer's channel, or a nil channel if timer is nil.
209+func timerChan(t *time.Timer) <-chan time.Time {
210+ if t != nil {
211+ return t.C
212+ }
213+ return nil
214+}
internal/lsp/manager.go+367−0
@@ -0,0 +1,367 @@
1+package lsp
2+
3+import (
4+ "context"
5+ "fmt"
6+ "io"
7+ "log/slog"
8+ "os"
9+ "os/exec"
10+ "path/filepath"
11+ "sync"
12+ "time"
13+
14+ powernapconfig "github.com/charmbracelet/x/powernap/pkg/config"
15+ powernap "github.com/charmbracelet/x/powernap/pkg/lsp"
16+ "github.com/charmbracelet/x/powernap/pkg/lsp/protocol"
17+ "github.com/rs/zerolog/log"
18+)
19+
20+// skipAutoStart lists generic commands that should not be auto-started.
21+// These interpreters/runners may trigger package downloads or run wrong binaries.
22+var skipAutoStart = map[string]bool{
23+ "npx": true,
24+ "node": true,
25+ "python": true,
26+ "python3": true,
27+ "java": true,
28+ "ruby": true,
29+ "perl": true,
30+ "dotnet": true,
31+ "bun": true,
32+}
33+
34+// DiagCallback is called when diagnostics change for a file.
35+// absPath is the filesystem path; lines maps 0-indexed line numbers to max severity.
36+type DiagCallback func(absPath string, lines map[int]int)
37+
38+// Manager manages LSP server lifecycles keyed by server name.
39+type Manager struct {
40+ cfgMgr *powernapconfig.Manager
41+
42+ mu sync.Mutex
43+ clients map[string]*Client // serverName -> client
44+ broken map[string]bool // servers that failed to start
45+
46+ callback DiagCallback
47+}
48+
49+// NewManager creates a manager with powernap's built-in server defaults.
50+func NewManager() *Manager {
51+ // Silence powernap's slog output — it writes to stderr which the TUI owns.
52+ slog.SetDefault(slog.New(slog.NewTextHandler(io.Discard, nil)))
53+
54+ cm := powernapconfig.NewManager()
55+ _ = cm.LoadDefaults()
56+ return &Manager{
57+ cfgMgr: cm,
58+ clients: make(map[string]*Client),
59+ broken: make(map[string]bool),
60+ }
61+}
62+
63+// SetCallback sets the function called when diagnostics change.
64+func (m *Manager) SetCallback(cb DiagCallback) {
65+ m.mu.Lock()
66+ defer m.mu.Unlock()
67+ m.callback = cb
68+}
69+
70+// TouchFile ensures the right LSP servers are running for this file and
71+// sends didOpen/didChange. Non-blocking — errors are logged, not returned.
72+func (m *Manager) TouchFile(ctx context.Context, absPath string) {
73+ clients := m.ensureClients(ctx, absPath)
74+ for _, c := range clients {
75+ if err := c.openFile(ctx, absPath); err != nil {
76+ log.Error().Err(err).Str("server", c.serverID).Msg("lsp: touchFile openFile")
77+ }
78+ }
79+}
80+
81+// NotifyAndWait notifies relevant LSP servers of a file change and waits for
82+// diagnostics. Returns aggregated diagnostics across all matching servers.
83+func (m *Manager) NotifyAndWait(ctx context.Context, absPath string, timeout time.Duration) []protocol.Diagnostic {
84+ clients := m.ensureClients(ctx, absPath)
85+ if len(clients) == 0 {
86+ return nil
87+ }
88+
89+ var all []protocol.Diagnostic
90+ for _, c := range clients {
91+ diags, err := c.notifyAndWait(ctx, absPath, timeout)
92+ if err != nil {
93+ log.Error().Err(err).Str("server", c.serverID).Msg("lsp: notifyAndWait")
94+ continue
95+ }
96+ log.Debug().Str("server", c.serverID).Int("count", len(diags)).Str("file", absPath).Msg("lsp: diagnostics received")
97+ all = append(all, diags...)
98+ }
99+
100+ log.Debug().Int("total", len(all)).Str("file", absPath).Msg("lsp: aggregated diagnostics")
101+
102+ // Fire callback once with aggregated diagnostics from all servers.
103+ m.mu.Lock()
104+ cb := m.callback
105+ m.mu.Unlock()
106+ if cb != nil {
107+ cb(absPath, diagLineSeverities(all))
108+ }
109+
110+ return all
111+}
112+
113+// StopAll gracefully shuts down all running LSP servers.
114+func (m *Manager) StopAll(ctx context.Context) {
115+ m.mu.Lock()
116+ clients := make([]*Client, 0, len(m.clients))
117+ for _, c := range m.clients {
118+ clients = append(clients, c)
119+ }
120+ m.mu.Unlock()
121+
122+ for _, c := range clients {
123+ if err := c.close(ctx); err != nil {
124+ log.Error().Err(err).Str("server", c.serverID).Msg("lsp: stopAll")
125+ }
126+ }
127+}
128+
129+// serverToStart holds info needed to start an LSP server outside the lock.
130+type serverToStart struct {
131+ name string
132+ cfg *powernapconfig.ServerConfig
133+ root string
134+ cmdPath string
135+}
136+
137+// ensureClients finds or starts LSP servers for the given file.
138+func (m *Manager) ensureClients(ctx context.Context, absPath string) []*Client {
139+ lang := string(powernap.DetectLanguage(absPath))
140+ if lang == "" {
141+ log.Debug().Str("file", absPath).Msg("lsp: unknown language, skipping")
142+ return nil
143+ }
144+
145+ log.Debug().Str("file", absPath).Str("lang", lang).Msg("lsp: ensureClients")
146+
147+ servers := m.cfgMgr.GetServers()
148+
149+ // Phase 1: under lock, collect existing clients and identify servers to start.
150+ m.mu.Lock()
151+ var result []*Client
152+ var pending []serverToStart
153+
154+ for name, cfg := range servers {
155+ if !matchesFileType(cfg, lang) {
156+ continue
157+ }
158+ if m.broken[name] {
159+ continue
160+ }
161+ if c, ok := m.clients[name]; ok {
162+ result = append(result, c)
163+ continue
164+ }
165+ if skipAutoStart[cfg.Command] {
166+ m.broken[name] = true
167+ continue
168+ }
169+ cmdPath := lookPath(cfg.Command)
170+ if cmdPath == "" {
171+ m.broken[name] = true
172+ continue
173+ }
174+ root := findRoot(absPath, cfg.RootMarkers)
175+ if root == "" {
176+ root, _ = os.Getwd()
177+ }
178+ pending = append(pending, serverToStart{name: name, cfg: cfg, root: root, cmdPath: cmdPath})
179+ }
180+ m.mu.Unlock()
181+
182+ // Phase 2: start servers without holding the lock (blocking I/O).
183+ for _, s := range pending {
184+ c, err := m.startClient(ctx, s.name, s.cfg, s.root, s.cmdPath)
185+
186+ m.mu.Lock()
187+ if err != nil {
188+ log.Error().Err(err).Str("server", s.name).Msg("lsp: start failed")
189+ m.broken[s.name] = true
190+ } else {
191+ m.clients[s.name] = c
192+ result = append(result, c)
193+ }
194+ m.mu.Unlock()
195+ }
196+
197+ return result
198+}
199+
200+// startClient spawns and initializes a single LSP server. Must be called with m.mu held.
201+func (m *Manager) startClient(ctx context.Context, name string, cfg *powernapconfig.ServerConfig, root, cmdPath string) (*Client, error) {
202+ rootURI := string(protocol.URIFromPath(root))
203+
204+ pcfg := powernap.ClientConfig{
205+ Command: cmdPath,
206+ Args: cfg.Args,
207+ RootURI: rootURI,
208+ Environment: cfg.Environment,
209+ Settings: cfg.Settings,
210+ InitOptions: cfg.InitOptions,
211+ WorkspaceFolders: []protocol.WorkspaceFolder{
212+ {URI: rootURI, Name: filepath.Base(root)},
213+ },
214+ }
215+
216+ c, err := newClient(name, pcfg)
217+ if err != nil {
218+ return nil, err
219+ }
220+
221+ initCtx, cancel := context.WithTimeout(ctx, 15*time.Second)
222+ defer cancel()
223+
224+ if err := c.initialize(initCtx); err != nil {
225+ _ = c.close(ctx)
226+ return nil, fmt.Errorf("initialize: %w", err)
227+ }
228+
229+ log.Info().Str("server", name).Str("root", root).Str("cmd", cmdPath).Msg("lsp: server started")
230+ return c, nil
231+}
232+
233+// matchesFileType checks if a server config handles the given language ID.
234+func matchesFileType(cfg *powernapconfig.ServerConfig, lang string) bool {
235+ for _, ft := range cfg.FileTypes {
236+ if ft == lang {
237+ return true
238+ }
239+ }
240+ return false
241+}
242+
243+// findRoot walks up from the file looking for any of the root markers.
244+func findRoot(absPath string, markers []string) string {
245+ dir := filepath.Dir(absPath)
246+ for {
247+ for _, marker := range markers {
248+ matches, _ := filepath.Glob(filepath.Join(dir, marker))
249+ if len(matches) > 0 {
250+ return dir
251+ }
252+ }
253+ parent := filepath.Dir(dir)
254+ if parent == dir {
255+ return ""
256+ }
257+ dir = parent
258+ }
259+}
260+
261+// diagLineSeverities converts a diagnostic slice to a line->severity map.
262+// Only tracks errors (1) and warnings (2). Lower severity number wins.
263+func diagLineSeverities(diags []protocol.Diagnostic) map[int]int {
264+ if len(diags) == 0 {
265+ return nil
266+ }
267+ lines := make(map[int]int)
268+ for _, d := range diags {
269+ sev := int(d.Severity)
270+ if sev != SeverityError && sev != SeverityWarning {
271+ continue
272+ }
273+ line := int(d.Range.Start.Line) // 0-indexed
274+ if existing, ok := lines[line]; !ok || sev < existing {
275+ lines[line] = sev
276+ }
277+ }
278+ return lines
279+}
280+
281+// FormatDiagnostics formats diagnostics as a text block for LLM tool responses.
282+// Returns empty string if no errors or warnings.
283+func FormatDiagnostics(displayPath string, diags []protocol.Diagnostic) string {
284+ if len(diags) == 0 {
285+ return ""
286+ }
287+
288+ var buf []byte
289+ count := 0
290+ for _, d := range diags {
291+ sev := int(d.Severity)
292+ if sev != SeverityError && sev != SeverityWarning {
293+ continue
294+ }
295+ if count == 0 {
296+ buf = append(buf, fmt.Sprintf("\nLSP diagnostics:\n<diagnostics file=%q>\n", displayPath)...)
297+ }
298+ label := "WARNING"
299+ if sev == SeverityError {
300+ label = "ERROR"
301+ }
302+ buf = append(buf, fmt.Sprintf("%s [%d:%d] %s\n",
303+ label,
304+ d.Range.Start.Line+1, // display as 1-indexed
305+ d.Range.Start.Character+1,
306+ d.Message,
307+ )...)
308+ count++
309+ if count >= 20 {
310+ remaining := 0
311+ for _, dd := range diags {
312+ if int(dd.Severity) == SeverityError || int(dd.Severity) == SeverityWarning {
313+ remaining++
314+ }
315+ }
316+ remaining -= count
317+ if remaining > 0 {
318+ buf = append(buf, fmt.Sprintf("... and %d more\n", remaining)...)
319+ }
320+ break
321+ }
322+ }
323+ if count == 0 {
324+ return ""
325+ }
326+ buf = append(buf, "</diagnostics>"...)
327+ return string(buf)
328+}
329+
330+// lookPath finds a command binary, checking PATH first, then common
331+// language-specific bin directories that may not be in PATH.
332+func lookPath(command string) string {
333+ if p, err := exec.LookPath(command); err == nil {
334+ return p
335+ }
336+
337+ // Extra directories where language toolchains install binaries.
338+ home, err := os.UserHomeDir()
339+ if err != nil {
340+ return ""
341+ }
342+
343+ var extras []string
344+
345+ // Go: $GOBIN or $GOPATH/bin or ~/go/bin
346+ if gobin := os.Getenv("GOBIN"); gobin != "" {
347+ extras = append(extras, gobin)
348+ }
349+ if gopath := os.Getenv("GOPATH"); gopath != "" {
350+ extras = append(extras, filepath.Join(gopath, "bin"))
351+ }
352+ extras = append(extras, filepath.Join(home, "go", "bin"))
353+
354+ // Rust: ~/.cargo/bin
355+ extras = append(extras, filepath.Join(home, ".cargo", "bin"))
356+
357+ // Local bin
358+ extras = append(extras, filepath.Join(home, ".local", "bin"))
359+
360+ for _, dir := range extras {
361+ p := filepath.Join(dir, command)
362+ if fi, err := os.Stat(p); err == nil && !fi.IsDir() {
363+ return p
364+ }
365+ }
366+ return ""
367+}
internal/mcp_tools/edit.go+29−8
@@ -7,9 +7,11 @@ import (
77 "os"
88 "path/filepath"
99 "strings"
10+ "time"
1011
1112 tea "charm.land/bubbletea/v2"
1213 "github.com/xonecas/symb/internal/hashline"
14+ "github.com/xonecas/symb/internal/lsp"
1315 "github.com/xonecas/symb/internal/mcp"
1416 )
1517
@@ -151,13 +153,14 @@ After each edit you receive fresh hashes — use those for subsequent edits, not
151153
152154 // EditHandler handles Edit tool calls.
153155 type EditHandler struct {
154- program *tea.Program
155- tracker *FileReadTracker
156+ program *tea.Program
157+ tracker *FileReadTracker
158+ lspManager *lsp.Manager
156159 }
157160
158161 // NewEditHandler creates a handler for the Edit tool.
159-func NewEditHandler(tracker *FileReadTracker) *EditHandler {
160- return &EditHandler{tracker: tracker}
162+func NewEditHandler(tracker *FileReadTracker, lspManager *lsp.Manager) *EditHandler {
163+ return &EditHandler{tracker: tracker, lspManager: lspManager}
161164 }
162165
163166 // SetProgram sets the tea.Program instance after it's created.
@@ -212,7 +215,7 @@ func (h *EditHandler) Handle(ctx context.Context, arguments json.RawMessage) (*m
212215
213216 // Dispatch to operation handler
214217 if args.Create != nil {
215- return h.handleCreate(absPath, args.File, args.Create)
218+ return h.handleCreate(ctx, absPath, args.File, args.Create)
216219 }
217220
218221 // Enforce read-before-edit: file must have been opened first
@@ -252,6 +255,7 @@ func (h *EditHandler) Handle(ctx context.Context, arguments json.RawMessage) (*m
252255 Content: result,
253256 Language: language,
254257 FilePath: args.File,
258+ AbsPath: absPath,
255259 })
256260 }
257261
@@ -259,12 +263,20 @@ func (h *EditHandler) Handle(ctx context.Context, arguments json.RawMessage) (*m
259263 tagged := hashline.TagLines(result, 1)
260264 taggedOutput := hashline.FormatTagged(tagged)
261265
266+ text := fmt.Sprintf("Edited %s (%d lines):\n\n%s", args.File, len(tagged), taggedOutput)
267+
268+ // Closed-loop LSP diagnostics: notify and wait for errors/warnings.
269+ if h.lspManager != nil {
270+ diags := h.lspManager.NotifyAndWait(ctx, absPath, 5*time.Second)
271+ text += lsp.FormatDiagnostics(args.File, diags)
272+ }
273+
262274 return &mcp.ToolResult{
263- Content: []mcp.ContentBlock{{Type: "text", Text: fmt.Sprintf("Edited %s (%d lines):\n\n%s", args.File, len(tagged), taggedOutput)}},
275+ Content: []mcp.ContentBlock{{Type: "text", Text: text}},
264276 }, nil
265277 }
266278
267-func (h *EditHandler) handleCreate(absPath, displayPath string, op *CreateOp) (*mcp.ToolResult, error) {
279+func (h *EditHandler) handleCreate(ctx context.Context, absPath, displayPath string, op *CreateOp) (*mcp.ToolResult, error) {
268280 // Fail if file already exists
269281 if _, err := os.Stat(absPath); err == nil {
270282 return toolError("File already exists: %s (use replace/insert/delete to modify)", displayPath), nil
@@ -287,14 +299,23 @@ func (h *EditHandler) handleCreate(absPath, displayPath string, op *CreateOp) (*
287299 Content: op.Content,
288300 Language: language,
289301 FilePath: displayPath,
302+ AbsPath: absPath,
290303 })
291304 }
292305
293306 tagged := hashline.TagLines(op.Content, 1)
294307 taggedOutput := hashline.FormatTagged(tagged)
295308
309+ text := fmt.Sprintf("Created %s (%d lines):\n\n%s", displayPath, len(tagged), taggedOutput)
310+
311+ // Closed-loop LSP diagnostics for newly created file.
312+ if h.lspManager != nil {
313+ diags := h.lspManager.NotifyAndWait(ctx, absPath, 5*time.Second)
314+ text += lsp.FormatDiagnostics(displayPath, diags)
315+ }
316+
296317 return &mcp.ToolResult{
297- Content: []mcp.ContentBlock{{Type: "text", Text: fmt.Sprintf("Created %s (%d lines):\n\n%s", displayPath, len(tagged), taggedOutput)}},
318+ Content: []mcp.ContentBlock{{Type: "text", Text: text}},
298319 }, nil
299320 }
300321
internal/mcp_tools/edit_test.go+7−7
@@ -36,7 +36,7 @@ func newTrackedHandler(t *testing.T, absPath string) *EditHandler {
3636 t.Helper()
3737 tracker := NewFileReadTracker()
3838 tracker.MarkRead(absPath)
39- return NewEditHandler(tracker)
39+ return NewEditHandler(tracker, nil)
4040 }
4141
4242 func callEdit(t *testing.T, handler *EditHandler, args EditArgs) (string, bool) {
@@ -159,7 +159,7 @@ func TestEditCreate(t *testing.T) {
159159 defer os.Chdir(origDir) //nolint:errcheck
160160
161161 tracker := NewFileReadTracker()
162- handler := NewEditHandler(tracker)
162+ handler := NewEditHandler(tracker, nil)
163163 text, isErr := callEdit(t, handler, EditArgs{
164164 File: "newfile.go",
165165 Create: &CreateOp{Content: "package main\n\nfunc main() {}\n"},
@@ -184,7 +184,7 @@ func TestEditCreateFailsIfExists(t *testing.T) {
184184 defer cleanup()
185185
186186 tracker := NewFileReadTracker()
187- handler := NewEditHandler(tracker)
187+ handler := NewEditHandler(tracker, nil)
188188 _, isErr := callEdit(t, handler, EditArgs{
189189 File: "test.go",
190190 Create: &CreateOp{Content: "new content"},
@@ -220,7 +220,7 @@ func TestEditNoOperation(t *testing.T) {
220220 defer cleanup()
221221
222222 tracker := NewFileReadTracker()
223- handler := NewEditHandler(tracker)
223+ handler := NewEditHandler(tracker, nil)
224224 _, isErr := callEdit(t, handler, EditArgs{
225225 File: "test.go",
226226 })
@@ -262,7 +262,7 @@ func TestEditPathTraversal(t *testing.T) {
262262 defer cleanup()
263263
264264 tracker := NewFileReadTracker()
265- handler := NewEditHandler(tracker)
265+ handler := NewEditHandler(tracker, nil)
266266 _, isErr := callEdit(t, handler, EditArgs{
267267 File: "../../../etc/passwd",
268268 Create: &CreateOp{Content: "hacked"},
@@ -339,7 +339,7 @@ func TestEditRequiresReadFirst(t *testing.T) {
339339
340340 // Handler with empty tracker — file NOT read
341341 tracker := NewFileReadTracker()
342- handler := NewEditHandler(tracker)
342+ handler := NewEditHandler(tracker, nil)
343343
344344 text, isErr := callEdit(t, handler, EditArgs{
345345 File: filepath.Base(path),
@@ -385,7 +385,7 @@ func TestEditCreateBypassesReadCheck(t *testing.T) {
385385
386386 // Empty tracker — no file read. Create should still work.
387387 tracker := NewFileReadTracker()
388- handler := NewEditHandler(tracker)
388+ handler := NewEditHandler(tracker, nil)
389389 _, isErr := callEdit(t, handler, EditArgs{
390390 File: "brand-new.go",
391391 Create: &CreateOp{Content: "package new\n"},
internal/mcp_tools/open.go+15−5
@@ -10,6 +10,7 @@ import (
1010
1111 tea "charm.land/bubbletea/v2"
1212 "github.com/xonecas/symb/internal/hashline"
13+ "github.com/xonecas/symb/internal/lsp"
1314 "github.com/xonecas/symb/internal/mcp"
1415 )
1516
@@ -24,7 +25,8 @@ type OpenForUserArgs struct {
2425 type OpenForUserMsg struct {
2526 Content string
2627 Language string
27- FilePath string
28+ FilePath string // display path (may be relative)
29+ AbsPath string // absolute path for matching LSP diagnostics
2830 }
2931
3032 // NewOpenForUserTool creates the Open tool definition.
@@ -59,13 +61,14 @@ func NewOpenForUserTool() mcp.Tool {
5961
6062 // OpenForUserHandler handles Open tool calls and sends messages to the TUI program.
6163 type OpenForUserHandler struct {
62- program *tea.Program
63- tracker *FileReadTracker
64+ program *tea.Program
65+ tracker *FileReadTracker
66+ lspManager *lsp.Manager
6467 }
6568
6669 // NewOpenForUserHandler creates a handler for Open tool.
67-func NewOpenForUserHandler(tracker *FileReadTracker) *OpenForUserHandler {
68- return &OpenForUserHandler{tracker: tracker}
70+func NewOpenForUserHandler(tracker *FileReadTracker, lspManager *lsp.Manager) *OpenForUserHandler {
71+ return &OpenForUserHandler{tracker: tracker, lspManager: lspManager}
6972 }
7073
7174 // SetProgram sets the tea.Program instance after it's created.
@@ -129,6 +132,12 @@ func (h *OpenForUserHandler) Handle(ctx context.Context, arguments json.RawMessa
129132 // Record that this file was read (enables editing)
130133 h.tracker.MarkRead(absPath)
131134
135+ // Warm up LSP for this file (fire-and-forget).
136+ // Use Background context since this outlives the tool-call context.
137+ if h.lspManager != nil {
138+ go h.lspManager.TouchFile(context.Background(), absPath)
139+ }
140+
132141 lines := strings.Split(string(content), "\n")
133142
134143 // Extract line range if specified
@@ -178,6 +187,7 @@ func (h *OpenForUserHandler) Handle(ctx context.Context, arguments json.RawMessa
178187 Content: selectedContent,
179188 Language: language,
180189 FilePath: args.File,
190+ AbsPath: absPath,
181191 })
182192 }
183193
internal/tui/editor/editor.go+5−0
@@ -51,6 +51,11 @@ type Model struct {
5151 // Per-line background overrides (e.g. diff line tinting).
5252 LineBg map[int]lipgloss.Style // bufRow (0-indexed) -> background style
5353
54+ // Per-line diagnostic severity (LSP). bufRow (0-indexed) -> severity (1=error, 2=warning).
55+ DiagnosticLines map[int]int
56+ DiagErrStyle lipgloss.Style // Line number fg when line has error
57+ DiagWarnStyle lipgloss.Style // Line number fg when line has warning
58+
5459 // Internal state
5560 lines [][]rune // Backing store, one entry per line
5661 row int // Cursor row (0-indexed into lines)
internal/tui/editor/view.go+10−1
@@ -130,8 +130,17 @@ func (m Model) View() string {
130130 }
131131 digits := m.gutterWidth - 2 // gutter = digits + space + marker
132132 if vr.subRow == 0 {
133+ numSty := gutSty
134+ if sev, ok := m.DiagnosticLines[vr.bufRow]; ok {
135+ switch sev {
136+ case 1: // error
137+ numSty = m.DiagErrStyle.Background(gutSty.GetBackground())
138+ case 2: // warning
139+ numSty = m.DiagWarnStyle.Background(gutSty.GetBackground())
140+ }
141+ }
133142 num := fmt.Sprintf("%*d ", digits, vr.bufRow+1)
134- b.WriteString(gutSty.Render(num))
143+ b.WriteString(numSty.Render(num))
135144 b.WriteString(m.renderGutterMark(vr.bufRow, gutSty))
136145 } else {
137146 // Continuation row — blank gutter
internal/tui/messages.go+6−0
@@ -41,6 +41,12 @@ type llmReasoningDeltaMsg struct{ content string }
4141 // UpdateToolsMsg is exported so main.go can send it via program.Send.
4242 type UpdateToolsMsg struct{ Tools []mcp.Tool }
4343
44+// LSPDiagnosticsMsg carries diagnostic line severities from the LSP manager to the TUI.
45+type LSPDiagnosticsMsg struct {
46+ FilePath string // absolute path of the file
47+ Lines map[int]int // bufRow (0-indexed) -> max severity (1=error, 2=warning)
48+}
49+
4450 // ---------------------------------------------------------------------------
4551 // ELM commands
4652 // ---------------------------------------------------------------------------
internal/tui/tui.go+5−0
@@ -188,6 +188,9 @@ type Model struct {
188188 streaming bool // Whether we're currently streaming
189189 streamEntryStart int // Index in convEntries where streaming entries begin (-1 = none)
190190
191+ // Editor state
192+ editorFilePath string // absolute path of the file currently shown in the editor
193+
191194 // Mouse state
192195 resizingPane bool
193196
@@ -219,6 +222,8 @@ func New(prov provider.Provider, proxy *mcp.Proxy, tools []mcp.Tool, modelID str
219222 ed.MarkAddStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#4ec964")).Background(ColorBg)
220223 ed.MarkChgStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#e5c07b")).Background(ColorBg)
221224 ed.MarkDelStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#e06c75")).Background(ColorBg)
225+ ed.DiagErrStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#e06c75"))
226+ ed.DiagWarnStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("#e5c07b"))
222227
223228 ai := editor.New()
224229 ai.Placeholder = "Type a message..."
internal/tui/update.go+9−0
Cut short: this commit's diff is over 1000 lines.