sidebar.go

  1package sidebar
  2
  3import (
  4	"context"
  5	"fmt"
  6	"os"
  7	"sort"
  8	"strings"
  9	"sync"
 10
 11	tea "github.com/charmbracelet/bubbletea/v2"
 12	"github.com/charmbracelet/crush/internal/config"
 13	"github.com/charmbracelet/crush/internal/diff"
 14	"github.com/charmbracelet/crush/internal/fsext"
 15	"github.com/charmbracelet/crush/internal/history"
 16
 17	"github.com/charmbracelet/crush/internal/lsp"
 18	"github.com/charmbracelet/crush/internal/lsp/protocol"
 19	"github.com/charmbracelet/crush/internal/pubsub"
 20	"github.com/charmbracelet/crush/internal/session"
 21	"github.com/charmbracelet/crush/internal/tui/components/chat"
 22	"github.com/charmbracelet/crush/internal/tui/components/core"
 23	"github.com/charmbracelet/crush/internal/tui/components/core/layout"
 24	"github.com/charmbracelet/crush/internal/tui/components/logo"
 25	"github.com/charmbracelet/crush/internal/tui/styles"
 26	"github.com/charmbracelet/crush/internal/tui/util"
 27	"github.com/charmbracelet/crush/internal/version"
 28	"github.com/charmbracelet/lipgloss/v2"
 29	"github.com/charmbracelet/x/ansi"
 30)
 31
 32const (
 33	logoBreakpoint = 65
 34)
 35
 36type FileHistory struct {
 37	initialVersion history.File
 38	latestVersion  history.File
 39}
 40
 41type SessionFile struct {
 42	History   FileHistory
 43	FilePath  string
 44	Additions int
 45	Deletions int
 46}
 47type SessionFilesMsg struct {
 48	Files []SessionFile
 49}
 50
 51type Sidebar interface {
 52	util.Model
 53	layout.Sizeable
 54	SetSession(session session.Session) tea.Cmd
 55}
 56
 57type sidebarCmp struct {
 58	width, height int
 59	session       session.Session
 60	logo          string
 61	cwd           string
 62	lspClients    map[string]*lsp.Client
 63	compactMode   bool
 64	history       history.Service
 65	// Using a sync map here because we might receive file history events concurrently
 66	files sync.Map
 67}
 68
 69func NewSidebarCmp(history history.Service, lspClients map[string]*lsp.Client, compact bool) Sidebar {
 70	return &sidebarCmp{
 71		lspClients:  lspClients,
 72		history:     history,
 73		compactMode: compact,
 74	}
 75}
 76
 77func (m *sidebarCmp) Init() tea.Cmd {
 78	m.logo = m.logoBlock(false)
 79	m.cwd = cwd()
 80	return nil
 81}
 82
 83func (m *sidebarCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
 84	switch msg := msg.(type) {
 85	case chat.SessionSelectedMsg:
 86		return m, m.SetSession(msg)
 87	case SessionFilesMsg:
 88		m.files = sync.Map{}
 89		for _, file := range msg.Files {
 90			m.files.Store(file.FilePath, file)
 91		}
 92		return m, nil
 93
 94	case chat.SessionClearedMsg:
 95		m.session = session.Session{}
 96	case pubsub.Event[history.File]:
 97		return m, m.handleFileHistoryEvent(msg)
 98	case pubsub.Event[session.Session]:
 99		if msg.Type == pubsub.UpdatedEvent {
100			if m.session.ID == msg.Payload.ID {
101				m.session = msg.Payload
102			}
103		}
104	}
105	return m, nil
106}
107
108func (m *sidebarCmp) View() string {
109	t := styles.CurrentTheme()
110	parts := []string{}
111	if !m.compactMode {
112		parts = append(parts, m.logo)
113	}
114
115	if !m.compactMode && m.session.ID != "" {
116		parts = append(parts, t.S().Muted.Render(m.session.Title), "")
117	} else if m.session.ID != "" {
118		parts = append(parts, t.S().Text.Render(m.session.Title), "")
119	}
120
121	if !m.compactMode {
122		parts = append(parts,
123			m.cwd,
124			"",
125		)
126	}
127	parts = append(parts,
128		m.currentModelBlock(),
129	)
130	if m.session.ID != "" {
131		parts = append(parts, "", m.filesBlock())
132	}
133	parts = append(parts,
134		"",
135		m.lspBlock(),
136		"",
137		m.mcpBlock(),
138	)
139
140	return lipgloss.JoinVertical(lipgloss.Left, parts...)
141}
142
143func (m *sidebarCmp) handleFileHistoryEvent(event pubsub.Event[history.File]) tea.Cmd {
144	return func() tea.Msg {
145		file := event.Payload
146		found := false
147		m.files.Range(func(key, value any) bool {
148			existing := value.(SessionFile)
149			if existing.FilePath == file.Path {
150				if existing.History.latestVersion.Version < file.Version {
151					existing.History.latestVersion = file
152				} else if file.Version == 0 {
153					existing.History.initialVersion = file
154				} else {
155					// If the version is not greater than the latest, we ignore it
156					return true
157				}
158				before := existing.History.initialVersion.Content
159				after := existing.History.latestVersion.Content
160				path := existing.History.initialVersion.Path
161				cwd := config.Get().WorkingDir()
162				path = strings.TrimPrefix(path, cwd)
163				_, additions, deletions := diff.GenerateDiff(before, after, path)
164				existing.Additions = additions
165				existing.Deletions = deletions
166				m.files.Store(file.Path, existing)
167				found = true
168				return false
169			}
170			return true
171		})
172		if found {
173			return nil
174		}
175		sf := SessionFile{
176			History: FileHistory{
177				initialVersion: file,
178				latestVersion:  file,
179			},
180			FilePath:  file.Path,
181			Additions: 0,
182			Deletions: 0,
183		}
184		m.files.Store(file.Path, sf)
185		return nil
186	}
187}
188
189func (m *sidebarCmp) loadSessionFiles() tea.Msg {
190	files, err := m.history.ListBySession(context.Background(), m.session.ID)
191	if err != nil {
192		return util.InfoMsg{
193			Type: util.InfoTypeError,
194			Msg:  err.Error(),
195		}
196	}
197
198	fileMap := make(map[string]FileHistory)
199
200	for _, file := range files {
201		if existing, ok := fileMap[file.Path]; ok {
202			// Update the latest version
203			existing.latestVersion = file
204			fileMap[file.Path] = existing
205		} else {
206			// Add the initial version
207			fileMap[file.Path] = FileHistory{
208				initialVersion: file,
209				latestVersion:  file,
210			}
211		}
212	}
213
214	sessionFiles := make([]SessionFile, 0, len(fileMap))
215	for path, fh := range fileMap {
216		cwd := config.Get().WorkingDir()
217		path = strings.TrimPrefix(path, cwd)
218		_, additions, deletions := diff.GenerateDiff(fh.initialVersion.Content, fh.latestVersion.Content, path)
219		sessionFiles = append(sessionFiles, SessionFile{
220			History:   fh,
221			FilePath:  path,
222			Additions: additions,
223			Deletions: deletions,
224		})
225	}
226
227	return SessionFilesMsg{
228		Files: sessionFiles,
229	}
230}
231
232func (m *sidebarCmp) SetSize(width, height int) tea.Cmd {
233	if width < logoBreakpoint && (m.width == 0 || m.width >= logoBreakpoint) {
234		m.logo = m.logoBlock(true)
235	} else if width >= logoBreakpoint && (m.width == 0 || m.width < logoBreakpoint) {
236		m.logo = m.logoBlock(false)
237	}
238
239	m.width = width
240	m.height = height
241	return nil
242}
243
244func (m *sidebarCmp) GetSize() (int, int) {
245	return m.width, m.height
246}
247
248func (m *sidebarCmp) logoBlock(compact bool) string {
249	t := styles.CurrentTheme()
250	return logo.Render(version.Version, compact, logo.Opts{
251		FieldColor:   t.Primary,
252		TitleColorA:  t.Secondary,
253		TitleColorB:  t.Primary,
254		CharmColor:   t.Secondary,
255		VersionColor: t.Primary,
256	})
257}
258
259func (m *sidebarCmp) filesBlock() string {
260	maxWidth := min(m.width, 58)
261	t := styles.CurrentTheme()
262
263	section := t.S().Subtle.Render(
264		core.Section("Modified Files", maxWidth),
265	)
266
267	files := make([]SessionFile, 0)
268	m.files.Range(func(key, value any) bool {
269		file := value.(SessionFile)
270		files = append(files, file)
271		return true // continue iterating
272	})
273	if len(files) == 0 {
274		return lipgloss.JoinVertical(
275			lipgloss.Left,
276			section,
277			"",
278			t.S().Base.Foreground(t.Border).Render("None"),
279		)
280	}
281
282	fileList := []string{section, ""}
283	// order files by the latest version's created time
284	sort.Slice(files, func(i, j int) bool {
285		return files[i].History.latestVersion.CreatedAt > files[j].History.latestVersion.CreatedAt
286	})
287
288	for _, file := range files {
289		if file.Additions == 0 && file.Deletions == 0 {
290			continue // skip files with no changes
291		}
292		var statusParts []string
293		if file.Additions > 0 {
294			statusParts = append(statusParts, t.S().Base.Foreground(t.Success).Render(fmt.Sprintf("+%d", file.Additions)))
295		}
296		if file.Deletions > 0 {
297			statusParts = append(statusParts, t.S().Base.Foreground(t.Error).Render(fmt.Sprintf("-%d", file.Deletions)))
298		}
299
300		extraContent := strings.Join(statusParts, " ")
301		cwd := config.Get().WorkingDir() + string(os.PathSeparator)
302		filePath := file.FilePath
303		filePath = strings.TrimPrefix(filePath, cwd)
304		filePath = fsext.DirTrim(fsext.PrettyPath(filePath), 2)
305		filePath = ansi.Truncate(filePath, maxWidth-lipgloss.Width(extraContent)-2, "…")
306		fileList = append(fileList,
307			core.Status(
308				core.StatusOpts{
309					IconColor:    t.FgMuted,
310					NoIcon:       true,
311					Title:        filePath,
312					ExtraContent: extraContent,
313				},
314				m.width,
315			),
316		)
317	}
318
319	return lipgloss.JoinVertical(
320		lipgloss.Left,
321		fileList...,
322	)
323}
324
325func (m *sidebarCmp) lspBlock() string {
326	maxWidth := min(m.width, 58)
327	t := styles.CurrentTheme()
328
329	section := t.S().Subtle.Render(
330		core.Section("LSPs", maxWidth),
331	)
332
333	lspList := []string{section, ""}
334
335	lsp := config.Get().LSP.Sorted()
336	if len(lsp) == 0 {
337		return lipgloss.JoinVertical(
338			lipgloss.Left,
339			section,
340			"",
341			t.S().Base.Foreground(t.Border).Render("None"),
342		)
343	}
344
345	for _, l := range lsp {
346		iconColor := t.Success
347		if l.LSP.Disabled {
348			iconColor = t.FgMuted
349		}
350		lspErrs := map[protocol.DiagnosticSeverity]int{
351			protocol.SeverityError:       0,
352			protocol.SeverityWarning:     0,
353			protocol.SeverityHint:        0,
354			protocol.SeverityInformation: 0,
355		}
356		if client, ok := m.lspClients[l.Name]; ok {
357			for _, diagnostics := range client.GetDiagnostics() {
358				for _, diagnostic := range diagnostics {
359					if severity, ok := lspErrs[diagnostic.Severity]; ok {
360						lspErrs[diagnostic.Severity] = severity + 1
361					}
362				}
363			}
364		}
365
366		errs := []string{}
367		if lspErrs[protocol.SeverityError] > 0 {
368			errs = append(errs, t.S().Base.Foreground(t.Error).Render(fmt.Sprintf("%s %d", styles.ErrorIcon, lspErrs[protocol.SeverityError])))
369		}
370		if lspErrs[protocol.SeverityWarning] > 0 {
371			errs = append(errs, t.S().Base.Foreground(t.Warning).Render(fmt.Sprintf("%s %d", styles.WarningIcon, lspErrs[protocol.SeverityWarning])))
372		}
373		if lspErrs[protocol.SeverityHint] > 0 {
374			errs = append(errs, t.S().Base.Foreground(t.FgHalfMuted).Render(fmt.Sprintf("%s %d", styles.HintIcon, lspErrs[protocol.SeverityHint])))
375		}
376		if lspErrs[protocol.SeverityInformation] > 0 {
377			errs = append(errs, t.S().Base.Foreground(t.FgHalfMuted).Render(fmt.Sprintf("%s %d", styles.InfoIcon, lspErrs[protocol.SeverityInformation])))
378		}
379
380		lspList = append(lspList,
381			core.Status(
382				core.StatusOpts{
383					IconColor:    iconColor,
384					Title:        l.Name,
385					Description:  l.LSP.Command,
386					ExtraContent: strings.Join(errs, " "),
387				},
388				m.width,
389			),
390		)
391	}
392
393	return lipgloss.JoinVertical(
394		lipgloss.Left,
395		lspList...,
396	)
397}
398
399func (m *sidebarCmp) mcpBlock() string {
400	maxWidth := min(m.width, 58)
401	t := styles.CurrentTheme()
402
403	section := t.S().Subtle.Render(
404		core.Section("MCPs", maxWidth),
405	)
406
407	mcpList := []string{section, ""}
408
409	mcps := config.Get().MCP.Sorted()
410	if len(mcps) == 0 {
411		return lipgloss.JoinVertical(
412			lipgloss.Left,
413			section,
414			"",
415			t.S().Base.Foreground(t.Border).Render("None"),
416		)
417	}
418
419	for _, l := range mcps {
420		iconColor := t.Success
421		mcpList = append(mcpList,
422			core.Status(
423				core.StatusOpts{
424					IconColor:   iconColor,
425					Title:       l.Name,
426					Description: l.MCP.Command,
427				},
428				m.width,
429			),
430		)
431	}
432
433	return lipgloss.JoinVertical(
434		lipgloss.Left,
435		mcpList...,
436	)
437}
438
439func formatTokensAndCost(tokens, contextWindow int64, cost float64) string {
440	t := styles.CurrentTheme()
441	// Format tokens in human-readable format (e.g., 110K, 1.2M)
442	var formattedTokens string
443	switch {
444	case tokens >= 1_000_000:
445		formattedTokens = fmt.Sprintf("%.1fM", float64(tokens)/1_000_000)
446	case tokens >= 1_000:
447		formattedTokens = fmt.Sprintf("%.1fK", float64(tokens)/1_000)
448	default:
449		formattedTokens = fmt.Sprintf("%d", tokens)
450	}
451
452	// Remove .0 suffix if present
453	if strings.HasSuffix(formattedTokens, ".0K") {
454		formattedTokens = strings.Replace(formattedTokens, ".0K", "K", 1)
455	}
456	if strings.HasSuffix(formattedTokens, ".0M") {
457		formattedTokens = strings.Replace(formattedTokens, ".0M", "M", 1)
458	}
459
460	percentage := (float64(tokens) / float64(contextWindow)) * 100
461
462	baseStyle := t.S().Base
463
464	formattedCost := baseStyle.Foreground(t.FgMuted).Render(fmt.Sprintf("$%.2f", cost))
465
466	formattedTokens = baseStyle.Foreground(t.FgSubtle).Render(fmt.Sprintf("(%s)", formattedTokens))
467	formattedPercentage := baseStyle.Foreground(t.FgMuted).Render(fmt.Sprintf("%d%%", int(percentage)))
468	formattedTokens = fmt.Sprintf("%s %s", formattedPercentage, formattedTokens)
469	if percentage > 80 {
470		// add the warning icon
471		formattedTokens = fmt.Sprintf("%s %s", styles.WarningIcon, formattedTokens)
472	}
473
474	return fmt.Sprintf("%s %s", formattedTokens, formattedCost)
475}
476
477func (s *sidebarCmp) currentModelBlock() string {
478	agentCfg := config.Get().Agents["coder"]
479	model := config.Get().GetModelByType(agentCfg.Model)
480
481	t := styles.CurrentTheme()
482
483	modelIcon := t.S().Base.Foreground(t.FgSubtle).Render(styles.ModelIcon)
484	modelName := t.S().Text.Render(model.Model)
485	modelInfo := fmt.Sprintf("%s %s", modelIcon, modelName)
486	parts := []string{
487		modelInfo,
488	}
489	if s.session.ID != "" {
490		parts = append(
491			parts,
492			"  "+formatTokensAndCost(
493				s.session.CompletionTokens+s.session.PromptTokens,
494				model.ContextWindow,
495				s.session.Cost,
496			),
497		)
498	}
499	return lipgloss.JoinVertical(
500		lipgloss.Left,
501		parts...,
502	)
503}
504
505// SetSession implements Sidebar.
506func (m *sidebarCmp) SetSession(session session.Session) tea.Cmd {
507	m.session = session
508	return m.loadSessionFiles
509}
510
511func cwd() string {
512	cwd := config.Get().WorkingDir()
513	t := styles.CurrentTheme()
514	// Replace home directory with ~, unless we're at the top level of the
515	// home directory).
516	homeDir, err := os.UserHomeDir()
517	if err == nil && cwd != homeDir {
518		cwd = strings.ReplaceAll(cwd, homeDir, "~")
519	}
520	return t.S().Muted.Render(cwd)
521}