on main help sign in
Merge remote-tracking branch 'origin/list' into tool_improvements
commit1da73eaed5c278d43f3bcfe6adb633fa83f34acd authorKujtim Hoxha <kujtimii.h@gmail.com> dateMon 28 Jul 2025, 09:28 (1 year ago) parentfd19d848e4a2ce
14 files changed+353−140
README.md+1 internal/app/app.go+5−5 internal/app/lsp.go+1−3 internal/config/config.go+1−1 internal/csync/maps.go+20 internal/csync/maps_test.go+225 internal/csync/slices.go+11−2 internal/csync/slices_test.go+3−4 internal/llm/agent/agent.go+23−32 internal/llm/agent/mcp-tools.go+7−12 internal/llm/prompt/prompt.go+6−18 internal/lsp/watcher/watcher.go+7−12 internal/permission/permission.go+11−9 internal/tui/components/chat/sidebar/sidebar.go+32−42
README.md+1
@@ -4,6 +4,7 @@
44# Crush
55
66<p>
7+ <img width="450" alt="Charm Crush Art" src="https://github.com/user-attachments/assets/9ab4c30c-9327-46b6-a722-3ad0e20f6976" /><br>
78 <a href="https://github.com/charmbracelet/crush/releases"><img src="https://img.shields.io/github/release/charmbracelet/crush" alt="Latest Release"></a>
89 <a href="https://github.com/charmbracelet/crush/actions"><img src="https://github.com/charmbracelet/crush/workflows/build/badge.svg" alt="Build Status"></a>
910</p>
internal/app/app.go+5−5
@@ -12,6 +12,7 @@ import (
1212
1313 tea "github.com/charmbracelet/bubbletea/v2"
1414 "github.com/charmbracelet/crush/internal/config"
15+ "github.com/charmbracelet/crush/internal/csync"
1516 "github.com/charmbracelet/crush/internal/db"
1617 "github.com/charmbracelet/crush/internal/format"
1718 "github.com/charmbracelet/crush/internal/history"
@@ -37,8 +38,7 @@ type App struct {
3738
3839 clientsMutex sync.RWMutex
3940
40− watcherCancelFuncs []context.CancelFunc
41− cancelFuncsMutex sync.Mutex
41+ watcherCancelFuncs *csync.Slice[context.CancelFunc]
4242 lspWatcherWG sync.WaitGroup
4343
4444 config *config.Config
@@ -76,6 +76,8 @@ func New(ctx context.Context, conn *sql.DB, cfg *config.Config) (*App, error) {
7676
7777 config: cfg,
7878
79+ watcherCancelFuncs: csync.NewSlice[context.CancelFunc](),
80+
7981 events: make(chan tea.Msg, 100),
8082 serviceEventsWG: &sync.WaitGroup{},
8183 tuiWG: &sync.WaitGroup{},
@@ -306,11 +308,9 @@ func (app *App) Shutdown() {
306308 app.CoderAgent.CancelAll()
307309 }
308310
309− app.cancelFuncsMutex.Lock()
310− for _, cancel := range app.watcherCancelFuncs {
311+ for cancel := range app.watcherCancelFuncs.Seq() {
311312 cancel()
312313 }
313− app.cancelFuncsMutex.Unlock()
314314
315315 // Wait for all LSP watchers to finish.
316316 app.lspWatcherWG.Wait()
internal/app/lsp.go+1−3
@@ -63,9 +63,7 @@ func (app *App) createAndStartLSPClient(ctx context.Context, name string, comman
6363 workspaceWatcher := watcher.NewWorkspaceWatcher(name, lspClient)
6464
6565 // Store the cancel function to be called during cleanup.
66− app.cancelFuncsMutex.Lock()
67− app.watcherCancelFuncs = append(app.watcherCancelFuncs, cancelFunc)
68− app.cancelFuncsMutex.Unlock()
66+ app.watcherCancelFuncs.Append(cancelFunc)
6967
7068 // Add to map with mutex protection before starting goroutine
7169 app.clientsMutex.Lock()
internal/config/config.go+1−1
@@ -270,7 +270,7 @@ func (c *Config) WorkingDir() string {
270270
271271func (c *Config) EnabledProviders() []ProviderConfig {
272272 var enabled []ProviderConfig
273− for _, p := range c.Providers.Seq2() {
273+ for p := range c.Providers.Seq() {
274274 if !p.Disable {
275275 enabled = append(enabled, p)
276276 }
internal/csync/maps.go+20
@@ -56,6 +56,15 @@ func (m *Map[K, V]) Len() int {
5656 return len(m.inner)
5757}
5858
59+// Take gets an item and then deletes it.
60+func (m *Map[K, V]) Take(key K) (V, bool) {
61+ m.mu.Lock()
62+ defer m.mu.Unlock()
63+ v, ok := m.inner[key]
64+ delete(m.inner, key)
65+ return v, ok
66+}
67+
5968// Seq2 returns an iter.Seq2 that yields key-value pairs from the map.
6069func (m *Map[K, V]) Seq2() iter.Seq2[K, V] {
6170 dst := make(map[K]V)
@@ -71,6 +80,17 @@ func (m *Map[K, V]) Seq2() iter.Seq2[K, V] {
7180 }
7281}
7382
83+// Seq returns an iter.Seq that yields values from the map.
84+func (m *Map[K, V]) Seq() iter.Seq[V] {
85+ return func(yield func(V) bool) {
86+ for _, v := range m.Seq2() {
87+ if !yield(v) {
88+ return
89+ }
90+ }
91+ }
92+}
93+
7494var (
7595 _ json.Unmarshaler = &Map[string, any]{}
7696 _ json.Marshaler = &Map[string, any]{}
internal/csync/maps_test.go+225
@@ -110,6 +110,72 @@ func TestMap_Len(t *testing.T) {
110110 assert.Equal(t, 0, m.Len())
111111}
112112
113+func TestMap_Take(t *testing.T) {
114+ t.Parallel()
115+
116+ m := NewMap[string, int]()
117+ m.Set("key1", 42)
118+ m.Set("key2", 100)
119+
120+ assert.Equal(t, 2, m.Len())
121+
122+ value, ok := m.Take("key1")
123+ assert.True(t, ok)
124+ assert.Equal(t, 42, value)
125+ assert.Equal(t, 1, m.Len())
126+
127+ _, exists := m.Get("key1")
128+ assert.False(t, exists)
129+
130+ value, ok = m.Get("key2")
131+ assert.True(t, ok)
132+ assert.Equal(t, 100, value)
133+}
134+
135+func TestMap_Take_NonexistentKey(t *testing.T) {
136+ t.Parallel()
137+
138+ m := NewMap[string, int]()
139+ m.Set("key1", 42)
140+
141+ value, ok := m.Take("nonexistent")
142+ assert.False(t, ok)
143+ assert.Equal(t, 0, value)
144+ assert.Equal(t, 1, m.Len())
145+
146+ value, ok = m.Get("key1")
147+ assert.True(t, ok)
148+ assert.Equal(t, 42, value)
149+}
150+
151+func TestMap_Take_EmptyMap(t *testing.T) {
152+ t.Parallel()
153+
154+ m := NewMap[string, int]()
155+
156+ value, ok := m.Take("key1")
157+ assert.False(t, ok)
158+ assert.Equal(t, 0, value)
159+ assert.Equal(t, 0, m.Len())
160+}
161+
162+func TestMap_Take_SameKeyTwice(t *testing.T) {
163+ t.Parallel()
164+
165+ m := NewMap[string, int]()
166+ m.Set("key1", 42)
167+
168+ value, ok := m.Take("key1")
169+ assert.True(t, ok)
170+ assert.Equal(t, 42, value)
171+ assert.Equal(t, 0, m.Len())
172+
173+ value, ok = m.Take("key1")
174+ assert.False(t, ok)
175+ assert.Equal(t, 0, value)
176+ assert.Equal(t, 0, m.Len())
177+}
178+
113179func TestMap_Seq2(t *testing.T) {
114180 t.Parallel()
115181
@@ -158,6 +224,57 @@ func TestMap_Seq2_EmptyMap(t *testing.T) {
158224 assert.Equal(t, 0, count)
159225}
160226
227+func TestMap_Seq(t *testing.T) {
228+ t.Parallel()
229+
230+ m := NewMap[string, int]()
231+ m.Set("key1", 1)
232+ m.Set("key2", 2)
233+ m.Set("key3", 3)
234+
235+ collected := make([]int, 0)
236+ for v := range m.Seq() {
237+ collected = append(collected, v)
238+ }
239+
240+ assert.Equal(t, 3, len(collected))
241+ assert.Contains(t, collected, 1)
242+ assert.Contains(t, collected, 2)
243+ assert.Contains(t, collected, 3)
244+}
245+
246+func TestMap_Seq_EarlyReturn(t *testing.T) {
247+ t.Parallel()
248+
249+ m := NewMap[string, int]()
250+ m.Set("key1", 1)
251+ m.Set("key2", 2)
252+ m.Set("key3", 3)
253+
254+ count := 0
255+ for range m.Seq() {
256+ count++
257+ if count == 2 {
258+ break
259+ }
260+ }
261+
262+ assert.Equal(t, 2, count)
263+}
264+
265+func TestMap_Seq_EmptyMap(t *testing.T) {
266+ t.Parallel()
267+
268+ m := NewMap[string, int]()
269+
270+ count := 0
271+ for range m.Seq() {
272+ count++
273+ }
274+
275+ assert.Equal(t, 0, count)
276+}
277+
161278func TestMap_MarshalJSON(t *testing.T) {
162279 t.Parallel()
163280
@@ -371,6 +488,82 @@ func TestMap_ConcurrentSeq2(t *testing.T) {
371488 wg.Wait()
372489}
373490
491+func TestMap_ConcurrentSeq(t *testing.T) {
492+ t.Parallel()
493+
494+ m := NewMap[int, int]()
495+ for i := range 100 {
496+ m.Set(i, i*2)
497+ }
498+
499+ var wg sync.WaitGroup
500+ const numIterators = 10
501+
502+ wg.Add(numIterators)
503+ for range numIterators {
504+ go func() {
505+ defer wg.Done()
506+ count := 0
507+ values := make(map[int]bool)
508+ for v := range m.Seq() {
509+ values[v] = true
510+ count++
511+ }
512+ assert.Equal(t, 100, count)
513+ for i := range 100 {
514+ assert.True(t, values[i*2])
515+ }
516+ }()
517+ }
518+
519+ wg.Wait()
520+}
521+
522+func TestMap_ConcurrentTake(t *testing.T) {
523+ t.Parallel()
524+
525+ m := NewMap[int, int]()
526+ const numItems = 1000
527+
528+ for i := range numItems {
529+ m.Set(i, i*2)
530+ }
531+
532+ var wg sync.WaitGroup
533+ const numWorkers = 10
534+ taken := make([][]int, numWorkers)
535+
536+ wg.Add(numWorkers)
537+ for i := range numWorkers {
538+ go func(workerID int) {
539+ defer wg.Done()
540+ taken[workerID] = make([]int, 0)
541+ for j := workerID; j < numItems; j += numWorkers {
542+ if value, ok := m.Take(j); ok {
543+ taken[workerID] = append(taken[workerID], value)
544+ }
545+ }
546+ }(i)
547+ }
548+
549+ wg.Wait()
550+
551+ assert.Equal(t, 0, m.Len())
552+
553+ allTaken := make(map[int]bool)
554+ for _, workerTaken := range taken {
555+ for _, value := range workerTaken {
556+ assert.False(t, allTaken[value], "Value %d was taken multiple times", value)
557+ allTaken[value] = true
558+ }
559+ }
560+
561+ assert.Equal(t, numItems, len(allTaken))
562+ for i := range numItems {
563+ assert.True(t, allTaken[i*2], "Expected value %d to be taken", i*2)
564+ }
565+}
566+
374567func TestMap_TypeSafety(t *testing.T) {
375568 t.Parallel()
376569
@@ -431,6 +624,38 @@ func BenchmarkMap_Seq2(b *testing.B) {
431624 }
432625}
433626
627+func BenchmarkMap_Seq(b *testing.B) {
628+ m := NewMap[int, int]()
629+ for i := range 1000 {
630+ m.Set(i, i*2)
631+ }
632+
633+ for b.Loop() {
634+ for range m.Seq() {
635+ }
636+ }
637+}
638+
639+func BenchmarkMap_Take(b *testing.B) {
640+ m := NewMap[int, int]()
641+ for i := range 1000 {
642+ m.Set(i, i*2)
643+ }
644+
645+ b.ResetTimer()
646+ for i := 0; b.Loop(); i++ {
647+ key := i % 1000
648+ m.Take(key)
649+ if i%1000 == 999 {
650+ b.StopTimer()
651+ for j := range 1000 {
652+ m.Set(j, j*2)
653+ }
654+ b.StartTimer()
655+ }
656+ }
657+}
658+
434659func BenchmarkMap_ConcurrentReadWrite(b *testing.B) {
435660 m := NewMap[int, int]()
436661 for i := range 1000 {
internal/csync/slices.go+11−2
@@ -59,10 +59,10 @@ func NewSliceFrom[T any](s []T) *Slice[T] {
5959}
6060
6161// Append adds an element to the end of the slice.
62−func (s *Slice[T]) Append(item T) {
62+func (s *Slice[T]) Append(items ...T) {
6363 s.mu.Lock()
6464 defer s.mu.Unlock()
65− s.inner = append(s.inner, item)
65+ s.inner = append(s.inner, items...)
6666}
6767
6868// Prepend adds an element to the beginning of the slice.
@@ -112,6 +112,15 @@ func (s *Slice[T]) Len() int {
112112 return len(s.inner)
113113}
114114
115+// Slice returns a copy of the underlying slice.
116+func (s *Slice[T]) Slice() []T {
117+ s.mu.RLock()
118+ defer s.mu.RUnlock()
119+ result := make([]T, len(s.inner))
120+ copy(result, s.inner)
121+ return result
122+}
123+
115124// SetSlice replaces the entire slice with a new one.
116125func (s *Slice[T]) SetSlice(items []T) {
117126 s.mu.Lock()
internal/csync/slices_test.go+3−4
@@ -1,7 +1,6 @@
11package csync
22
33import (
4− "slices"
54 "sync"
65 "sync/atomic"
76 "testing"
@@ -146,7 +145,7 @@ func TestSlice(t *testing.T) {
146145 assert.Equal(t, 4, s.Len())
147146
148147 expected := []int{1, 2, 4, 5}
149− actual := slices.Collect(s.Seq())
148+ actual := s.Slice()
150149 assert.Equal(t, expected, actual)
151150
152151 // Delete out of bounds
@@ -204,7 +203,7 @@ func TestSlice(t *testing.T) {
204203 s.SetSlice(newItems)
205204
206205 assert.Equal(t, 3, s.Len())
207− assert.Equal(t, newItems, slices.Collect(s.Seq()))
206+ assert.Equal(t, newItems, s.Slice())
208207
209208 // Verify it's a copy
210209 newItems[0] = 999
@@ -225,7 +224,7 @@ func TestSlice(t *testing.T) {
225224 original := []int{1, 2, 3}
226225 s := NewSliceFrom(original)
227226
228− copy := slices.Collect(s.Seq())
227+ copy := s.Slice()
229228 assert.Equal(t, original, copy)
230229
231230 // Verify it's a copy
internal/llm/agent/agent.go+23−32
@@ -7,7 +7,6 @@ import (
77 "log/slog"
88 "slices"
99 "strings"
10− "sync"
1110 "time"
1211
1312 "github.com/charmbracelet/catwalk/pkg/catwalk"
@@ -78,7 +77,7 @@ type agent struct {
7877 summarizeProvider provider.Provider
7978 summarizeProviderID string
8079
81− activeRequests sync.Map
80+ activeRequests *csync.Map[string, context.CancelFunc]
8281}
8382
8483var agentPromptMap = map[string]prompt.PromptID{
@@ -222,7 +221,7 @@ func NewAgent(
222221 titleProvider: titleProvider,
223222 summarizeProvider: summarizeProvider,
224223 summarizeProviderID: string(smallModelProviderCfg.ID),
225− activeRequests: sync.Map{},
224+ activeRequests: csync.NewMap[string, context.CancelFunc](),
226225 tools: csync.NewLazySlice(toolFn),
227226 }, nil
228227}
@@ -233,38 +232,31 @@ func (a *agent) Model() catwalk.Model {
233232
234233func (a *agent) Cancel(sessionID string) {
235234 // Cancel regular requests
236− if cancelFunc, exists := a.activeRequests.LoadAndDelete(sessionID); exists {
237− if cancel, ok := cancelFunc.(context.CancelFunc); ok {
238− slog.Info("Request cancellation initiated", "session_id", sessionID)
239− cancel()
240− }
235+ if cancel, ok := a.activeRequests.Take(sessionID); ok && cancel != nil {
236+ slog.Info("Request cancellation initiated", "session_id", sessionID)
237+ cancel()
241238 }
242239
243240 // Also check for summarize requests
244− if cancelFunc, exists := a.activeRequests.LoadAndDelete(sessionID + "-summarize"); exists {
245− if cancel, ok := cancelFunc.(context.CancelFunc); ok {
246− slog.Info("Summarize cancellation initiated", "session_id", sessionID)
247− cancel()
248− }
241+ if cancel, ok := a.activeRequests.Take(sessionID + "-summarize"); ok && cancel != nil {
242+ slog.Info("Summarize cancellation initiated", "session_id", sessionID)
243+ cancel()
249244 }
250245}
251246
252247func (a *agent) IsBusy() bool {
253− busy := false
254− a.activeRequests.Range(func(key, value any) bool {
255− if cancelFunc, ok := value.(context.CancelFunc); ok {
256− if cancelFunc != nil {
257− busy = true
258− return false
259− }
248+ var busy bool
249+ for cancelFunc := range a.activeRequests.Seq() {
250+ if cancelFunc != nil {
251+ busy = true
252+ break
260253 }
261− return true
262− })
254+ }
263255 return busy
264256}
265257
266258func (a *agent) IsSessionBusy(sessionID string) bool {
267− _, busy := a.activeRequests.Load(sessionID)
259+ _, busy := a.activeRequests.Get(sessionID)
268260 return busy
269261}
270262
@@ -335,7 +327,7 @@ func (a *agent) Run(ctx context.Context, sessionID string, content string, attac
335327
336328 genCtx, cancel := context.WithCancel(ctx)
337329
338− a.activeRequests.Store(sessionID, cancel)
330+ a.activeRequests.Set(sessionID, cancel)
339331 go func() {
340332 slog.Debug("Request started", "sessionID", sessionID)
341333 defer log.RecoverPanic("agent.Run", func() {
@@ -350,7 +342,7 @@ func (a *agent) Run(ctx context.Context, sessionID string, content string, attac
350342 slog.Error(result.Error.Error())
351343 }
352344 slog.Debug("Request completed", "sessionID", sessionID)
353− a.activeRequests.Delete(sessionID)
345+ a.activeRequests.Del(sessionID)
354346 cancel()
355347 a.Publish(pubsub.CreatedEvent, result)
356348 events <- result
@@ -682,10 +674,10 @@ func (a *agent) Summarize(ctx context.Context, sessionID string) error {
682674 summarizeCtx, cancel := context.WithCancel(ctx)
683675
684676 // Store the cancel function in activeRequests to allow cancellation
685− a.activeRequests.Store(sessionID+"-summarize", cancel)
677+ a.activeRequests.Set(sessionID+"-summarize", cancel)
686678
687679 go func() {
688− defer a.activeRequests.Delete(sessionID + "-summarize")
680+ defer a.activeRequests.Del(sessionID + "-summarize")
689681 defer cancel()
690682 event := AgentEvent{
691683 Type: AgentEventTypeSummarize,
@@ -850,10 +842,9 @@ func (a *agent) CancelAll() {
850842 if !a.IsBusy() {
851843 return
852844 }
853− a.activeRequests.Range(func(key, value any) bool {
854− a.Cancel(key.(string)) // key is sessionID
855− return true
856− })
845+ for key := range a.activeRequests.Seq2() {
846+ a.Cancel(key) // key is sessionID
847+ }
857848
858849 timeout := time.After(5 * time.Second)
859850 for a.IsBusy() {
@@ -907,7 +898,7 @@ func (a *agent) UpdateModel() error {
907898 smallModelCfg := cfg.Models[config.SelectedModelTypeSmall]
908899 var smallModelProviderCfg config.ProviderConfig
909900
910− for _, p := range cfg.Providers.Seq2() {
901+ for p := range cfg.Providers.Seq() {
911902 if p.ID == smallModelCfg.Provider {
912903 smallModelProviderCfg = p
913904 break
internal/llm/agent/mcp-tools.go+7−12
@@ -5,9 +5,11 @@ import (
55 "encoding/json"
66 "fmt"
77 "log/slog"
8+ "slices"
89 "sync"
910
1011 "github.com/charmbracelet/crush/internal/config"
12+ "github.com/charmbracelet/crush/internal/csync"
1113 "github.com/charmbracelet/crush/internal/llm/tools"
1214
1315 "github.com/charmbracelet/crush/internal/permission"
@@ -196,9 +198,8 @@ func GetMCPTools(ctx context.Context, permissions permission.Service, cfg *confi
196198}
197199
198200func doGetMCPTools(ctx context.Context, permissions permission.Service, cfg *config.Config) []tools.BaseTool {
199− var mu sync.Mutex
200201 var wg sync.WaitGroup
201− var result []tools.BaseTool
202+ result := csync.NewSlice[tools.BaseTool]()
202203 for name, m := range cfg.MCP {
203204 if m.Disabled {
204205 slog.Debug("skipping disabled mcp", "name", name)
@@ -219,9 +220,7 @@ func doGetMCPTools(ctx context.Context, permissions permission.Service, cfg *con
219220 return
220221 }
221222
222− mu.Lock()
223− result = append(result, getTools(ctx, name, m, permissions, c, cfg.WorkingDir())...)
224− mu.Unlock()
223+ result.Append(getTools(ctx, name, m, permissions, c, cfg.WorkingDir())...)
225224 case config.MCPHttp:
226225 c, err := client.NewStreamableHttpClient(
227226 m.URL,
@@ -231,9 +230,7 @@ func doGetMCPTools(ctx context.Context, permissions permission.Service, cfg *con
231230 slog.Error("error creating mcp client", "error", err)
232231 return
233232 }
234− mu.Lock()
235− result = append(result, getTools(ctx, name, m, permissions, c, cfg.WorkingDir())...)
236− mu.Unlock()
233+ result.Append(getTools(ctx, name, m, permissions, c, cfg.WorkingDir())...)
237234 case config.MCPSse:
238235 c, err := client.NewSSEMCPClient(
239236 m.URL,
@@ -243,12 +240,10 @@ func doGetMCPTools(ctx context.Context, permissions permission.Service, cfg *con
243240 slog.Error("error creating mcp client", "error", err)
244241 return
245242 }
246− mu.Lock()
247− result = append(result, getTools(ctx, name, m, permissions, c, cfg.WorkingDir())...)
248− mu.Unlock()
243+ result.Append(getTools(ctx, name, m, permissions, c, cfg.WorkingDir())...)
249244 }
250245 }(name, m)
251246 }
252247 wg.Wait()
253− return result
248+ return slices.Collect(result.Seq())
254249}
internal/llm/prompt/prompt.go+6−18
@@ -7,6 +7,7 @@ import (
77 "sync"
88
99 "github.com/charmbracelet/crush/internal/config"
10+ "github.com/charmbracelet/crush/internal/csync"
1011 "github.com/charmbracelet/crush/internal/env"
1112)
1213
@@ -74,8 +75,7 @@ func processContextPaths(workDir string, paths []string) string {
7475 )
7576
7677 // Track processed files to avoid duplicates
77− processedFiles := make(map[string]bool)
78− var processedMutex sync.Mutex
78+ processedFiles := csync.NewMap[string, bool]()
7979
8080 for _, path := range paths {
8181 wg.Add(1)
@@ -106,14 +106,8 @@ func processContextPaths(workDir string, paths []string) string {
106106 // Check if we've already processed this file (case-insensitive)
107107 lowerPath := strings.ToLower(path)
108108
109− processedMutex.Lock()
110− alreadyProcessed := processedFiles[lowerPath]
111− if !alreadyProcessed {
112− processedFiles[lowerPath] = true
113− }
114− processedMutex.Unlock()
115−
116− if !alreadyProcessed {
109+ if alreadyProcessed, _ := processedFiles.Get(lowerPath); !alreadyProcessed {
110+ processedFiles.Set(lowerPath, true)
117111 if result := processFile(path); result != "" {
118112 resultCh <- result
119113 }
@@ -126,14 +120,8 @@ func processContextPaths(workDir string, paths []string) string {
126120 // Check if we've already processed this file (case-insensitive)
127121 lowerPath := strings.ToLower(fullPath)
128122
129− processedMutex.Lock()
130− alreadyProcessed := processedFiles[lowerPath]
131− if !alreadyProcessed {
132− processedFiles[lowerPath] = true
133− }
134− processedMutex.Unlock()
135−
136− if !alreadyProcessed {
123+ if alreadyProcessed, _ := processedFiles.Get(lowerPath); !alreadyProcessed {
124+ processedFiles.Set(lowerPath, true)
137125 result := processFile(fullPath)
138126 if result != "" {
139127 resultCh <- result
internal/lsp/watcher/watcher.go+7−12
@@ -12,6 +12,7 @@ import (
1212
1313 "github.com/bmatcuk/doublestar/v4"
1414 "github.com/charmbracelet/crush/internal/config"
15+ "github.com/charmbracelet/crush/internal/csync"
1516
1617 "github.com/charmbracelet/crush/internal/lsp"
1718 "github.com/charmbracelet/crush/internal/lsp/protocol"
@@ -25,8 +26,7 @@ type WorkspaceWatcher struct {
2526 workspacePath string
2627
2728 debounceTime time.Duration
28− debounceMap map[string]*time.Timer
29− debounceMu sync.Mutex
29+ debounceMap *csync.Map[string, *time.Timer]
3030
3131 // File watchers registered by the server
3232 registrations []protocol.FileSystemWatcher
@@ -46,7 +46,7 @@ func NewWorkspaceWatcher(name string, client *lsp.Client) *WorkspaceWatcher {
4646 name: name,
4747 client: client,
4848 debounceTime: 300 * time.Millisecond,
49− debounceMap: make(map[string]*time.Timer),
49+ debounceMap: csync.NewMap[string, *time.Timer](),
5050 registrations: []protocol.FileSystemWatcher{},
5151 }
5252}
@@ -639,26 +639,21 @@ func (w *WorkspaceWatcher) matchesPattern(path string, pattern protocol.GlobPatt
639639
640640// debounceHandleFileEvent handles file events with debouncing to reduce notifications
641641func (w *WorkspaceWatcher) debounceHandleFileEvent(ctx context.Context, uri string, changeType protocol.FileChangeType) {
642− w.debounceMu.Lock()
643− defer w.debounceMu.Unlock()
644−
645642 // Create a unique key based on URI and change type
646643 key := fmt.Sprintf("%s:%d", uri, changeType)
647644
648645 // Cancel existing timer if any
649− if timer, exists := w.debounceMap[key]; exists {
646+ if timer, exists := w.debounceMap.Get(key); exists {
650647 timer.Stop()
651648 }
652649
653650 // Create new timer
654− w.debounceMap[key] = time.AfterFunc(w.debounceTime, func() {
651+ w.debounceMap.Set(key, time.AfterFunc(w.debounceTime, func() {
655652 w.handleFileEvent(ctx, uri, changeType)
656653
657654 // Cleanup timer after execution
658− w.debounceMu.Lock()
659− delete(w.debounceMap, key)
660− w.debounceMu.Unlock()
661− })
655+ w.debounceMap.Del(key)
656+ }))
662657}
663658
664659// handleFileEvent sends file change notifications
internal/permission/permission.go+11−9
@@ -7,6 +7,7 @@ import (
77 "slices"
88 "sync"
99
10+ "github.com/charmbracelet/crush/internal/csync"
1011 "github.com/charmbracelet/crush/internal/pubsub"
1112 "github.com/google/uuid"
1213)
@@ -57,7 +58,7 @@ type permissionService struct {
5758 workingDir string
5859 sessionPermissions []PermissionRequest
5960 sessionPermissionsMu sync.RWMutex
60− pendingRequests sync.Map
61+ pendingRequests *csync.Map[string, chan bool]
6162 autoApproveSessions map[string]bool
6263 autoApproveSessionsMu sync.RWMutex
6364 skip bool
@@ -73,9 +74,9 @@ func (s *permissionService) GrantPersistent(permission PermissionRequest) {
7374 ToolCallID: permission.ToolCallID,
7475 Granted: true,
7576 })
76− respCh, ok := s.pendingRequests.Load(permission.ID)
77+ respCh, ok := s.pendingRequests.Get(permission.ID)
7778 if ok {
78− respCh.(chan bool) <- true
79+ respCh <- true
7980 }
8081
8182 s.sessionPermissionsMu.Lock()
@@ -92,9 +93,9 @@ func (s *permissionService) Grant(permission PermissionRequest) {
9293 ToolCallID: permission.ToolCallID,
9394 Granted: true,
9495 })
95− respCh, ok := s.pendingRequests.Load(permission.ID)
96+ respCh, ok := s.pendingRequests.Get(permission.ID)
9697 if ok {
97− respCh.(chan bool) <- true
98+ respCh <- true
9899 }
99100
100101 if s.activeRequest != nil && s.activeRequest.ID == permission.ID {
@@ -108,9 +109,9 @@ func (s *permissionService) Deny(permission PermissionRequest) {
108109 Granted: false,
109110 Denied: true,
110111 })
111− respCh, ok := s.pendingRequests.Load(permission.ID)
112+ respCh, ok := s.pendingRequests.Get(permission.ID)
112113 if ok {
113− respCh.(chan bool) <- false
114+ respCh <- false
114115 }
115116
116117 if s.activeRequest != nil && s.activeRequest.ID == permission.ID {
@@ -180,8 +181,8 @@ func (s *permissionService) Request(opts CreatePermissionRequest) bool {
180181 s.activeRequest = &permission
181182
182183 respCh := make(chan bool, 1)
183− s.pendingRequests.Store(permission.ID, respCh)
184− defer s.pendingRequests.Delete(permission.ID)
184+ s.pendingRequests.Set(permission.ID, respCh)
185+ defer s.pendingRequests.Del(permission.ID)
185186
186187 // Publish the request
187188 s.Publish(pubsub.CreatedEvent, permission)
@@ -208,5 +209,6 @@ func NewPermissionService(workingDir string, skip bool, allowedTools []string) S
208209 autoApproveSessions: make(map[string]bool),
209210 skip: skip,
210211 allowedTools: allowedTools,
212+ pendingRequests: csync.NewMap[string, chan bool](),
211213 }
212214}
internal/tui/components/chat/sidebar/sidebar.go+32−42
@@ -4,13 +4,14 @@ import (
44 "context"
55 "fmt"
66 "os"
7+ "slices"
78 "sort"
89 "strings"
9− "sync"
1010
1111 tea "github.com/charmbracelet/bubbletea/v2"
1212 "github.com/charmbracelet/catwalk/pkg/catwalk"
1313 "github.com/charmbracelet/crush/internal/config"
14+ "github.com/charmbracelet/crush/internal/csync"
1415 "github.com/charmbracelet/crush/internal/diff"
1516 "github.com/charmbracelet/crush/internal/fsext"
1617 "github.com/charmbracelet/crush/internal/history"
@@ -71,8 +72,7 @@ type sidebarCmp struct {
7172 lspClients map[string]*lsp.Client
7273 compactMode bool
7374 history history.Service
74− // Using a sync map here because we might receive file history events concurrently
75− files sync.Map
75+ files *csync.Map[string, SessionFile]
7676}
7777
7878func New(history history.Service, lspClients map[string]*lsp.Client, compact bool) Sidebar {
@@ -80,6 +80,7 @@ func New(history history.Service, lspClients map[string]*lsp.Client, compact boo
8080 lspClients: lspClients,
8181 history: history,
8282 compactMode: compact,
83+ files: csync.NewMap[string, SessionFile](),
8384 }
8485}
8586
@@ -90,9 +91,9 @@ func (m *sidebarCmp) Init() tea.Cmd {
9091func (m *sidebarCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
9192 switch msg := msg.(type) {
9293 case SessionFilesMsg:
93− m.files = sync.Map{}
94+ m.files = csync.NewMap[string, SessionFile]()
9495 for _, file := range msg.Files {
95− m.files.Store(file.FilePath, file)
96+ m.files.Set(file.FilePath, file)
9697 }
9798 return m, nil
9899
@@ -178,31 +179,30 @@ func (m *sidebarCmp) handleFileHistoryEvent(event pubsub.Event[history.File]) te
178179 return func() tea.Msg {
179180 file := event.Payload
180181 found := false
181− m.files.Range(func(key, value any) bool {
182− existing := value.(SessionFile)
183− if existing.FilePath == file.Path {
184− if existing.History.latestVersion.Version < file.Version {
185− existing.History.latestVersion = file
186− } else if file.Version == 0 {
187− existing.History.initialVersion = file
188− } else {
189− // If the version is not greater than the latest, we ignore it
190− return true
191− }
192− before := existing.History.initialVersion.Content
193− after := existing.History.latestVersion.Content
194− path := existing.History.initialVersion.Path
195− cwd := config.Get().WorkingDir()
196− path = strings.TrimPrefix(path, cwd)
197− _, additions, deletions := diff.GenerateDiff(before, after, path)
198− existing.Additions = additions
199− existing.Deletions = deletions
200− m.files.Store(file.Path, existing)
201− found = true
202− return false
182+ for existing := range m.files.Seq() {
183+ if existing.FilePath != file.Path {
184+ continue
203185 }
204− return true
205− })
186+ if existing.History.latestVersion.Version < file.Version {
187+ existing.History.latestVersion = file
188+ } else if file.Version == 0 {
189+ existing.History.initialVersion = file
190+ } else {
191+ // If the version is not greater than the latest, we ignore it
192+ continue
193+ }
194+ before := existing.History.initialVersion.Content
195+ after := existing.History.latestVersion.Content
196+ path := existing.History.initialVersion.Path
197+ cwd := config.Get().WorkingDir()
198+ path = strings.TrimPrefix(path, cwd)
199+ _, additions, deletions := diff.GenerateDiff(before, after, path)
200+ existing.Additions = additions
201+ existing.Deletions = deletions
202+ m.files.Set(file.Path, existing)
203+ found = true
204+ break
205+ }
206206 if found {
207207 return nil
208208 }
@@ -215,7 +215,7 @@ func (m *sidebarCmp) handleFileHistoryEvent(event pubsub.Event[history.File]) te
215215 Additions: 0,
216216 Deletions: 0,
217217 }
218− m.files.Store(file.Path, sf)
218+ m.files.Set(file.Path, sf)
219219 return nil
220220 }
221221}
@@ -386,12 +386,7 @@ func (m *sidebarCmp) filesBlockCompact(maxWidth int) string {
386386
387387 section := t.S().Subtle.Render("Modified Files")
388388
389− files := make([]SessionFile, 0)
390− m.files.Range(func(key, value any) bool {
391− file := value.(SessionFile)
392− files = append(files, file)
393− return true
394− })
389+ files := slices.Collect(m.files.Seq())
395390
396391 if len(files) == 0 {
397392 content := lipgloss.JoinVertical(
@@ -620,12 +615,7 @@ func (m *sidebarCmp) filesBlock() string {
620615 core.Section("Modified Files", m.getMaxWidth()),
621616 )
622617
623− files := make([]SessionFile, 0)
624− m.files.Range(func(key, value any) bool {
625− file := value.(SessionFile)
626− files = append(files, file)
627− return true // continue iterating
628− })
618+ files := slices.Collect(m.files.Seq())
629619 if len(files) == 0 {
630620 return lipgloss.JoinVertical(
631621 lipgloss.Left,