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() tea.View {
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 tea.NewView(
141 lipgloss.JoinVertical(lipgloss.Left, parts...),
142 )
143}
144
145func (m *sidebarCmp) handleFileHistoryEvent(event pubsub.Event[history.File]) tea.Cmd {
146 return func() tea.Msg {
147 file := event.Payload
148 found := false
149 m.files.Range(func(key, value any) bool {
150 existing := value.(SessionFile)
151 if existing.FilePath == file.Path {
152 if existing.History.latestVersion.Version < file.Version {
153 existing.History.latestVersion = file
154 } else if file.Version == 0 {
155 existing.History.initialVersion = file
156 } else {
157 // If the version is not greater than the latest, we ignore it
158 return true
159 }
160 before := existing.History.initialVersion.Content
161 after := existing.History.latestVersion.Content
162 path := existing.History.initialVersion.Path
163 cwd := config.Get().WorkingDir()
164 path = strings.TrimPrefix(path, cwd)
165 _, additions, deletions := diff.GenerateDiff(before, after, path)
166 existing.Additions = additions
167 existing.Deletions = deletions
168 m.files.Store(file.Path, existing)
169 found = true
170 return false
171 }
172 return true
173 })
174 if found {
175 return nil
176 }
177 sf := SessionFile{
178 History: FileHistory{
179 initialVersion: file,
180 latestVersion: file,
181 },
182 FilePath: file.Path,
183 Additions: 0,
184 Deletions: 0,
185 }
186 m.files.Store(file.Path, sf)
187 return nil
188 }
189}
190
191func (m *sidebarCmp) loadSessionFiles() tea.Msg {
192 files, err := m.history.ListBySession(context.Background(), m.session.ID)
193 if err != nil {
194 return util.InfoMsg{
195 Type: util.InfoTypeError,
196 Msg: err.Error(),
197 }
198 }
199
200 fileMap := make(map[string]FileHistory)
201
202 for _, file := range files {
203 if existing, ok := fileMap[file.Path]; ok {
204 // Update the latest version
205 existing.latestVersion = file
206 fileMap[file.Path] = existing
207 } else {
208 // Add the initial version
209 fileMap[file.Path] = FileHistory{
210 initialVersion: file,
211 latestVersion: file,
212 }
213 }
214 }
215
216 sessionFiles := make([]SessionFile, 0, len(fileMap))
217 for path, fh := range fileMap {
218 cwd := config.Get().WorkingDir()
219 path = strings.TrimPrefix(path, cwd)
220 _, additions, deletions := diff.GenerateDiff(fh.initialVersion.Content, fh.latestVersion.Content, path)
221 sessionFiles = append(sessionFiles, SessionFile{
222 History: fh,
223 FilePath: path,
224 Additions: additions,
225 Deletions: deletions,
226 })
227 }
228
229 return SessionFilesMsg{
230 Files: sessionFiles,
231 }
232}
233
234func (m *sidebarCmp) SetSize(width, height int) tea.Cmd {
235 if width < logoBreakpoint && (m.width == 0 || m.width >= logoBreakpoint) {
236 m.logo = m.logoBlock(true)
237 } else if width >= logoBreakpoint && (m.width == 0 || m.width < logoBreakpoint) {
238 m.logo = m.logoBlock(false)
239 }
240
241 m.width = width
242 m.height = height
243 return nil
244}
245
246func (m *sidebarCmp) GetSize() (int, int) {
247 return m.width, m.height
248}
249
250func (m *sidebarCmp) logoBlock(compact bool) string {
251 t := styles.CurrentTheme()
252 return logo.Render(version.Version, compact, logo.Opts{
253 FieldColor: t.Primary,
254 TitleColorA: t.Secondary,
255 TitleColorB: t.Primary,
256 CharmColor: t.Secondary,
257 VersionColor: t.Primary,
258 })
259}
260
261func (m *sidebarCmp) filesBlock() string {
262 maxWidth := min(m.width, 58)
263 t := styles.CurrentTheme()
264
265 section := t.S().Subtle.Render(
266 core.Section("Modified Files", maxWidth),
267 )
268
269 files := make([]SessionFile, 0)
270 m.files.Range(func(key, value any) bool {
271 file := value.(SessionFile)
272 files = append(files, file)
273 return true // continue iterating
274 })
275 if len(files) == 0 {
276 return lipgloss.JoinVertical(
277 lipgloss.Left,
278 section,
279 "",
280 t.S().Base.Foreground(t.Border).Render("None"),
281 )
282 }
283
284 fileList := []string{section, ""}
285 // order files by the latest version's created time
286 sort.Slice(files, func(i, j int) bool {
287 return files[i].History.latestVersion.CreatedAt > files[j].History.latestVersion.CreatedAt
288 })
289
290 for _, file := range files {
291 if file.Additions == 0 && file.Deletions == 0 {
292 continue // skip files with no changes
293 }
294 var statusParts []string
295 if file.Additions > 0 {
296 statusParts = append(statusParts, t.S().Base.Foreground(t.Success).Render(fmt.Sprintf("+%d", file.Additions)))
297 }
298 if file.Deletions > 0 {
299 statusParts = append(statusParts, t.S().Base.Foreground(t.Error).Render(fmt.Sprintf("-%d", file.Deletions)))
300 }
301
302 extraContent := strings.Join(statusParts, " ")
303 cwd := config.Get().WorkingDir() + string(os.PathSeparator)
304 filePath := file.FilePath
305 filePath = strings.TrimPrefix(filePath, cwd)
306 filePath = fsext.DirTrim(fsext.PrettyPath(filePath), 2)
307 filePath = ansi.Truncate(filePath, maxWidth-lipgloss.Width(extraContent)-2, "…")
308 fileList = append(fileList,
309 core.Status(
310 core.StatusOpts{
311 IconColor: t.FgMuted,
312 NoIcon: true,
313 Title: filePath,
314 ExtraContent: extraContent,
315 },
316 m.width,
317 ),
318 )
319 }
320
321 return lipgloss.JoinVertical(
322 lipgloss.Left,
323 fileList...,
324 )
325}
326
327func (m *sidebarCmp) lspBlock() string {
328 maxWidth := min(m.width, 58)
329 t := styles.CurrentTheme()
330
331 section := t.S().Subtle.Render(
332 core.Section("LSPs", maxWidth),
333 )
334
335 lspList := []string{section, ""}
336
337 lsp := config.Get().LSP
338 if len(lsp) == 0 {
339 return lipgloss.JoinVertical(
340 lipgloss.Left,
341 section,
342 "",
343 t.S().Base.Foreground(t.Border).Render("None"),
344 )
345 }
346
347 for n, l := range lsp {
348 iconColor := t.Success
349 if l.Disabled {
350 iconColor = t.FgMuted
351 }
352 lspErrs := map[protocol.DiagnosticSeverity]int{
353 protocol.SeverityError: 0,
354 protocol.SeverityWarning: 0,
355 protocol.SeverityHint: 0,
356 protocol.SeverityInformation: 0,
357 }
358 if client, ok := m.lspClients[n]; ok {
359 for _, diagnostics := range client.GetDiagnostics() {
360 for _, diagnostic := range diagnostics {
361 if severity, ok := lspErrs[diagnostic.Severity]; ok {
362 lspErrs[diagnostic.Severity] = severity + 1
363 }
364 }
365 }
366 }
367
368 errs := []string{}
369 if lspErrs[protocol.SeverityError] > 0 {
370 errs = append(errs, t.S().Base.Foreground(t.Error).Render(fmt.Sprintf("%s %d", styles.ErrorIcon, lspErrs[protocol.SeverityError])))
371 }
372 if lspErrs[protocol.SeverityWarning] > 0 {
373 errs = append(errs, t.S().Base.Foreground(t.Warning).Render(fmt.Sprintf("%s %d", styles.WarningIcon, lspErrs[protocol.SeverityWarning])))
374 }
375 if lspErrs[protocol.SeverityHint] > 0 {
376 errs = append(errs, t.S().Base.Foreground(t.FgHalfMuted).Render(fmt.Sprintf("%s %d", styles.HintIcon, lspErrs[protocol.SeverityHint])))
377 }
378 if lspErrs[protocol.SeverityInformation] > 0 {
379 errs = append(errs, t.S().Base.Foreground(t.FgHalfMuted).Render(fmt.Sprintf("%s %d", styles.InfoIcon, lspErrs[protocol.SeverityInformation])))
380 }
381
382 lspList = append(lspList,
383 core.Status(
384 core.StatusOpts{
385 IconColor: iconColor,
386 Title: n,
387 Description: l.Command,
388 ExtraContent: strings.Join(errs, " "),
389 },
390 m.width,
391 ),
392 )
393 }
394
395 return lipgloss.JoinVertical(
396 lipgloss.Left,
397 lspList...,
398 )
399}
400
401func (m *sidebarCmp) mcpBlock() string {
402 maxWidth := min(m.width, 58)
403 t := styles.CurrentTheme()
404
405 section := t.S().Subtle.Render(
406 core.Section("MCPs", maxWidth),
407 )
408
409 mcpList := []string{section, ""}
410
411 mcp := config.Get().MCP
412 if len(mcp) == 0 {
413 return lipgloss.JoinVertical(
414 lipgloss.Left,
415 section,
416 "",
417 t.S().Base.Foreground(t.Border).Render("None"),
418 )
419 }
420
421 for n, l := range mcp {
422 iconColor := t.Success
423 mcpList = append(mcpList,
424 core.Status(
425 core.StatusOpts{
426 IconColor: iconColor,
427 Title: n,
428 Description: l.Command,
429 },
430 m.width,
431 ),
432 )
433 }
434
435 return lipgloss.JoinVertical(
436 lipgloss.Left,
437 mcpList...,
438 )
439}
440
441func formatTokensAndCost(tokens, contextWindow int64, cost float64) string {
442 t := styles.CurrentTheme()
443 // Format tokens in human-readable format (e.g., 110K, 1.2M)
444 var formattedTokens string
445 switch {
446 case tokens >= 1_000_000:
447 formattedTokens = fmt.Sprintf("%.1fM", float64(tokens)/1_000_000)
448 case tokens >= 1_000:
449 formattedTokens = fmt.Sprintf("%.1fK", float64(tokens)/1_000)
450 default:
451 formattedTokens = fmt.Sprintf("%d", tokens)
452 }
453
454 // Remove .0 suffix if present
455 if strings.HasSuffix(formattedTokens, ".0K") {
456 formattedTokens = strings.Replace(formattedTokens, ".0K", "K", 1)
457 }
458 if strings.HasSuffix(formattedTokens, ".0M") {
459 formattedTokens = strings.Replace(formattedTokens, ".0M", "M", 1)
460 }
461
462 percentage := (float64(tokens) / float64(contextWindow)) * 100
463
464 baseStyle := t.S().Base
465
466 formattedCost := baseStyle.Foreground(t.FgMuted).Render(fmt.Sprintf("$%.2f", cost))
467
468 formattedTokens = baseStyle.Foreground(t.FgSubtle).Render(fmt.Sprintf("(%s)", formattedTokens))
469 formattedPercentage := baseStyle.Foreground(t.FgMuted).Render(fmt.Sprintf("%d%%", int(percentage)))
470 formattedTokens = fmt.Sprintf("%s %s", formattedPercentage, formattedTokens)
471 if percentage > 80 {
472 // add the warning icon
473 formattedTokens = fmt.Sprintf("%s %s", styles.WarningIcon, formattedTokens)
474 }
475
476 return fmt.Sprintf("%s %s", formattedTokens, formattedCost)
477}
478
479func (s *sidebarCmp) currentModelBlock() string {
480 agentCfg := config.Get().Agents["coder"]
481 model := config.Get().GetModelByType(agentCfg.Model)
482
483 t := styles.CurrentTheme()
484
485 modelIcon := t.S().Base.Foreground(t.FgSubtle).Render(styles.ModelIcon)
486 modelName := t.S().Text.Render(model.Name)
487 modelInfo := fmt.Sprintf("%s %s", modelIcon, modelName)
488 parts := []string{
489 modelInfo,
490 }
491 if s.session.ID != "" {
492 parts = append(
493 parts,
494 " "+formatTokensAndCost(
495 s.session.CompletionTokens+s.session.PromptTokens,
496 model.ContextWindow,
497 s.session.Cost,
498 ),
499 )
500 }
501 return lipgloss.JoinVertical(
502 lipgloss.Left,
503 parts...,
504 )
505}
506
507// SetSession implements Sidebar.
508func (m *sidebarCmp) SetSession(session session.Session) tea.Cmd {
509 m.session = session
510 return m.loadSessionFiles
511}
512
513func cwd() string {
514 cwd := config.Get().WorkingDir()
515 t := styles.CurrentTheme()
516 // Replace home directory with ~, unless we're at the top level of the
517 // home directory).
518 homeDir, err := os.UserHomeDir()
519 if err == nil && cwd != homeDir {
520 cwd = strings.ReplaceAll(cwd, homeDir, "~")
521 }
522 return t.S().Muted.Render(cwd)
523}