on main help sign in
Merge remote-tracking branch 'origin/main' into fix-openai-provider
dd11ff0Kujtim Hoxha
.github/dependabot.yml+2−2
@@ -9,7 +9,7 @@ updates:
9 time: "05:00"
9 time: "05:00"
10 timezone: "America/New_York"
10 timezone: "America/New_York"
11 labels:
11 labels:
12− - "dependencies"
12+ - "area: dependencies"
13 commit-message:
13 commit-message:
14 prefix: "chore"
14 prefix: "chore"
15 include: "scope"
15 include: "scope"
@@ -22,7 +22,7 @@ updates:
22 time: "05:00"
22 time: "05:00"
23 timezone: "America/New_York"
23 timezone: "America/New_York"
24 labels:
24 labels:
25− - "dependencies"
25+ - "area: dependencies"
26 commit-message:
26 commit-message:
27 prefix: "chore"
27 prefix: "chore"
28 include: "scope"
28 include: "scope"
.github/workflows/build.yml+2
@@ -23,7 +23,9 @@ jobs:
23 with:
23 with:
24 github-token: "${{ secrets.GITHUB_TOKEN }}"
24 github-token: "${{ secrets.GITHUB_TOKEN }}"
25 - run: |
25 - run: |
26+ echo "Approving..."
26 gh pr review --approve "$PR_URL"
27 gh pr review --approve "$PR_URL"
28+ echo "Merging..."
27 gh pr merge --squash --auto "$PR_URL"
29 gh pr merge --squash --auto "$PR_URL"
28 env:
30 env:
29 PR_URL: ${{github.event.pull_request.html_url}}
31 PR_URL: ${{github.event.pull_request.html_url}}
.goreleaser.yml+6
@@ -166,6 +166,12 @@ brews:
166 fish_completion.install "completions/{{ .ProjectName }}.fish"
166 fish_completion.install "completions/{{ .ProjectName }}.fish"
167 man1.install "manpages/{{ .ProjectName }}.1.gz"
167 man1.install "manpages/{{ .ProjectName }}.1.gz"
168
168
169+scoops:
170+ - repository:
171+ owner: charmbracelet
172+ name: scoop-bucket
173+ token: "{{ .Env.HOMEBREW_TAP_GITHUB_TOKEN }}"
174+
169npms:
175npms:
170 - name: "@charmland/crush"
176 - name: "@charmland/crush"
171 repository: "git+https://github.com/charmbracelet/crush.git"
177 repository: "git+https://github.com/charmbracelet/crush.git"
go.mod+3−3
@@ -6,7 +6,7 @@ require (
6 github.com/JohannesKaufmann/html-to-markdown v1.6.0
6 github.com/JohannesKaufmann/html-to-markdown v1.6.0
7 github.com/MakeNowJust/heredoc v1.0.0
7 github.com/MakeNowJust/heredoc v1.0.0
8 github.com/PuerkitoBio/goquery v1.9.2
8 github.com/PuerkitoBio/goquery v1.9.2
9− github.com/alecthomas/chroma/v2 v2.15.0
9+ github.com/alecthomas/chroma/v2 v2.20.0
10 github.com/anthropics/anthropic-sdk-go v1.6.2
10 github.com/anthropics/anthropic-sdk-go v1.6.2
11 github.com/atotto/clipboard v0.1.4
11 github.com/atotto/clipboard v0.1.4
12 github.com/aymanbagabas/go-udiff v0.3.1
12 github.com/aymanbagabas/go-udiff v0.3.1
@@ -93,7 +93,7 @@ require (
93 github.com/charmbracelet/x/windows v0.2.1 // indirect
93 github.com/charmbracelet/x/windows v0.2.1 // indirect
94 github.com/davecgh/go-spew v1.1.1 // indirect
94 github.com/davecgh/go-spew v1.1.1 // indirect
95 github.com/disintegration/gift v1.1.2 // indirect
95 github.com/disintegration/gift v1.1.2 // indirect
96− github.com/dlclark/regexp2 v1.11.4 // indirect
96+ github.com/dlclark/regexp2 v1.11.5 // indirect
97 github.com/dustin/go-humanize v1.0.1 // indirect
97 github.com/dustin/go-humanize v1.0.1 // indirect
98 github.com/felixge/httpsnoop v1.0.4 // indirect
98 github.com/felixge/httpsnoop v1.0.4 // indirect
99 github.com/go-logfmt/logfmt v0.6.0 // indirect
99 github.com/go-logfmt/logfmt v0.6.0 // indirect
@@ -144,7 +144,7 @@ require (
144 golang.org/x/sync v0.16.0 // indirect
144 golang.org/x/sync v0.16.0 // indirect
145 golang.org/x/sys v0.34.0
145 golang.org/x/sys v0.34.0
146 golang.org/x/term v0.32.0 // indirect
146 golang.org/x/term v0.32.0 // indirect
147− golang.org/x/text v0.25.0
147+ golang.org/x/text v0.27.0
148 google.golang.org/genai v1.3.0
148 google.golang.org/genai v1.3.0
149 google.golang.org/genproto/googleapis/rpc v0.0.0-20250324211829-b45e905df463 // indirect
149 google.golang.org/genproto/googleapis/rpc v0.0.0-20250324211829-b45e905df463 // indirect
150 google.golang.org/grpc v1.71.0 // indirect
150 google.golang.org/grpc v1.71.0 // indirect
go.sum+8−8
@@ -22,10 +22,10 @@ github.com/PuerkitoBio/goquery v1.9.2 h1:4/wZksC3KgkQw7SQgkKotmKljk0M6V8TUvA8Wb4
22github.com/PuerkitoBio/goquery v1.9.2/go.mod h1:GHPCaP0ODyyxqcNoFGYlAprUFH81NuRPd0GX3Zu2Mvk=
22github.com/PuerkitoBio/goquery v1.9.2/go.mod h1:GHPCaP0ODyyxqcNoFGYlAprUFH81NuRPd0GX3Zu2Mvk=
23github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0=
23github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0=
24github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k=
24github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k=
25−github.com/alecthomas/chroma/v2 v2.15.0 h1:LxXTQHFoYrstG2nnV9y2X5O94sOBzf0CIUpSTbpxvMc=
25+github.com/alecthomas/chroma/v2 v2.20.0 h1:sfIHpxPyR07/Oylvmcai3X/exDlE8+FA820NTz+9sGw=
26−github.com/alecthomas/chroma/v2 v2.15.0/go.mod h1:gUhVLrPDXPtp/f+L1jo9xepo9gL4eLwRuGAunSZMkio=
26+github.com/alecthomas/chroma/v2 v2.20.0/go.mod h1:e7tViK0xh/Nf4BYHl00ycY6rV7b8iXBksI9E359yNmA=
27−github.com/alecthomas/repr v0.4.0 h1:GhI2A8MACjfegCPVq9f1FLvIBS+DrQ2KQBFZP1iFzXc=
27+github.com/alecthomas/repr v0.5.1 h1:E3G4t2QbHTSNpPKBgMTln5KLkZHLOcU7r37J4pXBuIg=
28−github.com/alecthomas/repr v0.4.0/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
28+github.com/alecthomas/repr v0.5.1/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4=
29github.com/andybalholm/cascadia v1.3.2 h1:3Xi6Dw5lHF15JtdcmAHD3i1+T8plmv7BQ/nsViSLyss=
29github.com/andybalholm/cascadia v1.3.2 h1:3Xi6Dw5lHF15JtdcmAHD3i1+T8plmv7BQ/nsViSLyss=
30github.com/andybalholm/cascadia v1.3.2/go.mod h1:7gtRlve5FxPPgIgX36uWBX58OdBsSS6lUvCFb+h7KvU=
30github.com/andybalholm/cascadia v1.3.2/go.mod h1:7gtRlve5FxPPgIgX36uWBX58OdBsSS6lUvCFb+h7KvU=
31github.com/anthropics/anthropic-sdk-go v1.6.2 h1:oORA212y0/zAxe7OPvdgIbflnn/x5PGk5uwjF60GqXM=
31github.com/anthropics/anthropic-sdk-go v1.6.2 h1:oORA212y0/zAxe7OPvdgIbflnn/x5PGk5uwjF60GqXM=
@@ -118,8 +118,8 @@ github.com/disintegration/gift v1.1.2 h1:9ZyHJr+kPamiH10FX3Pynt1AxFUob812bU9Wt4G
118github.com/disintegration/gift v1.1.2/go.mod h1:Jh2i7f7Q2BM7Ezno3PhfezbR1xpUg9dUg3/RlKGr4HI=
118github.com/disintegration/gift v1.1.2/go.mod h1:Jh2i7f7Q2BM7Ezno3PhfezbR1xpUg9dUg3/RlKGr4HI=
119github.com/disintegration/imageorient v0.0.0-20180920195336-8147d86e83ec h1:YrB6aVr9touOt75I9O1SiancmR2GMg45U9UYf0gtgWg=
119github.com/disintegration/imageorient v0.0.0-20180920195336-8147d86e83ec h1:YrB6aVr9touOt75I9O1SiancmR2GMg45U9UYf0gtgWg=
120github.com/disintegration/imageorient v0.0.0-20180920195336-8147d86e83ec/go.mod h1:K0KBFIr1gWu/C1Gp10nFAcAE4hsB7JxE6OgLijrJ8Sk=
120github.com/disintegration/imageorient v0.0.0-20180920195336-8147d86e83ec/go.mod h1:K0KBFIr1gWu/C1Gp10nFAcAE4hsB7JxE6OgLijrJ8Sk=
121−github.com/dlclark/regexp2 v1.11.4 h1:rPYF9/LECdNymJufQKmri9gV604RvvABwgOA8un7yAo=
121+github.com/dlclark/regexp2 v1.11.5 h1:Q/sSnsKerHeCkc/jSTNq1oCm7KiVgUMZRDUoRu0JQZQ=
122−github.com/dlclark/regexp2 v1.11.4/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
122+github.com/dlclark/regexp2 v1.11.5/go.mod h1:DHkYz0B9wPfa6wondMfaivmHpzrQ3v9q8cnmRbL6yW8=
123github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
123github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
124github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
124github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
125github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
125github.com/felixge/httpsnoop v1.0.4 h1:NFTV2Zj1bL4mc9sqWACXbQFVBBg2W3GPvqp8/ESS2Wg=
@@ -371,8 +371,8 @@ golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
371golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
371golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8=
372golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
372golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
373golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
373golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
374−golang.org/x/text v0.25.0 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4=
374+golang.org/x/text v0.27.0 h1:4fGWRpyh641NLlecmyl4LOe6yDdfaYNrGb2zdfo4JV4=
375−golang.org/x/text v0.25.0/go.mod h1:WEdwpYrmk1qmdHvhkSTNPm3app7v4rsT8F2UD6+VHIA=
375+golang.org/x/text v0.27.0/go.mod h1:1D28KMCvyooCX9hBiosv5Tz/+YLxj0j7XhWjpSUF7CU=
376golang.org/x/time v0.8.0 h1:9i3RxcPv3PZnitoVGMPDKZSq1xW1gK1Xy3ArNOGZfEg=
376golang.org/x/time v0.8.0 h1:9i3RxcPv3PZnitoVGMPDKZSq1xW1gK1Xy3ArNOGZfEg=
377golang.org/x/time v0.8.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
377golang.org/x/time v0.8.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
378golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
378golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
internal/app/app.go+2
@@ -207,6 +207,8 @@ func (app *App) setupEvents() {
207 setupSubscriber(ctx, app.serviceEventsWG, "permissions", app.Permissions.Subscribe, app.events)
207 setupSubscriber(ctx, app.serviceEventsWG, "permissions", app.Permissions.Subscribe, app.events)
208 setupSubscriber(ctx, app.serviceEventsWG, "permissions-notifications", app.Permissions.SubscribeNotifications, app.events)
208 setupSubscriber(ctx, app.serviceEventsWG, "permissions-notifications", app.Permissions.SubscribeNotifications, app.events)
209 setupSubscriber(ctx, app.serviceEventsWG, "history", app.History.Subscribe, app.events)
209 setupSubscriber(ctx, app.serviceEventsWG, "history", app.History.Subscribe, app.events)
210+ setupSubscriber(ctx, app.serviceEventsWG, "mcp", agent.SubscribeMCPEvents, app.events)
211+ setupSubscriber(ctx, app.serviceEventsWG, "lsp", SubscribeLSPEvents, app.events)
210 cleanupFunc := func() {
212 cleanupFunc := func() {
211 cancel()
213 cancel()
212 app.serviceEventsWG.Wait()
214 app.serviceEventsWG.Wait()
internal/app/lsp.go+11−1
@@ -22,13 +22,20 @@ func (app *App) initLSPClients(ctx context.Context) {
22func (app *App) createAndStartLSPClient(ctx context.Context, name string, command string, args ...string) {
22func (app *App) createAndStartLSPClient(ctx context.Context, name string, command string, args ...string) {
23 slog.Info("Creating LSP client", "name", name, "command", command, "args", args)
23 slog.Info("Creating LSP client", "name", name, "command", command, "args", args)
24
24
25+ // Update state to starting
26+ updateLSPState(name, lsp.StateStarting, nil, nil, 0)
27+
25 // Create LSP client.
28 // Create LSP client.
26− lspClient, err := lsp.NewClient(ctx, command, args...)
29+ lspClient, err := lsp.NewClient(ctx, name, command, args...)
27 if err != nil {
30 if err != nil {
28 slog.Error("Failed to create LSP client for", name, err)
31 slog.Error("Failed to create LSP client for", name, err)
32+ updateLSPState(name, lsp.StateError, err, nil, 0)
29 return
33 return
30 }
34 }
31
35
36+ // Set diagnostics callback
37+ lspClient.SetDiagnosticsCallback(updateLSPDiagnostics)
38+
32 // Increase initialization timeout as some servers take more time to start.
39 // Increase initialization timeout as some servers take more time to start.
33 initCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
40 initCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
34 defer cancel()
41 defer cancel()
@@ -37,6 +44,7 @@ func (app *App) createAndStartLSPClient(ctx context.Context, name string, comman
37 _, err = lspClient.InitializeLSPClient(initCtx, app.config.WorkingDir())
44 _, err = lspClient.InitializeLSPClient(initCtx, app.config.WorkingDir())
38 if err != nil {
45 if err != nil {
39 slog.Error("Initialize failed", "name", name, "error", err)
46 slog.Error("Initialize failed", "name", name, "error", err)
47+ updateLSPState(name, lsp.StateError, err, lspClient, 0)
40 lspClient.Close()
48 lspClient.Close()
41 return
49 return
42 }
50 }
@@ -47,10 +55,12 @@ func (app *App) createAndStartLSPClient(ctx context.Context, name string, comman
47 // Server never reached a ready state, but let's continue anyway, as
55 // Server never reached a ready state, but let's continue anyway, as
48 // some functionality might still work.
56 // some functionality might still work.
49 lspClient.SetServerState(lsp.StateError)
57 lspClient.SetServerState(lsp.StateError)
58+ updateLSPState(name, lsp.StateError, err, lspClient, 0)
50 } else {
59 } else {
51 // Server reached a ready state scuccessfully.
60 // Server reached a ready state scuccessfully.
52 slog.Info("LSP server is ready", "name", name)
61 slog.Info("LSP server is ready", "name", name)
53 lspClient.SetServerState(lsp.StateReady)
62 lspClient.SetServerState(lsp.StateReady)
63+ updateLSPState(name, lsp.StateReady, nil, lspClient, 0)
54 }
64 }
55
65
56 slog.Info("LSP client initialized", "name", name)
66 slog.Info("LSP client initialized", "name", name)
internal/app/lsp_events.gonew file+102
@@ -0,0 +1,102 @@
1+package app
2+
3+import (
4+ "context"
5+ "time"
6+
7+ "github.com/charmbracelet/crush/internal/csync"
8+ "github.com/charmbracelet/crush/internal/lsp"
9+ "github.com/charmbracelet/crush/internal/pubsub"
10+)
11+
12+// LSPEventType represents the type of LSP event
13+type LSPEventType string
14+
15+const (
16+ LSPEventStateChanged LSPEventType = "state_changed"
17+ LSPEventDiagnosticsChanged LSPEventType = "diagnostics_changed"
18+)
19+
20+// LSPEvent represents an event in the LSP system
21+type LSPEvent struct {
22+ Type LSPEventType
23+ Name string
24+ State lsp.ServerState
25+ Error error
26+ DiagnosticCount int
27+}
28+
29+// LSPClientInfo holds information about an LSP client's state
30+type LSPClientInfo struct {
31+ Name string
32+ State lsp.ServerState
33+ Error error
34+ Client *lsp.Client
35+ DiagnosticCount int
36+ ConnectedAt time.Time
37+}
38+
39+var (
40+ lspStates = csync.NewMap[string, LSPClientInfo]()
41+ lspBroker = pubsub.NewBroker[LSPEvent]()
42+)
43+
44+// SubscribeLSPEvents returns a channel for LSP events
45+func SubscribeLSPEvents(ctx context.Context) <-chan pubsub.Event[LSPEvent] {
46+ return lspBroker.Subscribe(ctx)
47+}
48+
49+// GetLSPStates returns the current state of all LSP clients
50+func GetLSPStates() map[string]LSPClientInfo {
51+ states := make(map[string]LSPClientInfo)
52+ for name, info := range lspStates.Seq2() {
53+ states[name] = info
54+ }
55+ return states
56+}
57+
58+// GetLSPState returns the state of a specific LSP client
59+func GetLSPState(name string) (LSPClientInfo, bool) {
60+ return lspStates.Get(name)
61+}
62+
63+// updateLSPState updates the state of an LSP client and publishes an event
64+func updateLSPState(name string, state lsp.ServerState, err error, client *lsp.Client, diagnosticCount int) {
65+ info := LSPClientInfo{
66+ Name: name,
67+ State: state,
68+ Error: err,
69+ Client: client,
70+ DiagnosticCount: diagnosticCount,
71+ }
72+ if state == lsp.StateReady {
73+ info.ConnectedAt = time.Now()
74+ }
75+ lspStates.Set(name, info)
76+
77+ // Publish state change event
78+ lspBroker.Publish(pubsub.UpdatedEvent, LSPEvent{
79+ Type: LSPEventStateChanged,
80+ Name: name,
81+ State: state,
82+ Error: err,
83+ DiagnosticCount: diagnosticCount,
84+ })
85+}
86+
87+// updateLSPDiagnostics updates the diagnostic count for an LSP client and publishes an event
88+func updateLSPDiagnostics(name string, diagnosticCount int) {
89+ if info, exists := lspStates.Get(name); exists {
90+ info.DiagnosticCount = diagnosticCount
91+ lspStates.Set(name, info)
92+
93+ // Publish diagnostics change event
94+ lspBroker.Publish(pubsub.UpdatedEvent, LSPEvent{
95+ Type: LSPEventDiagnosticsChanged,
96+ Name: name,
97+ State: info.State,
98+ Error: info.Error,
99+ DiagnosticCount: diagnosticCount,
100+ })
101+ }
102+}
internal/llm/agent/agent.go+37−31
@@ -159,11 +159,12 @@ func NewAgent(
159 if err != nil {
159 if err != nil {
160 return nil, err
160 return nil, err
161 }
161 }
162+
162 summarizeOpts := []provider.ProviderClientOption{
163 summarizeOpts := []provider.ProviderClientOption{
163− provider.WithModel(config.SelectedModelTypeSmall),
164+ provider.WithModel(config.SelectedModelTypeLarge),
164− provider.WithSystemMessage(prompt.GetPrompt(prompt.PromptSummarizer, smallModelProviderCfg.ID)),
165+ provider.WithSystemMessage(prompt.GetPrompt(prompt.PromptSummarizer, providerCfg.ID)),
165 }
166 }
166− summarizeProvider, err := provider.NewProvider(*smallModelProviderCfg, summarizeOpts...)
167+ summarizeProvider, err := provider.NewProvider(*providerCfg, summarizeOpts...)
167 if err != nil {
168 if err != nil {
168 return nil, err
169 return nil, err
169 }
170 }
@@ -224,7 +225,7 @@ func NewAgent(
224 sessions: sessions,
225 sessions: sessions,
225 titleProvider: titleProvider,
226 titleProvider: titleProvider,
226 summarizeProvider: summarizeProvider,
227 summarizeProvider: summarizeProvider,
227− summarizeProviderID: string(smallModelProviderCfg.ID),
228+ summarizeProviderID: string(providerCfg.ID),
228 activeRequests: csync.NewMap[string, context.CancelFunc](),
229 activeRequests: csync.NewMap[string, context.CancelFunc](),
229 tools: csync.NewLazySlice(toolFn),
230 tools: csync.NewLazySlice(toolFn),
230 }, nil
231 }, nil
@@ -904,54 +905,59 @@ func (a *agent) UpdateModel() error {
904 a.providerID = string(currentProviderCfg.ID)
905 a.providerID = string(currentProviderCfg.ID)
905 }
906 }
906
907
907− // Check if small model provider has changed (affects title and summarize providers)
908+ // Check if providers have changed for title (small) and summarize (large)
908 smallModelCfg := cfg.Models[config.SelectedModelTypeSmall]
909 smallModelCfg := cfg.Models[config.SelectedModelTypeSmall]
909 var smallModelProviderCfg config.ProviderConfig
910 var smallModelProviderCfg config.ProviderConfig
910−
911 for p := range cfg.Providers.Seq() {
911 for p := range cfg.Providers.Seq() {
912 if p.ID == smallModelCfg.Provider {
912 if p.ID == smallModelCfg.Provider {
913 smallModelProviderCfg = p
913 smallModelProviderCfg = p
914 break
914 break
915 }
915 }
916 }
916 }
917−
918 if smallModelProviderCfg.ID == "" {
917 if smallModelProviderCfg.ID == "" {
919 return fmt.Errorf("provider %s not found in config", smallModelCfg.Provider)
918 return fmt.Errorf("provider %s not found in config", smallModelCfg.Provider)
920 }
919 }
921
920
922− // Check if summarize provider has changed
921+ largeModelCfg := cfg.Models[config.SelectedModelTypeLarge]
923− if string(smallModelProviderCfg.ID) != a.summarizeProviderID {
922+ var largeModelProviderCfg config.ProviderConfig
924− smallModel := cfg.GetModelByType(config.SelectedModelTypeSmall)
923+ for p := range cfg.Providers.Seq() {
925− if smallModel == nil {
924+ if p.ID == largeModelCfg.Provider {
926− return fmt.Errorf("model %s not found in provider %s", smallModelCfg.Model, smallModelProviderCfg.ID)
925+ largeModelProviderCfg = p
926+ break
927 }
927 }
928+ }
929+ if largeModelProviderCfg.ID == "" {
930+ return fmt.Errorf("provider %s not found in config", largeModelCfg.Provider)
931+ }
928
932
929− // Recreate title provider
933+ // Recreate title provider
930− titleOpts := []provider.ProviderClientOption{
934+ titleOpts := []provider.ProviderClientOption{
931− provider.WithModel(config.SelectedModelTypeSmall),
935+ provider.WithModel(config.SelectedModelTypeSmall),
932− provider.WithSystemMessage(prompt.GetPrompt(prompt.PromptTitle, smallModelProviderCfg.ID)),
936+ provider.WithSystemMessage(prompt.GetPrompt(prompt.PromptTitle, smallModelProviderCfg.ID)),
933− // We want the title to be short, so we limit the max tokens
934− provider.WithMaxTokens(40),
937+ provider.WithMaxTokens(40),
935− }
938+ }
936− newTitleProvider, err := provider.NewProvider(smallModelProviderCfg, titleOpts...)
939+ newTitleProvider, err := provider.NewProvider(smallModelProviderCfg, titleOpts...)
937− if err != nil {
940+ if err != nil {
938− return fmt.Errorf("failed to create new title provider: %w", err)
941+ return fmt.Errorf("failed to create new title provider: %w", err)
939− }
942+ }
943+ a.titleProvider = newTitleProvider
940
944
941− // Recreate summarize provider
945+ // Recreate summarize provider if provider changed (now large model)
946+ if string(largeModelProviderCfg.ID) != a.summarizeProviderID {
947+ largeModel := cfg.GetModelByType(config.SelectedModelTypeLarge)
948+ if largeModel == nil {
949+ return fmt.Errorf("model %s not found in provider %s", largeModelCfg.Model, largeModelProviderCfg.ID)
950+ }
942 summarizeOpts := []provider.ProviderClientOption{
951 summarizeOpts := []provider.ProviderClientOption{
943− provider.WithModel(config.SelectedModelTypeSmall),
952+ provider.WithModel(config.SelectedModelTypeLarge),
944− provider.WithSystemMessage(prompt.GetPrompt(prompt.PromptSummarizer, smallModelProviderCfg.ID)),
953+ provider.WithSystemMessage(prompt.GetPrompt(prompt.PromptSummarizer, largeModelProviderCfg.ID)),
945 }
954 }
946− newSummarizeProvider, err := provider.NewProvider(smallModelProviderCfg, summarizeOpts...)
955+ newSummarizeProvider, err := provider.NewProvider(largeModelProviderCfg, summarizeOpts...)
947 if err != nil {
956 if err != nil {
948 return fmt.Errorf("failed to create new summarize provider: %w", err)
957 return fmt.Errorf("failed to create new summarize provider: %w", err)
949 }
958 }
950−
951− // Update the providers and provider ID
952− a.titleProvider = newTitleProvider
953 a.summarizeProvider = newSummarizeProvider
959 a.summarizeProvider = newSummarizeProvider
954− a.summarizeProviderID = string(smallModelProviderCfg.ID)
960+ a.summarizeProviderID = string(largeModelProviderCfg.ID)
955 }
961 }
956
962
957 return nil
963 return nil
internal/llm/agent/mcp-tools.go+130−2
@@ -7,21 +7,76 @@ import (
7 "log/slog"
7 "log/slog"
8 "slices"
8 "slices"
9 "sync"
9 "sync"
10+ "time"
10
11
11 "github.com/charmbracelet/crush/internal/config"
12 "github.com/charmbracelet/crush/internal/config"
12 "github.com/charmbracelet/crush/internal/csync"
13 "github.com/charmbracelet/crush/internal/csync"
13 "github.com/charmbracelet/crush/internal/llm/tools"
14 "github.com/charmbracelet/crush/internal/llm/tools"
14 "github.com/charmbracelet/crush/internal/permission"
15 "github.com/charmbracelet/crush/internal/permission"
16+ "github.com/charmbracelet/crush/internal/pubsub"
15 "github.com/charmbracelet/crush/internal/version"
17 "github.com/charmbracelet/crush/internal/version"
16 "github.com/mark3labs/mcp-go/client"
18 "github.com/mark3labs/mcp-go/client"
17 "github.com/mark3labs/mcp-go/client/transport"
19 "github.com/mark3labs/mcp-go/client/transport"
18 "github.com/mark3labs/mcp-go/mcp"
20 "github.com/mark3labs/mcp-go/mcp"
19)
21)
20
22
23+// MCPState represents the current state of an MCP client
24+type MCPState int
25+
26+const (
27+ MCPStateDisabled MCPState = iota
28+ MCPStateStarting
29+ MCPStateConnected
30+ MCPStateError
31+)
32+
33+func (s MCPState) String() string {
34+ switch s {
35+ case MCPStateDisabled:
36+ return "disabled"
37+ case MCPStateStarting:
38+ return "starting"
39+ case MCPStateConnected:
40+ return "connected"
41+ case MCPStateError:
42+ return "error"
43+ default:
44+ return "unknown"
45+ }
46+}
47+
48+// MCPEventType represents the type of MCP event
49+type MCPEventType string
50+
51+const (
52+ MCPEventStateChanged MCPEventType = "state_changed"
53+)
54+
55+// MCPEvent represents an event in the MCP system
56+type MCPEvent struct {
57+ Type MCPEventType
58+ Name string
59+ State MCPState
60+ Error error
61+ ToolCount int
62+}
63+
64+// MCPClientInfo holds information about an MCP client's state
65+type MCPClientInfo struct {
66+ Name string
67+ State MCPState
68+ Error error
69+ Client *client.Client
70+ ToolCount int
71+ ConnectedAt time.Time
72+}
73+
21var (
74var (
22 mcpToolsOnce sync.Once
75 mcpToolsOnce sync.Once
23 mcpTools []tools.BaseTool
76 mcpTools []tools.BaseTool
24 mcpClients = csync.NewMap[string, *client.Client]()
77 mcpClients = csync.NewMap[string, *client.Client]()
78+ mcpStates = csync.NewMap[string, MCPClientInfo]()
79+ mcpBroker = pubsub.NewBroker[MCPEvent]()
25)
80)
26
81
27type McpTool struct {
82type McpTool struct {
@@ -107,6 +162,7 @@ func getTools(ctx context.Context, name string, permissions permission.Service,
107 result, err := c.ListTools(ctx, mcp.ListToolsRequest{})
162 result, err := c.ListTools(ctx, mcp.ListToolsRequest{})
108 if err != nil {
163 if err != nil {
109 slog.Error("error listing tools", "error", err)
164 slog.Error("error listing tools", "error", err)
165+ updateMCPState(name, MCPStateError, err, nil, 0)
110 c.Close()
166 c.Close()
111 mcpClients.Del(name)
167 mcpClients.Del(name)
112 return nil
168 return nil
@@ -123,11 +179,55 @@ func getTools(ctx context.Context, name string, permissions permission.Service,
123 return mcpTools
179 return mcpTools
124}
180}
125
181
182+// SubscribeMCPEvents returns a channel for MCP events
183+func SubscribeMCPEvents(ctx context.Context) <-chan pubsub.Event[MCPEvent] {
184+ return mcpBroker.Subscribe(ctx)
185+}
186+
187+// GetMCPStates returns the current state of all MCP clients
188+func GetMCPStates() map[string]MCPClientInfo {
189+ states := make(map[string]MCPClientInfo)
190+ for name, info := range mcpStates.Seq2() {
191+ states[name] = info
192+ }
193+ return states
194+}
195+
196+// GetMCPState returns the state of a specific MCP client
197+func GetMCPState(name string) (MCPClientInfo, bool) {
198+ return mcpStates.Get(name)
199+}
200+
201+// updateMCPState updates the state of an MCP client and publishes an event
202+func updateMCPState(name string, state MCPState, err error, client *client.Client, toolCount int) {
203+ info := MCPClientInfo{
204+ Name: name,
205+ State: state,
206+ Error: err,
207+ Client: client,
208+ ToolCount: toolCount,
209+ }
210+ if state == MCPStateConnected {
211+ info.ConnectedAt = time.Now()
212+ }
213+ mcpStates.Set(name, info)
214+
215+ // Publish state change event
216+ mcpBroker.Publish(pubsub.UpdatedEvent, MCPEvent{
217+ Type: MCPEventStateChanged,
218+ Name: name,
219+ State: state,
220+ Error: err,
221+ ToolCount: toolCount,
222+ })
223+}
224+
126// CloseMCPClients closes all MCP clients. This should be called during application shutdown.
225// CloseMCPClients closes all MCP clients. This should be called during application shutdown.
127func CloseMCPClients() {
226func CloseMCPClients() {
128 for c := range mcpClients.Seq() {
227 for c := range mcpClients.Seq() {
129 _ = c.Close()
228 _ = c.Close()
130 }
229 }
230+ mcpBroker.Shutdown()
131}
231}
132
232
133var mcpInitRequest = mcp.InitializeRequest{
233var mcpInitRequest = mcp.InitializeRequest{
@@ -143,25 +243,51 @@ var mcpInitRequest = mcp.InitializeRequest{
143func doGetMCPTools(ctx context.Context, permissions permission.Service, cfg *config.Config) []tools.BaseTool {
243func doGetMCPTools(ctx context.Context, permissions permission.Service, cfg *config.Config) []tools.BaseTool {
144 var wg sync.WaitGroup
244 var wg sync.WaitGroup
145 result := csync.NewSlice[tools.BaseTool]()
245 result := csync.NewSlice[tools.BaseTool]()
246+
247+ // Initialize states for all configured MCPs
146 for name, m := range cfg.MCP {
248 for name, m := range cfg.MCP {
147 if m.Disabled {
249 if m.Disabled {
250+ updateMCPState(name, MCPStateDisabled, nil, nil, 0)
148 slog.Debug("skipping disabled mcp", "name", name)
251 slog.Debug("skipping disabled mcp", "name", name)
149 continue
252 continue
150 }
253 }
254+
255+ // Set initial starting state
256+ updateMCPState(name, MCPStateStarting, nil, nil, 0)
257+
151 wg.Add(1)
258 wg.Add(1)
152 go func(name string, m config.MCPConfig) {
259 go func(name string, m config.MCPConfig) {
260+ defer func() {
153− defer wg.Done()
261+ wg.Done()
262+ if r := recover(); r != nil {
263+ var err error
264+ switch v := r.(type) {
265+ case error:
266+ err = v
267+ case string:
268+ err = fmt.Errorf("panic: %s", v)
269+ default:
270+ err = fmt.Errorf("panic: %v", v)
271+ }
272+ updateMCPState(name, MCPStateError, err, nil, 0)
273+ slog.Error("panic in mcp client initialization", "error", err, "name", name)
274+ }
275+ }()
276+
154 c, err := createMcpClient(m)
277 c, err := createMcpClient(m)
155 if err != nil {
278 if err != nil {
279+ updateMCPState(name, MCPStateError, err, nil, 0)
156 slog.Error("error creating mcp client", "error", err, "name", name)
280 slog.Error("error creating mcp client", "error", err, "name", name)
157 return
281 return
158 }
282 }
159 if err := c.Start(ctx); err != nil {
283 if err := c.Start(ctx); err != nil {
284+ updateMCPState(name, MCPStateError, err, nil, 0)
160 slog.Error("error starting mcp client", "error", err, "name", name)
285 slog.Error("error starting mcp client", "error", err, "name", name)
161 _ = c.Close()
286 _ = c.Close()
162 return
287 return
163 }
288 }
164 if _, err := c.Initialize(ctx, mcpInitRequest); err != nil {
289 if _, err := c.Initialize(ctx, mcpInitRequest); err != nil {
290+ updateMCPState(name, MCPStateError, err, nil, 0)
165 slog.Error("error initializing mcp client", "error", err, "name", name)
291 slog.Error("error initializing mcp client", "error", err, "name", name)
166 _ = c.Close()
292 _ = c.Close()
167 return
293 return
@@ -170,7 +296,9 @@ func doGetMCPTools(ctx context.Context, permissions permission.Service, cfg *con
170 slog.Info("Initialized mcp client", "name", name)
296 slog.Info("Initialized mcp client", "name", name)
171 mcpClients.Set(name, c)
297 mcpClients.Set(name, c)
172
298
173− result.Append(getTools(ctx, name, permissions, c, cfg.WorkingDir())...)
299+ tools := getTools(ctx, name, permissions, c, cfg.WorkingDir())
300+ updateMCPState(name, MCPStateConnected, nil, c, len(tools))
301+ result.Append(tools...)
174 }(name, m)
302 }(name, m)
175 }
303 }
176 wg.Wait()
304 wg.Wait()
internal/llm/tools/tools.go+74−1
@@ -3,6 +3,8 @@ package tools
3import (
3import (
4 "context"
4 "context"
5 "encoding/json"
5 "encoding/json"
6+ "fmt"
7+ "strings"
6)
8)
7
9
8type ToolInfo struct {
10type ToolInfo struct {
@@ -25,6 +27,10 @@ const (
25
27
26 SessionIDContextKey sessionIDContextKey = "session_id"
28 SessionIDContextKey sessionIDContextKey = "session_id"
27 MessageIDContextKey messageIDContextKey = "message_id"
29 MessageIDContextKey messageIDContextKey = "message_id"
30+
31+ maxResponseWidth = 3000
32+ maxResponseHeight = 5000
33+ maxResponseChars = 50000
28)
34)
29
35
30type ToolResponse struct {
36type ToolResponse struct {
@@ -37,10 +43,77 @@ type ToolResponse struct {
37func NewTextResponse(content string) ToolResponse {
43func NewTextResponse(content string) ToolResponse {
38 return ToolResponse{
44 return ToolResponse{
39 Type: ToolResponseTypeText,
45 Type: ToolResponseTypeText,
40− Content: content,
46+ Content: truncateContent(content),
41 }
47 }
42}
48}
43
49
50+func truncateContent(content string) string {
51+ if len(content) <= maxResponseChars {
52+ return truncateWidthAndHeight(content)
53+ }
54+
55+ truncated := content[:maxResponseChars]
56+
57+ if lastNewline := strings.LastIndex(truncated, "\n"); lastNewline > maxResponseChars/2 {
58+ truncated = truncated[:lastNewline]
59+ }
60+
61+ truncated += "\n\n... [Content truncated due to length] ..."
62+
63+ return truncateWidthAndHeight(truncated)
64+}
65+
66+func truncateWidthAndHeight(content string) string {
67+ lines := strings.Split(content, "\n")
68+
69+ heightTruncated := false
70+ if len(lines) > maxResponseHeight {
71+ keepLines := maxResponseHeight - 3
72+ firstHalf := keepLines / 2
73+ secondHalf := keepLines - firstHalf
74+
75+ truncatedLines := make([]string, 0, maxResponseHeight)
76+ truncatedLines = append(truncatedLines, lines[:firstHalf]...)
77+ truncatedLines = append(truncatedLines, "")
78+ truncatedLines = append(truncatedLines, fmt.Sprintf("... [%d lines truncated] ...", len(lines)-keepLines))
79+ truncatedLines = append(truncatedLines, "")
80+ truncatedLines = append(truncatedLines, lines[len(lines)-secondHalf:]...)
81+
82+ lines = truncatedLines
83+ heightTruncated = true
84+ }
85+
86+ widthTruncated := false
87+ for i, line := range lines {
88+ if len(line) > maxResponseWidth {
89+ if maxResponseWidth > 20 {
90+ keepChars := maxResponseWidth - 10
91+ firstHalf := keepChars / 2
92+ secondHalf := keepChars - firstHalf
93+ lines[i] = line[:firstHalf] + " ... " + line[len(line)-secondHalf:]
94+ } else {
95+ lines[i] = line[:maxResponseWidth]
96+ }
97+ widthTruncated = true
98+ }
99+ }
100+
101+ result := strings.Join(lines, "\n")
102+
103+ if heightTruncated || widthTruncated {
104+ notices := make([]string, 0, 2)
105+ if heightTruncated {
106+ notices = append(notices, "height")
107+ }
108+ if widthTruncated {
109+ notices = append(notices, "width")
110+ }
111+ result += fmt.Sprintf("\n\n[Note: Content truncated by %s to fit response limits]", strings.Join(notices, " and "))
112+ }
113+
114+ return result
115+}
116+
44func WithResponseMetadata(response ToolResponse, metadata any) ToolResponse {
117func WithResponseMetadata(response ToolResponse, metadata any) ToolResponse {
45 if metadata != nil {
118 if metadata != nil {
46 metadataBytes, err := json.Marshal(metadata)
119 metadataBytes, err := json.Marshal(metadata)
internal/lsp/client.go+18−1
@@ -26,6 +26,12 @@ type Client struct {
26 stdout *bufio.Reader
26 stdout *bufio.Reader
27 stderr io.ReadCloser
27 stderr io.ReadCloser
28
28
29+ // Client name for identification
30+ name string
31+
32+ // Diagnostic change callback
33+ onDiagnosticsChanged func(name string, count int)
34+
29 // Request ID counter
35 // Request ID counter
30 nextID atomic.Int32
36 nextID atomic.Int32
31
37
@@ -53,7 +59,7 @@ type Client struct {
53 serverState atomic.Value
59 serverState atomic.Value
54}
60}
55
61
56−func NewClient(ctx context.Context, command string, args ...string) (*Client, error) {
62+func NewClient(ctx context.Context, name, command string, args ...string) (*Client, error) {
57 cmd := exec.CommandContext(ctx, command, args...)
63 cmd := exec.CommandContext(ctx, command, args...)
58 // Copy env
64 // Copy env
59 cmd.Env = os.Environ()
65 cmd.Env = os.Environ()
@@ -75,6 +81,7 @@ func NewClient(ctx context.Context, command string, args ...string) (*Client, er
75
81
76 client := &Client{
82 client := &Client{
77 Cmd: cmd,
83 Cmd: cmd,
84+ name: name,
78 stdin: stdin,
85 stdin: stdin,
79 stdout: bufio.NewReader(stdout),
86 stdout: bufio.NewReader(stdout),
80 stderr: stderr,
87 stderr: stderr,
@@ -284,6 +291,16 @@ func (c *Client) SetServerState(state ServerState) {
284 c.serverState.Store(state)
291 c.serverState.Store(state)
285}
292}
286
293
294+// GetName returns the name of the LSP client
295+func (c *Client) GetName() string {
296+ return c.name
297+}
298+
299+// SetDiagnosticsCallback sets the callback function for diagnostic changes
300+func (c *Client) SetDiagnosticsCallback(callback func(name string, count int)) {
301+ c.onDiagnosticsChanged = callback
302+}
303+
287// WaitForServerReady waits for the server to be ready by polling the server
304// WaitForServerReady waits for the server to be ready by polling the server
288// with a simple request until it responds successfully or times out
305// with a simple request until it responds successfully or times out
289func (c *Client) WaitForServerReady(ctx context.Context) error {
306func (c *Client) WaitForServerReady(ctx context.Context) error {
internal/lsp/handlers.go+12−2
@@ -103,7 +103,17 @@ func HandleDiagnostics(client *Client, params json.RawMessage) {
103 }
103 }
104
104
105 client.diagnosticsMu.Lock()
105 client.diagnosticsMu.Lock()
106− defer client.diagnosticsMu.Unlock()
107−
108 client.diagnostics[diagParams.URI] = diagParams.Diagnostics
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+ }
109}
119}
internal/tui/components/chat/sidebar/sidebar.go+76−411
@@ -5,7 +5,6 @@ import (
5 "fmt"
5 "fmt"
6 "os"
6 "os"
7 "slices"
7 "slices"
8− "sort"
9 "strings"
8 "strings"
10
9
11 tea "github.com/charmbracelet/bubbletea/v2"
10 tea "github.com/charmbracelet/bubbletea/v2"
@@ -13,21 +12,21 @@ import (
13 "github.com/charmbracelet/crush/internal/config"
12 "github.com/charmbracelet/crush/internal/config"
14 "github.com/charmbracelet/crush/internal/csync"
13 "github.com/charmbracelet/crush/internal/csync"
15 "github.com/charmbracelet/crush/internal/diff"
14 "github.com/charmbracelet/crush/internal/diff"
16− "github.com/charmbracelet/crush/internal/fsext"
17 "github.com/charmbracelet/crush/internal/history"
15 "github.com/charmbracelet/crush/internal/history"
18 "github.com/charmbracelet/crush/internal/lsp"
16 "github.com/charmbracelet/crush/internal/lsp"
19− "github.com/charmbracelet/crush/internal/lsp/protocol"
20 "github.com/charmbracelet/crush/internal/pubsub"
17 "github.com/charmbracelet/crush/internal/pubsub"
21 "github.com/charmbracelet/crush/internal/session"
18 "github.com/charmbracelet/crush/internal/session"
22 "github.com/charmbracelet/crush/internal/tui/components/chat"
19 "github.com/charmbracelet/crush/internal/tui/components/chat"
23 "github.com/charmbracelet/crush/internal/tui/components/core"
20 "github.com/charmbracelet/crush/internal/tui/components/core"
24 "github.com/charmbracelet/crush/internal/tui/components/core/layout"
21 "github.com/charmbracelet/crush/internal/tui/components/core/layout"
22+ "github.com/charmbracelet/crush/internal/tui/components/files"
25 "github.com/charmbracelet/crush/internal/tui/components/logo"
23 "github.com/charmbracelet/crush/internal/tui/components/logo"
24+ lspcomponent "github.com/charmbracelet/crush/internal/tui/components/lsp"
25+ "github.com/charmbracelet/crush/internal/tui/components/mcp"
26 "github.com/charmbracelet/crush/internal/tui/styles"
26 "github.com/charmbracelet/crush/internal/tui/styles"
27 "github.com/charmbracelet/crush/internal/tui/util"
27 "github.com/charmbracelet/crush/internal/tui/util"
28 "github.com/charmbracelet/crush/internal/version"
28 "github.com/charmbracelet/crush/internal/version"
29 "github.com/charmbracelet/lipgloss/v2"
29 "github.com/charmbracelet/lipgloss/v2"
30− "github.com/charmbracelet/x/ansi"
31 "golang.org/x/text/cases"
30 "golang.org/x/text/cases"
32 "golang.org/x/text/language"
31 "golang.org/x/text/language"
33)
32)
@@ -382,459 +381,125 @@ func (m *sidebarCmp) renderSectionsHorizontal() string {
382
381
383// filesBlockCompact renders the files block with limited width and height for horizontal layout
382// filesBlockCompact renders the files block with limited width and height for horizontal layout
384func (m *sidebarCmp) filesBlockCompact(maxWidth int) string {
383func (m *sidebarCmp) filesBlockCompact(maxWidth int) string {
385− t := styles.CurrentTheme()
384+ // Convert map to slice and handle type conversion
386−
387− section := t.S().Subtle.Render("Modified Files")
388−
389− files := slices.Collect(m.files.Seq())
385+ sessionFiles := slices.Collect(m.files.Seq())
390−
386+ fileSlice := make([]files.SessionFile, len(sessionFiles))
391− if len(files) == 0 {
387+ for i, sf := range sessionFiles {
392− content := lipgloss.JoinVertical(
388+ fileSlice[i] = files.SessionFile{
393− lipgloss.Left,
389+ History: files.FileHistory{
394− section,
390+ InitialVersion: sf.History.initialVersion,
395− "",
391+ LatestVersion: sf.History.latestVersion,
396− t.S().Base.Foreground(t.Border).Render("None"),
392+ },
397− )
393+ FilePath: sf.FilePath,
398− return lipgloss.NewStyle().Width(maxWidth).Render(content)
394+ Additions: sf.Additions,
395+ Deletions: sf.Deletions,
396+ }
399 }
397 }
400
398
401− fileList := []string{section, ""}
402− sort.Slice(files, func(i, j int) bool {
403− return files[i].History.latestVersion.CreatedAt > files[j].History.latestVersion.CreatedAt
404− })
405−
406− // Limit items for horizontal layout - use less space
399+ // Limit items for horizontal layout
407− maxItems := min(5, len(files))
400+ maxItems := min(5, len(fileSlice))
408 availableHeight := m.height - 8 // Reserve space for header and other content
401 availableHeight := m.height - 8 // Reserve space for header and other content
409 if availableHeight > 0 {
402 if availableHeight > 0 {
410 maxItems = min(maxItems, availableHeight)
403 maxItems = min(maxItems, availableHeight)
411 }
404 }
412
405
413− filesShown := 0
406+ return files.RenderFileBlock(fileSlice, files.RenderOptions{
414− for _, file := range files {
407+ MaxWidth: maxWidth,
415− if file.Additions == 0 && file.Deletions == 0 {
408+ MaxItems: maxItems,
416− continue
409+ ShowSection: true,
417− }
410+ SectionName: "Modified Files",
418− if filesShown >= maxItems {
411+ }, true)
419− break
420− }
421−
422− var statusParts []string
423− if file.Additions > 0 {
424− statusParts = append(statusParts, t.S().Base.Foreground(t.Success).Render(fmt.Sprintf("+%d", file.Additions)))
425− }
426− if file.Deletions > 0 {
427− statusParts = append(statusParts, t.S().Base.Foreground(t.Error).Render(fmt.Sprintf("-%d", file.Deletions)))
428− }
429−
430− extraContent := strings.Join(statusParts, " ")
431− cwd := config.Get().WorkingDir() + string(os.PathSeparator)
432− filePath := file.FilePath
433− filePath = strings.TrimPrefix(filePath, cwd)
434− filePath = fsext.DirTrim(fsext.PrettyPath(filePath), 2)
435− filePath = ansi.Truncate(filePath, maxWidth-lipgloss.Width(extraContent)-2, "…")
436−
437− fileList = append(fileList,
438− core.Status(
439− core.StatusOpts{
440− IconColor: t.FgMuted,
441− NoIcon: true,
442− Title: filePath,
443− ExtraContent: extraContent,
444− },
445− maxWidth,
446− ),
447− )
448− filesShown++
449− }
450−
451− // Add "..." indicator if there are more files
452− totalFilesWithChanges := 0
453− for _, file := range files {
454− if file.Additions > 0 || file.Deletions > 0 {
455− totalFilesWithChanges++
456− }
457− }
458− if totalFilesWithChanges > maxItems {
459− fileList = append(fileList, t.S().Base.Foreground(t.FgMuted).Render("…"))
460− }
461−
462− content := lipgloss.JoinVertical(lipgloss.Left, fileList...)
463− return lipgloss.NewStyle().Width(maxWidth).Render(content)
464}
412}
465
413
466// lspBlockCompact renders the LSP block with limited width and height for horizontal layout
414// lspBlockCompact renders the LSP block with limited width and height for horizontal layout
467func (m *sidebarCmp) lspBlockCompact(maxWidth int) string {
415func (m *sidebarCmp) lspBlockCompact(maxWidth int) string {
468− t := styles.CurrentTheme()
469−
470− section := t.S().Subtle.Render("LSPs")
471−
472− lspList := []string{section, ""}
473−
474− lsp := config.Get().LSP.Sorted()
475− if len(lsp) == 0 {
476− content := lipgloss.JoinVertical(
477− lipgloss.Left,
478− section,
479− "",
480− t.S().Base.Foreground(t.Border).Render("None"),
481− )
482− return lipgloss.NewStyle().Width(maxWidth).Render(content)
483− }
484−
485 // Limit items for horizontal layout
416 // Limit items for horizontal layout
417+ lspConfigs := config.Get().LSP.Sorted()
486− maxItems := min(5, len(lsp))
418+ maxItems := min(5, len(lspConfigs))
487 availableHeight := m.height - 8
419 availableHeight := m.height - 8
488 if availableHeight > 0 {
420 if availableHeight > 0 {
489 maxItems = min(maxItems, availableHeight)
421 maxItems = min(maxItems, availableHeight)
490 }
422 }
491
423
492− for i, l := range lsp {
424+ return lspcomponent.RenderLSPBlock(m.lspClients, lspcomponent.RenderOptions{
493− if i >= maxItems {
425+ MaxWidth: maxWidth,
494− break
426+ MaxItems: maxItems,
495− }
427+ ShowSection: true,
496−
428+ SectionName: "LSPs",
497− iconColor := t.Success
429+ }, true)
498− if l.LSP.Disabled {
499− iconColor = t.FgMuted
500− }
501−
502− lspErrs := map[protocol.DiagnosticSeverity]int{
503− protocol.SeverityError: 0,
504− protocol.SeverityWarning: 0,
505− protocol.SeverityHint: 0,
506− protocol.SeverityInformation: 0,
507− }
508− if client, ok := m.lspClients[l.Name]; ok {
509− for _, diagnostics := range client.GetDiagnostics() {
510− for _, diagnostic := range diagnostics {
511− if severity, ok := lspErrs[diagnostic.Severity]; ok {
512− lspErrs[diagnostic.Severity] = severity + 1
513− }
514− }
515− }
516− }
517−
518− errs := []string{}
519− if lspErrs[protocol.SeverityError] > 0 {
520− errs = append(errs, t.S().Base.Foreground(t.Error).Render(fmt.Sprintf("%s %d", styles.ErrorIcon, lspErrs[protocol.SeverityError])))
521− }
522− if lspErrs[protocol.SeverityWarning] > 0 {
523− errs = append(errs, t.S().Base.Foreground(t.Warning).Render(fmt.Sprintf("%s %d", styles.WarningIcon, lspErrs[protocol.SeverityWarning])))
524− }
525− if lspErrs[protocol.SeverityHint] > 0 {
526− errs = append(errs, t.S().Base.Foreground(t.FgHalfMuted).Render(fmt.Sprintf("%s %d", styles.HintIcon, lspErrs[protocol.SeverityHint])))
527− }
528− if lspErrs[protocol.SeverityInformation] > 0 {
529− errs = append(errs, t.S().Base.Foreground(t.FgHalfMuted).Render(fmt.Sprintf("%s %d", styles.InfoIcon, lspErrs[protocol.SeverityInformation])))
530− }
531−
532− lspList = append(lspList,
533− core.Status(
534− core.StatusOpts{
535− IconColor: iconColor,
536− Title: l.Name,
537− Description: l.LSP.Command,
538− ExtraContent: strings.Join(errs, " "),
539− },
540− maxWidth,
541− ),
542− )
543− }
544−
545− // Add "..." indicator if there are more LSPs
546− if len(lsp) > maxItems {
547− lspList = append(lspList, t.S().Base.Foreground(t.FgMuted).Render("…"))
548− }
549−
550− content := lipgloss.JoinVertical(lipgloss.Left, lspList...)
551− return lipgloss.NewStyle().Width(maxWidth).Render(content)
552}
430}
553
431
554// mcpBlockCompact renders the MCP block with limited width and height for horizontal layout
432// mcpBlockCompact renders the MCP block with limited width and height for horizontal layout
555func (m *sidebarCmp) mcpBlockCompact(maxWidth int) string {
433func (m *sidebarCmp) mcpBlockCompact(maxWidth int) string {
556− t := styles.CurrentTheme()
557−
558− section := t.S().Subtle.Render("MCPs")
559−
560− mcpList := []string{section, ""}
561−
562− mcps := config.Get().MCP.Sorted()
563− if len(mcps) == 0 {
564− content := lipgloss.JoinVertical(
565− lipgloss.Left,
566− section,
567− "",
568− t.S().Base.Foreground(t.Border).Render("None"),
569− )
570− return lipgloss.NewStyle().Width(maxWidth).Render(content)
571− }
572−
573 // Limit items for horizontal layout
434 // Limit items for horizontal layout
574− maxItems := min(5, len(mcps))
435+ maxItems := min(5, len(config.Get().MCP.Sorted()))
575 availableHeight := m.height - 8
436 availableHeight := m.height - 8
576 if availableHeight > 0 {
437 if availableHeight > 0 {
577 maxItems = min(maxItems, availableHeight)
438 maxItems = min(maxItems, availableHeight)
578 }
439 }
579
440
580− for i, l := range mcps {
441+ return mcp.RenderMCPBlock(mcp.RenderOptions{
581− if i >= maxItems {
442+ MaxWidth: maxWidth,
582− break
443+ MaxItems: maxItems,
583− }
444+ ShowSection: true,
584−
445+ SectionName: "MCPs",
585− iconColor := t.Success
446+ }, true)
586− if l.MCP.Disabled {
587− iconColor = t.FgMuted
588− }
589−
590− mcpList = append(mcpList,
591− core.Status(
592− core.StatusOpts{
593− IconColor: iconColor,
594− Title: l.Name,
595− Description: l.MCP.Command,
596− },
597− maxWidth,
598− ),
599− )
600− }
601−
602− // Add "..." indicator if there are more MCPs
603− if len(mcps) > maxItems {
604− mcpList = append(mcpList, t.S().Base.Foreground(t.FgMuted).Render("…"))
605− }
606−
607− content := lipgloss.JoinVertical(lipgloss.Left, mcpList...)
608− return lipgloss.NewStyle().Width(maxWidth).Render(content)
609}
447}
610
448
611func (m *sidebarCmp) filesBlock() string {
449func (m *sidebarCmp) filesBlock() string {
612− t := styles.CurrentTheme()
450+ // Convert map to slice and handle type conversion
613−
614− section := t.S().Subtle.Render(
615− core.Section("Modified Files", m.getMaxWidth()),
616− )
617−
618− files := slices.Collect(m.files.Seq())
451+ sessionFiles := slices.Collect(m.files.Seq())
619− if len(files) == 0 {
452+ fileSlice := make([]files.SessionFile, len(sessionFiles))
620− return lipgloss.JoinVertical(
453+ for i, sf := range sessionFiles {
621− lipgloss.Left,
454+ fileSlice[i] = files.SessionFile{
622− section,
455+ History: files.FileHistory{
456+ InitialVersion: sf.History.initialVersion,
457+ LatestVersion: sf.History.latestVersion,
623− "",
458+ },
624− t.S().Base.Foreground(t.Border).Render("None"),
459+ FilePath: sf.FilePath,
625− )
460+ Additions: sf.Additions,
461+ Deletions: sf.Deletions,
462+ }
626 }
463 }
627
464
628− fileList := []string{section, ""}
629− // order files by the latest version's created time
630− sort.Slice(files, func(i, j int) bool {
631− return files[i].History.latestVersion.CreatedAt > files[j].History.latestVersion.CreatedAt
632− })
633−
634 // Limit the number of files shown
465 // Limit the number of files shown
635 maxFiles, _, _ := m.getDynamicLimits()
466 maxFiles, _, _ := m.getDynamicLimits()
636− maxFiles = min(len(files), maxFiles)
467+ maxFiles = min(len(fileSlice), maxFiles)
637− filesShown := 0
468+
638−
469+ return files.RenderFileBlock(fileSlice, files.RenderOptions{
639− for _, file := range files {
470+ MaxWidth: m.getMaxWidth(),
640− if file.Additions == 0 && file.Deletions == 0 {
471+ MaxItems: maxFiles,
641− continue // skip files with no changes
472+ ShowSection: true,
642− }
473+ SectionName: core.Section("Modified Files", m.getMaxWidth()),
643− if filesShown >= maxFiles {
474+ }, true)
644− break
645− }
646−
647− var statusParts []string
648− if file.Additions > 0 {
649− statusParts = append(statusParts, t.S().Base.Foreground(t.Success).Render(fmt.Sprintf("+%d", file.Additions)))
650− }
651− if file.Deletions > 0 {
652− statusParts = append(statusParts, t.S().Base.Foreground(t.Error).Render(fmt.Sprintf("-%d", file.Deletions)))
653− }
654−
655− extraContent := strings.Join(statusParts, " ")
656− cwd := config.Get().WorkingDir() + string(os.PathSeparator)
657− filePath := file.FilePath
658− filePath = strings.TrimPrefix(filePath, cwd)
659− filePath = fsext.DirTrim(fsext.PrettyPath(filePath), 2)
660− filePath = ansi.Truncate(filePath, m.getMaxWidth()-lipgloss.Width(extraContent)-2, "…")
661− fileList = append(fileList,
662− core.Status(
663− core.StatusOpts{
664− IconColor: t.FgMuted,
665− NoIcon: true,
666− Title: filePath,
667− ExtraContent: extraContent,
668− },
669− m.getMaxWidth(),
670− ),
671− )
672− filesShown++
673− }
674−
675− // Add indicator if there are more files
676− totalFilesWithChanges := 0
677− for _, file := range files {
678− if file.Additions > 0 || file.Deletions > 0 {
679− totalFilesWithChanges++
680− }
681− }
682− if totalFilesWithChanges > maxFiles {
683− remaining := totalFilesWithChanges - maxFiles
684− fileList = append(fileList,
685− t.S().Base.Foreground(t.FgSubtle).Render(fmt.Sprintf("…and %d more", remaining)),
686− )
687− }
688−
689− return lipgloss.JoinVertical(
690− lipgloss.Left,
691− fileList...,
692− )
693}
475}
694
476
695func (m *sidebarCmp) lspBlock() string {
477func (m *sidebarCmp) lspBlock() string {
696− t := styles.CurrentTheme()
697−
698− section := t.S().Subtle.Render(
699− core.Section("LSPs", m.getMaxWidth()),
700− )
701−
702− lspList := []string{section, ""}
703−
704− lsp := config.Get().LSP.Sorted()
705− if len(lsp) == 0 {
706− return lipgloss.JoinVertical(
707− lipgloss.Left,
708− section,
709− "",
710− t.S().Base.Foreground(t.Border).Render("None"),
711− )
712− }
713−
714 // Limit the number of LSPs shown
478 // Limit the number of LSPs shown
715 _, maxLSPs, _ := m.getDynamicLimits()
479 _, maxLSPs, _ := m.getDynamicLimits()
480+ lspConfigs := config.Get().LSP.Sorted()
716− maxLSPs = min(len(lsp), maxLSPs)
481+ maxLSPs = min(len(lspConfigs), maxLSPs)
717− for i, l := range lsp {
482+
718− if i >= maxLSPs {
483+ return lspcomponent.RenderLSPBlock(m.lspClients, lspcomponent.RenderOptions{
719− break
484+ MaxWidth: m.getMaxWidth(),
720− }
485+ MaxItems: maxLSPs,
721−
486+ ShowSection: true,
722− iconColor := t.Success
487+ SectionName: core.Section("LSPs", m.getMaxWidth()),
723− if l.LSP.Disabled {
488+ }, true)
724− iconColor = t.FgMuted
725− }
726− lspErrs := map[protocol.DiagnosticSeverity]int{
727− protocol.SeverityError: 0,
728− protocol.SeverityWarning: 0,
729− protocol.SeverityHint: 0,
730− protocol.SeverityInformation: 0,
731− }
732− if client, ok := m.lspClients[l.Name]; ok {
733− for _, diagnostics := range client.GetDiagnostics() {
734− for _, diagnostic := range diagnostics {
735− if severity, ok := lspErrs[diagnostic.Severity]; ok {
736− lspErrs[diagnostic.Severity] = severity + 1
737− }
738− }
739− }
740− }
741−
742− errs := []string{}
743− if lspErrs[protocol.SeverityError] > 0 {
744− errs = append(errs, t.S().Base.Foreground(t.Error).Render(fmt.Sprintf("%s %d", styles.ErrorIcon, lspErrs[protocol.SeverityError])))
745− }
746− if lspErrs[protocol.SeverityWarning] > 0 {
747− errs = append(errs, t.S().Base.Foreground(t.Warning).Render(fmt.Sprintf("%s %d", styles.WarningIcon, lspErrs[protocol.SeverityWarning])))
748− }
749− if lspErrs[protocol.SeverityHint] > 0 {
750− errs = append(errs, t.S().Base.Foreground(t.FgHalfMuted).Render(fmt.Sprintf("%s %d", styles.HintIcon, lspErrs[protocol.SeverityHint])))
751− }
752− if lspErrs[protocol.SeverityInformation] > 0 {
753− errs = append(errs, t.S().Base.Foreground(t.FgHalfMuted).Render(fmt.Sprintf("%s %d", styles.InfoIcon, lspErrs[protocol.SeverityInformation])))
754− }
755−
756− lspList = append(lspList,
757− core.Status(
758− core.StatusOpts{
759− IconColor: iconColor,
760− Title: l.Name,
761− Description: l.LSP.Command,
762− ExtraContent: strings.Join(errs, " "),
763− },
764− m.getMaxWidth(),
765− ),
766− )
767− }
768−
769− // Add indicator if there are more LSPs
770− if len(lsp) > maxLSPs {
771− remaining := len(lsp) - maxLSPs
772− lspList = append(lspList,
773− t.S().Base.Foreground(t.FgSubtle).Render(fmt.Sprintf("…and %d more", remaining)),
774− )
775− }
776−
777− return lipgloss.JoinVertical(
778− lipgloss.Left,
779− lspList...,
780− )
781}
489}
782
490
783func (m *sidebarCmp) mcpBlock() string {
491func (m *sidebarCmp) mcpBlock() string {
784− t := styles.CurrentTheme()
785−
786− section := t.S().Subtle.Render(
787− core.Section("MCPs", m.getMaxWidth()),
788− )
789−
790− mcpList := []string{section, ""}
791−
792− mcps := config.Get().MCP.Sorted()
793− if len(mcps) == 0 {
794− return lipgloss.JoinVertical(
795− lipgloss.Left,
796− section,
797− "",
798− t.S().Base.Foreground(t.Border).Render("None"),
799− )
800− }
801−
802 // Limit the number of MCPs shown
492 // Limit the number of MCPs shown
803 _, _, maxMCPs := m.getDynamicLimits()
493 _, _, maxMCPs := m.getDynamicLimits()
494+ mcps := config.Get().MCP.Sorted()
804 maxMCPs = min(len(mcps), maxMCPs)
495 maxMCPs = min(len(mcps), maxMCPs)
805− for i, l := range mcps {
806− if i >= maxMCPs {
807− break
808− }
809−
810− iconColor := t.Success
811− if l.MCP.Disabled {
812− iconColor = t.FgMuted
813− }
814− mcpList = append(mcpList,
815− core.Status(
816− core.StatusOpts{
817− IconColor: iconColor,
818− Title: l.Name,
819− Description: l.MCP.Command,
820− },
821− m.getMaxWidth(),
822− ),
823− )
824− }
825−
826− // Add indicator if there are more MCPs
827− if len(mcps) > maxMCPs {
828− remaining := len(mcps) - maxMCPs
829− mcpList = append(mcpList,
830− t.S().Base.Foreground(t.FgSubtle).Render(fmt.Sprintf("…and %d more", remaining)),
831− )
832− }
833
496
834− return lipgloss.JoinVertical(
497+ return mcp.RenderMCPBlock(mcp.RenderOptions{
835− lipgloss.Left,
498+ MaxWidth: m.getMaxWidth(),
836− mcpList...,
499+ MaxItems: maxMCPs,
837− )
500+ ShowSection: true,
501+ SectionName: core.Section("MCPs", m.getMaxWidth()),
502+ }, true)
838}
503}
839
504
840func formatTokensAndCost(tokens, contextWindow int64, cost float64) string {
505func formatTokensAndCost(tokens, contextWindow int64, cost float64) string {
internal/tui/components/chat/splash/splash.go+11−47
@@ -17,6 +17,8 @@ import (
17 "github.com/charmbracelet/crush/internal/tui/components/core/layout"
17 "github.com/charmbracelet/crush/internal/tui/components/core/layout"
18 "github.com/charmbracelet/crush/internal/tui/components/dialogs/models"
18 "github.com/charmbracelet/crush/internal/tui/components/dialogs/models"
19 "github.com/charmbracelet/crush/internal/tui/components/logo"
19 "github.com/charmbracelet/crush/internal/tui/components/logo"
20+ lspcomponent "github.com/charmbracelet/crush/internal/tui/components/lsp"
21+ "github.com/charmbracelet/crush/internal/tui/components/mcp"
20 "github.com/charmbracelet/crush/internal/tui/exp/list"
22 "github.com/charmbracelet/crush/internal/tui/exp/list"
21 "github.com/charmbracelet/crush/internal/tui/styles"
23 "github.com/charmbracelet/crush/internal/tui/styles"
22 "github.com/charmbracelet/crush/internal/tui/util"
24 "github.com/charmbracelet/crush/internal/tui/util"
@@ -633,7 +635,7 @@ func (s *splashCmp) Bindings() []key.Binding {
633}
635}
634
636
635func (s *splashCmp) getMaxInfoWidth() int {
637func (s *splashCmp) getMaxInfoWidth() int {
636− return min(s.width-2, 40) // 2 for left padding
638+ return min(s.width-2, 90) // 2 for left padding
637}
639}
638
640
639func (s *splashCmp) cwd() string {
641func (s *splashCmp) cwd() string {
@@ -648,29 +650,10 @@ func (s *splashCmp) cwd() string {
648}
650}
649
651
650func LSPList(maxWidth int) []string {
652func LSPList(maxWidth int) []string {
651− t := styles.CurrentTheme()
653+ return lspcomponent.RenderLSPList(nil, lspcomponent.RenderOptions{
652− lspList := []string{}
653− lsp := config.Get().LSP.Sorted()
654− if len(lsp) == 0 {
655− return []string{t.S().Base.Foreground(t.Border).Render("None")}
656− }
657− for _, l := range lsp {
658− iconColor := t.Success
659− if l.LSP.Disabled {
660− iconColor = t.FgMuted
661− }
662− lspList = append(lspList,
663− core.Status(
664− core.StatusOpts{
665− IconColor: iconColor,
666− Title: l.Name,
667− Description: l.LSP.Command,
668− },
669− maxWidth,
654+ MaxWidth: maxWidth,
670− ),
655+ ShowSection: false,
671− )
672− }
656+ })
673− return lspList
674}
657}
675
658
676func (s *splashCmp) lspBlock() string {
659func (s *splashCmp) lspBlock() string {
@@ -687,29 +670,10 @@ func (s *splashCmp) lspBlock() string {
687}
670}
688
671
689func MCPList(maxWidth int) []string {
672func MCPList(maxWidth int) []string {
690− t := styles.CurrentTheme()
673+ return mcp.RenderMCPList(mcp.RenderOptions{
691− mcpList := []string{}
692− mcps := config.Get().MCP.Sorted()
693− if len(mcps) == 0 {
694− return []string{t.S().Base.Foreground(t.Border).Render("None")}
695− }
696− for _, l := range mcps {
697− iconColor := t.Success
698− if l.MCP.Disabled {
699− iconColor = t.FgMuted
700− }
701− mcpList = append(mcpList,
702− core.Status(
703− core.StatusOpts{
704− IconColor: iconColor,
705− Title: l.Name,
706− Description: l.MCP.Command,
707− },
708− maxWidth,
674+ MaxWidth: maxWidth,
709− ),
675+ ShowSection: false,
710− )
711− }
676+ })
712− return mcpList
713}
677}
714
678
715func (s *splashCmp) mcpBlock() string {
679func (s *splashCmp) mcpBlock() string {
internal/tui/components/dialogs/commands/commands.go+4−2
@@ -119,7 +119,10 @@ func (c *commandDialogCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
119 case tea.WindowSizeMsg:
119 case tea.WindowSizeMsg:
120 c.wWidth = msg.Width
120 c.wWidth = msg.Width
121 c.wHeight = msg.Height
121 c.wHeight = msg.Height
122+ return c, tea.Batch(
123+ c.SetCommandType(c.commandType),
122− return c, c.commandList.SetSize(c.listWidth(), c.listHeight())
124+ c.commandList.SetSize(c.listWidth(), c.listHeight()),
125+ )
123 case tea.KeyPressMsg:
126 case tea.KeyPressMsg:
124 switch {
127 switch {
125 case key.Matches(msg, c.keyMap.Select):
128 case key.Matches(msg, c.keyMap.Select):
@@ -318,7 +321,6 @@ func (c *commandDialogCmp) defaultCommands() []Command {
318 })
321 })
319 }
322 }
320 }
323 }
321−
322 // Only show toggle compact mode command if window width is larger than compact breakpoint (90)
324 // Only show toggle compact mode command if window width is larger than compact breakpoint (90)
323 if c.wWidth > 120 && c.sessionID != "" {
325 if c.wWidth > 120 && c.sessionID != "" {
324 commands = append(commands, Command{
326 commands = append(commands, Command{
internal/tui/components/files/files.gonew file+145
@@ -0,0 +1,145 @@
1+package files
2+
3+import (
4+ "fmt"
5+ "os"
6+ "sort"
7+ "strings"
8+
9+ "github.com/charmbracelet/lipgloss/v2"
10+ "github.com/charmbracelet/x/ansi"
11+
12+ "github.com/charmbracelet/crush/internal/config"
13+ "github.com/charmbracelet/crush/internal/fsext"
14+ "github.com/charmbracelet/crush/internal/history"
15+ "github.com/charmbracelet/crush/internal/tui/components/core"
16+ "github.com/charmbracelet/crush/internal/tui/styles"
17+)
18+
19+// FileHistory represents a file history with initial and latest versions.
20+type FileHistory struct {
21+ InitialVersion history.File
22+ LatestVersion history.File
23+}
24+
25+// SessionFile represents a file with its history information.
26+type SessionFile struct {
27+ History FileHistory
28+ FilePath string
29+ Additions int
30+ Deletions int
31+}
32+
33+// RenderOptions contains options for rendering file lists.
34+type RenderOptions struct {
35+ MaxWidth int
36+ MaxItems int
37+ ShowSection bool
38+ SectionName string
39+}
40+
41+// RenderFileList renders a list of file status items with the given options.
42+func RenderFileList(fileSlice []SessionFile, opts RenderOptions) []string {
43+ t := styles.CurrentTheme()
44+ fileList := []string{}
45+
46+ if opts.ShowSection {
47+ sectionName := opts.SectionName
48+ if sectionName == "" {
49+ sectionName = "Modified Files"
50+ }
51+ section := t.S().Subtle.Render(sectionName)
52+ fileList = append(fileList, section, "")
53+ }
54+
55+ if len(fileSlice) == 0 {
56+ fileList = append(fileList, t.S().Base.Foreground(t.Border).Render("None"))
57+ return fileList
58+ }
59+
60+ // Sort files by the latest version's created time
61+ sort.Slice(fileSlice, func(i, j int) bool {
62+ if fileSlice[i].History.LatestVersion.CreatedAt == fileSlice[j].History.LatestVersion.CreatedAt {
63+ return strings.Compare(fileSlice[i].FilePath, fileSlice[j].FilePath) < 0
64+ }
65+ return fileSlice[i].History.LatestVersion.CreatedAt > fileSlice[j].History.LatestVersion.CreatedAt
66+ })
67+
68+ // Determine how many items to show
69+ maxItems := len(fileSlice)
70+ if opts.MaxItems > 0 {
71+ maxItems = min(opts.MaxItems, len(fileSlice))
72+ }
73+
74+ filesShown := 0
75+ for _, file := range fileSlice {
76+ if file.Additions == 0 && file.Deletions == 0 {
77+ continue // skip files with no changes
78+ }
79+ if filesShown >= maxItems {
80+ break
81+ }
82+
83+ var statusParts []string
84+ if file.Additions > 0 {
85+ statusParts = append(statusParts, t.S().Base.Foreground(t.Success).Render(fmt.Sprintf("+%d", file.Additions)))
86+ }
87+ if file.Deletions > 0 {
88+ statusParts = append(statusParts, t.S().Base.Foreground(t.Error).Render(fmt.Sprintf("-%d", file.Deletions)))
89+ }
90+
91+ extraContent := strings.Join(statusParts, " ")
92+ cwd := config.Get().WorkingDir() + string(os.PathSeparator)
93+ filePath := file.FilePath
94+ filePath = strings.TrimPrefix(filePath, cwd)
95+ filePath = fsext.DirTrim(fsext.PrettyPath(filePath), 2)
96+ filePath = ansi.Truncate(filePath, opts.MaxWidth-lipgloss.Width(extraContent)-2, "…")
97+
98+ fileList = append(fileList,
99+ core.Status(
100+ core.StatusOpts{
101+ IconColor: t.FgMuted,
102+ NoIcon: true,
103+ Title: filePath,
104+ ExtraContent: extraContent,
105+ },
106+ opts.MaxWidth,
107+ ),
108+ )
109+ filesShown++
110+ }
111+
112+ return fileList
113+}
114+
115+// RenderFileBlock renders a complete file block with optional truncation indicator.
116+func RenderFileBlock(fileSlice []SessionFile, opts RenderOptions, showTruncationIndicator bool) string {
117+ t := styles.CurrentTheme()
118+ fileList := RenderFileList(fileSlice, opts)
119+
120+ // Add truncation indicator if needed
121+ if showTruncationIndicator && opts.MaxItems > 0 {
122+ totalFilesWithChanges := 0
123+ for _, file := range fileSlice {
124+ if file.Additions > 0 || file.Deletions > 0 {
125+ totalFilesWithChanges++
126+ }
127+ }
128+ if totalFilesWithChanges > opts.MaxItems {
129+ remaining := totalFilesWithChanges - opts.MaxItems
130+ if remaining == 1 {
131+ fileList = append(fileList, t.S().Base.Foreground(t.FgMuted).Render("…"))
132+ } else {
133+ fileList = append(fileList,
134+ t.S().Base.Foreground(t.FgSubtle).Render(fmt.Sprintf("…and %d more", remaining)),
135+ )
136+ }
137+ }
138+ }
139+
140+ content := lipgloss.JoinVertical(lipgloss.Left, fileList...)
141+ if opts.MaxWidth > 0 {
142+ return lipgloss.NewStyle().Width(opts.MaxWidth).Render(content)
143+ }
144+ return content
145+}
internal/tui/components/lsp/lsp.gonew file+160
@@ -0,0 +1,160 @@
1+package lsp
2+
3+import (
4+ "fmt"
5+ "strings"
6+
7+ "github.com/charmbracelet/lipgloss/v2"
8+
9+ "github.com/charmbracelet/crush/internal/app"
10+ "github.com/charmbracelet/crush/internal/config"
11+ "github.com/charmbracelet/crush/internal/lsp"
12+ "github.com/charmbracelet/crush/internal/lsp/protocol"
13+ "github.com/charmbracelet/crush/internal/tui/components/core"
14+ "github.com/charmbracelet/crush/internal/tui/styles"
15+)
16+
17+// RenderOptions contains options for rendering LSP lists.
18+type RenderOptions struct {
19+ MaxWidth int
20+ MaxItems int
21+ ShowSection bool
22+ SectionName string
23+}
24+
25+// RenderLSPList renders a list of LSP status items with the given options.
26+func RenderLSPList(lspClients map[string]*lsp.Client, opts RenderOptions) []string {
27+ t := styles.CurrentTheme()
28+ lspList := []string{}
29+
30+ if opts.ShowSection {
31+ sectionName := opts.SectionName
32+ if sectionName == "" {
33+ sectionName = "LSPs"
34+ }
35+ section := t.S().Subtle.Render(sectionName)
36+ lspList = append(lspList, section, "")
37+ }
38+
39+ lspConfigs := config.Get().LSP.Sorted()
40+ if len(lspConfigs) == 0 {
41+ lspList = append(lspList, t.S().Base.Foreground(t.Border).Render("None"))
42+ return lspList
43+ }
44+
45+ // Get LSP states
46+ lspStates := app.GetLSPStates()
47+
48+ // Determine how many items to show
49+ maxItems := len(lspConfigs)
50+ if opts.MaxItems > 0 {
51+ maxItems = min(opts.MaxItems, len(lspConfigs))
52+ }
53+
54+ for i, l := range lspConfigs {
55+ if i >= maxItems {
56+ break
57+ }
58+
59+ // Determine icon color and description based on state
60+ iconColor := t.FgMuted
61+ description := l.LSP.Command
62+
63+ if l.LSP.Disabled {
64+ iconColor = t.FgMuted
65+ description = t.S().Subtle.Render("disabled")
66+ } else if state, exists := lspStates[l.Name]; exists {
67+ switch state.State {
68+ case lsp.StateStarting:
69+ iconColor = t.Yellow
70+ description = t.S().Subtle.Render("starting...")
71+ case lsp.StateReady:
72+ iconColor = t.Success
73+ description = l.LSP.Command
74+ case lsp.StateError:
75+ iconColor = t.Red
76+ if state.Error != nil {
77+ description = t.S().Subtle.Render(fmt.Sprintf("error: %s", state.Error.Error()))
78+ } else {
79+ description = t.S().Subtle.Render("error")
80+ }
81+ }
82+ }
83+
84+ // Calculate diagnostic counts if we have LSP clients
85+ var extraContent string
86+ if lspClients != nil {
87+ lspErrs := map[protocol.DiagnosticSeverity]int{
88+ protocol.SeverityError: 0,
89+ protocol.SeverityWarning: 0,
90+ protocol.SeverityHint: 0,
91+ protocol.SeverityInformation: 0,
92+ }
93+ if client, ok := lspClients[l.Name]; ok {
94+ for _, diagnostics := range client.GetDiagnostics() {
95+ for _, diagnostic := range diagnostics {
96+ if severity, ok := lspErrs[diagnostic.Severity]; ok {
97+ lspErrs[diagnostic.Severity] = severity + 1
98+ }
99+ }
100+ }
101+ }
102+
103+ errs := []string{}
104+ if lspErrs[protocol.SeverityError] > 0 {
105+ errs = append(errs, t.S().Base.Foreground(t.Error).Render(fmt.Sprintf("%s %d", styles.ErrorIcon, lspErrs[protocol.SeverityError])))
106+ }
107+ if lspErrs[protocol.SeverityWarning] > 0 {
108+ errs = append(errs, t.S().Base.Foreground(t.Warning).Render(fmt.Sprintf("%s %d", styles.WarningIcon, lspErrs[protocol.SeverityWarning])))
109+ }
110+ if lspErrs[protocol.SeverityHint] > 0 {
111+ errs = append(errs, t.S().Base.Foreground(t.FgHalfMuted).Render(fmt.Sprintf("%s %d", styles.HintIcon, lspErrs[protocol.SeverityHint])))
112+ }
113+ if lspErrs[protocol.SeverityInformation] > 0 {
114+ errs = append(errs, t.S().Base.Foreground(t.FgHalfMuted).Render(fmt.Sprintf("%s %d", styles.InfoIcon, lspErrs[protocol.SeverityInformation])))
115+ }
116+ extraContent = strings.Join(errs, " ")
117+ }
118+
119+ lspList = append(lspList,
120+ core.Status(
121+ core.StatusOpts{
122+ IconColor: iconColor,
123+ Title: l.Name,
124+ Description: description,
125+ ExtraContent: extraContent,
126+ },
127+ opts.MaxWidth,
128+ ),
129+ )
130+ }
131+
132+ return lspList
133+}
134+
135+// RenderLSPBlock renders a complete LSP block with optional truncation indicator.
136+func RenderLSPBlock(lspClients map[string]*lsp.Client, opts RenderOptions, showTruncationIndicator bool) string {
137+ t := styles.CurrentTheme()
138+ lspList := RenderLSPList(lspClients, opts)
139+
140+ // Add truncation indicator if needed
141+ if showTruncationIndicator && opts.MaxItems > 0 {
142+ lspConfigs := config.Get().LSP.Sorted()
143+ if len(lspConfigs) > opts.MaxItems {
144+ remaining := len(lspConfigs) - opts.MaxItems
145+ if remaining == 1 {
146+ lspList = append(lspList, t.S().Base.Foreground(t.FgMuted).Render("…"))
147+ } else {
148+ lspList = append(lspList,
149+ t.S().Base.Foreground(t.FgSubtle).Render(fmt.Sprintf("…and %d more", remaining)),
150+ )
151+ }
152+ }
153+ }
154+
155+ content := lipgloss.JoinVertical(lipgloss.Left, lspList...)
156+ if opts.MaxWidth > 0 {
157+ return lipgloss.NewStyle().Width(opts.MaxWidth).Render(content)
158+ }
159+ return content
160+}
internal/tui/components/mcp/mcp.gonew file+128
@@ -0,0 +1,128 @@
1+package mcp
2+
3+import (
4+ "fmt"
5+
6+ "github.com/charmbracelet/lipgloss/v2"
7+
8+ "github.com/charmbracelet/crush/internal/config"
9+ "github.com/charmbracelet/crush/internal/llm/agent"
10+ "github.com/charmbracelet/crush/internal/tui/components/core"
11+ "github.com/charmbracelet/crush/internal/tui/styles"
12+)
13+
14+// RenderOptions contains options for rendering MCP lists.
15+type RenderOptions struct {
16+ MaxWidth int
17+ MaxItems int
18+ ShowSection bool
19+ SectionName string
20+}
21+
22+// RenderMCPList renders a list of MCP status items with the given options.
23+func RenderMCPList(opts RenderOptions) []string {
24+ t := styles.CurrentTheme()
25+ mcpList := []string{}
26+
27+ if opts.ShowSection {
28+ sectionName := opts.SectionName
29+ if sectionName == "" {
30+ sectionName = "MCPs"
31+ }
32+ section := t.S().Subtle.Render(sectionName)
33+ mcpList = append(mcpList, section, "")
34+ }
35+
36+ mcps := config.Get().MCP.Sorted()
37+ if len(mcps) == 0 {
38+ mcpList = append(mcpList, t.S().Base.Foreground(t.Border).Render("None"))
39+ return mcpList
40+ }
41+
42+ // Get MCP states
43+ mcpStates := agent.GetMCPStates()
44+
45+ // Determine how many items to show
46+ maxItems := len(mcps)
47+ if opts.MaxItems > 0 {
48+ maxItems = min(opts.MaxItems, len(mcps))
49+ }
50+
51+ for i, l := range mcps {
52+ if i >= maxItems {
53+ break
54+ }
55+
56+ // Determine icon and color based on state
57+ iconColor := t.FgMuted
58+ description := l.MCP.Command
59+ extraContent := ""
60+
61+ if state, exists := mcpStates[l.Name]; exists {
62+ switch state.State {
63+ case agent.MCPStateDisabled:
64+ iconColor = t.FgMuted
65+ description = t.S().Subtle.Render("disabled")
66+ case agent.MCPStateStarting:
67+ iconColor = t.Yellow
68+ description = t.S().Subtle.Render("starting...")
69+ case agent.MCPStateConnected:
70+ iconColor = t.Success
71+ if state.ToolCount > 0 {
72+ extraContent = t.S().Subtle.Render(fmt.Sprintf("(%d tools)", state.ToolCount))
73+ }
74+ case agent.MCPStateError:
75+ iconColor = t.Red
76+ if state.Error != nil {
77+ description = t.S().Subtle.Render(fmt.Sprintf("error: %s", state.Error.Error()))
78+ } else {
79+ description = t.S().Subtle.Render("error")
80+ }
81+ }
82+ } else if l.MCP.Disabled {
83+ iconColor = t.FgMuted
84+ description = t.S().Subtle.Render("disabled")
85+ }
86+
87+ mcpList = append(mcpList,
88+ core.Status(
89+ core.StatusOpts{
90+ IconColor: iconColor,
91+ Title: l.Name,
92+ Description: description,
93+ ExtraContent: extraContent,
94+ },
95+ opts.MaxWidth,
96+ ),
97+ )
98+ }
99+
100+ return mcpList
101+}
102+
103+// RenderMCPBlock renders a complete MCP block with optional truncation indicator.
104+func RenderMCPBlock(opts RenderOptions, showTruncationIndicator bool) string {
105+ t := styles.CurrentTheme()
106+ mcpList := RenderMCPList(opts)
107+
108+ // Add truncation indicator if needed
109+ if showTruncationIndicator && opts.MaxItems > 0 {
110+ mcps := config.Get().MCP.Sorted()
111+ if len(mcps) > opts.MaxItems {
112+ remaining := len(mcps) - opts.MaxItems
113+ if remaining == 1 {
114+ mcpList = append(mcpList, t.S().Base.Foreground(t.FgMuted).Render("…"))
115+ } else {
116+ mcpList = append(mcpList,
117+ t.S().Base.Foreground(t.FgSubtle).Render(fmt.Sprintf("…and %d more", remaining)),
118+ )
119+ }
120+ }
121+ }
122+
123+ content := lipgloss.JoinVertical(lipgloss.Left, mcpList...)
124+ if opts.MaxWidth > 0 {
125+ return lipgloss.NewStyle().Width(opts.MaxWidth).Render(content)
126+ }
127+ return content
128+}
internal/tui/exp/list/list.go+9−2
@@ -3,6 +3,7 @@ package list
3import (
3import (
4 "slices"
4 "slices"
5 "strings"
5 "strings"
6+ "sync"
6
7
7 "github.com/charmbracelet/bubbles/v2/key"
8 "github.com/charmbracelet/bubbles/v2/key"
8 tea "github.com/charmbracelet/bubbletea/v2"
9 tea "github.com/charmbracelet/bubbletea/v2"
@@ -90,6 +91,7 @@ type list[T Item] struct {
90
91
91 renderedItems *csync.Map[string, renderedItem]
92 renderedItems *csync.Map[string, renderedItem]
92
93
94+ renderMu sync.Mutex
93 rendered string
95 rendered string
94
96
95 movingByItem bool
97 movingByItem bool
@@ -328,7 +330,9 @@ func (l *list[T]) render() tea.Cmd {
328 // we are not rendering the first time
330 // we are not rendering the first time
329 if l.rendered != "" {
331 if l.rendered != "" {
330 // rerender everything will mostly hit cache
332 // rerender everything will mostly hit cache
333+ l.renderMu.Lock()
331 l.rendered, _ = l.renderIterator(0, false, "")
334 l.rendered, _ = l.renderIterator(0, false, "")
335+ l.renderMu.Unlock()
332 if l.direction == DirectionBackward {
336 if l.direction == DirectionBackward {
333 l.recalculateItemPositions()
337 l.recalculateItemPositions()
334 }
338 }
@@ -338,9 +342,10 @@ func (l *list[T]) render() tea.Cmd {
338 }
342 }
339 return focusChangeCmd
343 return focusChangeCmd
340 }
344 }
345+ l.renderMu.Lock()
341 rendered, finishIndex := l.renderIterator(0, true, "")
346 rendered, finishIndex := l.renderIterator(0, true, "")
342 l.rendered = rendered
347 l.rendered = rendered
343−
348+ l.renderMu.Unlock()
344 // recalculate for the initial items
349 // recalculate for the initial items
345 if l.direction == DirectionBackward {
350 if l.direction == DirectionBackward {
346 l.recalculateItemPositions()
351 l.recalculateItemPositions()
@@ -348,7 +353,10 @@ func (l *list[T]) render() tea.Cmd {
348 renderCmd := func() tea.Msg {
353 renderCmd := func() tea.Msg {
349 l.offset = 0
354 l.offset = 0
350 // render the rest
355 // render the rest
356+
357+ l.renderMu.Lock()
351 l.rendered, _ = l.renderIterator(finishIndex, false, l.rendered)
358 l.rendered, _ = l.renderIterator(finishIndex, false, l.rendered)
359+ l.renderMu.Unlock()
352 // needed for backwards
360 // needed for backwards
353 if l.direction == DirectionBackward {
361 if l.direction == DirectionBackward {
354 l.recalculateItemPositions()
362 l.recalculateItemPositions()
@@ -357,7 +365,6 @@ func (l *list[T]) render() tea.Cmd {
357 if l.focused {
365 if l.focused {
358 l.scrollToSelection()
366 l.scrollToSelection()
359 }
367 }
360−
361 return nil
368 return nil
362 }
369 }
363 return tea.Batch(focusChangeCmd, renderCmd)
370 return tea.Batch(focusChangeCmd, renderCmd)