1package sidebar
2
3import (
4 "context"
5 "fmt"
6 "os"
7 "slices"
8 "sort"
9 "strings"
10
11 tea "github.com/charmbracelet/bubbletea/v2"
12 "github.com/charmbracelet/catwalk/pkg/catwalk"
13 "github.com/charmbracelet/crush/internal/config"
14 "github.com/charmbracelet/crush/internal/csync"
15 "github.com/charmbracelet/crush/internal/diff"
16 "github.com/charmbracelet/crush/internal/fsext"
17 "github.com/charmbracelet/crush/internal/history"
18 "github.com/charmbracelet/crush/internal/lsp"
19 "github.com/charmbracelet/crush/internal/lsp/protocol"
20 "github.com/charmbracelet/crush/internal/pubsub"
21 "github.com/charmbracelet/crush/internal/session"
22 "github.com/charmbracelet/crush/internal/tui/components/chat"
23 "github.com/charmbracelet/crush/internal/tui/components/core"
24 "github.com/charmbracelet/crush/internal/tui/components/core/layout"
25 "github.com/charmbracelet/crush/internal/tui/components/logo"
26 "github.com/charmbracelet/crush/internal/tui/styles"
27 "github.com/charmbracelet/crush/internal/tui/util"
28 "github.com/charmbracelet/crush/internal/version"
29 "github.com/charmbracelet/lipgloss/v2"
30 "github.com/charmbracelet/x/ansi"
31 "golang.org/x/text/cases"
32 "golang.org/x/text/language"
33)
34
35type FileHistory struct {
36 initialVersion history.File
37 latestVersion history.File
38}
39
40const LogoHeightBreakpoint = 30
41
42// Default maximum number of items to show in each section
43const (
44 DefaultMaxFilesShown = 10
45 DefaultMaxLSPsShown = 8
46 DefaultMaxMCPsShown = 8
47 MinItemsPerSection = 2 // Minimum items to show per section
48)
49
50type SessionFile struct {
51 History FileHistory
52 FilePath string
53 Additions int
54 Deletions int
55}
56type SessionFilesMsg struct {
57 Files []SessionFile
58}
59
60type Sidebar interface {
61 util.Model
62 layout.Sizeable
63 SetSession(session session.Session) tea.Cmd
64 SetCompactMode(bool)
65}
66
67type sidebarCmp struct {
68 width, height int
69 session session.Session
70 logo string
71 cwd string
72 lspClients map[string]*lsp.Client
73 compactMode bool
74 history history.Service
75 files *csync.Map[string, SessionFile]
76}
77
78func New(history history.Service, lspClients map[string]*lsp.Client, compact bool) Sidebar {
79 return &sidebarCmp{
80 lspClients: lspClients,
81 history: history,
82 compactMode: compact,
83 files: csync.NewMap[string, SessionFile](),
84 }
85}
86
87func (m *sidebarCmp) Init() tea.Cmd {
88 return nil
89}
90
91func (m *sidebarCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
92 switch msg := msg.(type) {
93 case SessionFilesMsg:
94 m.files = csync.NewMap[string, SessionFile]()
95 for _, file := range msg.Files {
96 m.files.Set(file.FilePath, file)
97 }
98 return m, nil
99
100 case chat.SessionClearedMsg:
101 m.session = session.Session{}
102 case pubsub.Event[history.File]:
103 return m, m.handleFileHistoryEvent(msg)
104 case pubsub.Event[session.Session]:
105 if msg.Type == pubsub.UpdatedEvent {
106 if m.session.ID == msg.Payload.ID {
107 m.session = msg.Payload
108 }
109 }
110 }
111 return m, nil
112}
113
114func (m *sidebarCmp) View() string {
115 t := styles.CurrentTheme()
116 parts := []string{}
117
118 style := t.S().Base.
119 Width(m.width).
120 Height(m.height).
121 Padding(1)
122 if m.compactMode {
123 style = style.PaddingTop(0)
124 }
125
126 if !m.compactMode {
127 if m.height > LogoHeightBreakpoint {
128 parts = append(parts, m.logo)
129 } else {
130 // Use a smaller logo for smaller screens
131 parts = append(parts,
132 logo.SmallRender(m.width-style.GetHorizontalFrameSize()),
133 "")
134 }
135 }
136
137 if !m.compactMode && m.session.ID != "" {
138 parts = append(parts, t.S().Muted.Render(m.session.Title), "")
139 } else if m.session.ID != "" {
140 parts = append(parts, t.S().Text.Render(m.session.Title), "")
141 }
142
143 if !m.compactMode {
144 parts = append(parts,
145 m.cwd,
146 "",
147 )
148 }
149 parts = append(parts,
150 m.currentModelBlock(),
151 )
152
153 // Check if we should use horizontal layout for sections
154 if m.compactMode && m.width > m.height {
155 // Horizontal layout for compact mode when width > height
156 sectionsContent := m.renderSectionsHorizontal()
157 if sectionsContent != "" {
158 parts = append(parts, "", sectionsContent)
159 }
160 } else {
161 // Vertical layout (default)
162 if m.session.ID != "" {
163 parts = append(parts, "", m.filesBlock())
164 }
165 parts = append(parts,
166 "",
167 m.lspBlock(),
168 "",
169 m.mcpBlock(),
170 )
171 }
172
173 return style.Render(
174 lipgloss.JoinVertical(lipgloss.Left, parts...),
175 )
176}
177
178func (m *sidebarCmp) handleFileHistoryEvent(event pubsub.Event[history.File]) tea.Cmd {
179 return func() tea.Msg {
180 file := event.Payload
181 found := false
182 for existing := range m.files.Seq() {
183 if existing.FilePath != file.Path {
184 continue
185 }
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 }
206 if found {
207 return nil
208 }
209 sf := SessionFile{
210 History: FileHistory{
211 initialVersion: file,
212 latestVersion: file,
213 },
214 FilePath: file.Path,
215 Additions: 0,
216 Deletions: 0,
217 }
218 m.files.Set(file.Path, sf)
219 return nil
220 }
221}
222
223func (m *sidebarCmp) loadSessionFiles() tea.Msg {
224 files, err := m.history.ListBySession(context.Background(), m.session.ID)
225 if err != nil {
226 return util.InfoMsg{
227 Type: util.InfoTypeError,
228 Msg: err.Error(),
229 }
230 }
231
232 fileMap := make(map[string]FileHistory)
233
234 for _, file := range files {
235 if existing, ok := fileMap[file.Path]; ok {
236 // Update the latest version
237 existing.latestVersion = file
238 fileMap[file.Path] = existing
239 } else {
240 // Add the initial version
241 fileMap[file.Path] = FileHistory{
242 initialVersion: file,
243 latestVersion: file,
244 }
245 }
246 }
247
248 sessionFiles := make([]SessionFile, 0, len(fileMap))
249 for path, fh := range fileMap {
250 cwd := config.Get().WorkingDir()
251 path = strings.TrimPrefix(path, cwd)
252 _, additions, deletions := diff.GenerateDiff(fh.initialVersion.Content, fh.latestVersion.Content, path)
253 sessionFiles = append(sessionFiles, SessionFile{
254 History: fh,
255 FilePath: path,
256 Additions: additions,
257 Deletions: deletions,
258 })
259 }
260
261 return SessionFilesMsg{
262 Files: sessionFiles,
263 }
264}
265
266func (m *sidebarCmp) SetSize(width, height int) tea.Cmd {
267 m.logo = m.logoBlock()
268 m.cwd = cwd()
269 m.width = width
270 m.height = height
271 return nil
272}
273
274func (m *sidebarCmp) GetSize() (int, int) {
275 return m.width, m.height
276}
277
278func (m *sidebarCmp) logoBlock() string {
279 t := styles.CurrentTheme()
280 return logo.Render(version.Version, true, logo.Opts{
281 FieldColor: t.Primary,
282 TitleColorA: t.Secondary,
283 TitleColorB: t.Primary,
284 CharmColor: t.Secondary,
285 VersionColor: t.Primary,
286 Width: m.width - 2,
287 })
288}
289
290func (m *sidebarCmp) getMaxWidth() int {
291 return min(m.width-2, 58) // -2 for padding
292}
293
294// calculateAvailableHeight estimates how much height is available for dynamic content
295func (m *sidebarCmp) calculateAvailableHeight() int {
296 usedHeight := 0
297
298 if !m.compactMode {
299 if m.height > LogoHeightBreakpoint {
300 usedHeight += 7 // Approximate logo height
301 } else {
302 usedHeight += 2 // Smaller logo height
303 }
304 usedHeight += 1 // Empty line after logo
305 }
306
307 if m.session.ID != "" {
308 usedHeight += 1 // Title line
309 usedHeight += 1 // Empty line after title
310 }
311
312 if !m.compactMode {
313 usedHeight += 1 // CWD line
314 usedHeight += 1 // Empty line after CWD
315 }
316
317 usedHeight += 2 // Model info
318
319 usedHeight += 6 // 3 sections Γ 2 lines each (header + empty line)
320
321 // Base padding
322 usedHeight += 2 // Top and bottom padding
323
324 return max(0, m.height-usedHeight)
325}
326
327// getDynamicLimits calculates how many items to show in each section based on available height
328func (m *sidebarCmp) getDynamicLimits() (maxFiles, maxLSPs, maxMCPs int) {
329 availableHeight := m.calculateAvailableHeight()
330
331 // If we have very little space, use minimum values
332 if availableHeight < 10 {
333 return MinItemsPerSection, MinItemsPerSection, MinItemsPerSection
334 }
335
336 // Distribute available height among the three sections
337 // Give priority to files, then LSPs, then MCPs
338 totalSections := 3
339 heightPerSection := availableHeight / totalSections
340
341 // Calculate limits for each section, ensuring minimums
342 maxFiles = max(MinItemsPerSection, min(DefaultMaxFilesShown, heightPerSection))
343 maxLSPs = max(MinItemsPerSection, min(DefaultMaxLSPsShown, heightPerSection))
344 maxMCPs = max(MinItemsPerSection, min(DefaultMaxMCPsShown, heightPerSection))
345
346 // If we have extra space, give it to files first
347 remainingHeight := availableHeight - (maxFiles + maxLSPs + maxMCPs)
348 if remainingHeight > 0 {
349 extraForFiles := min(remainingHeight, DefaultMaxFilesShown-maxFiles)
350 maxFiles += extraForFiles
351 remainingHeight -= extraForFiles
352
353 if remainingHeight > 0 {
354 extraForLSPs := min(remainingHeight, DefaultMaxLSPsShown-maxLSPs)
355 maxLSPs += extraForLSPs
356 remainingHeight -= extraForLSPs
357
358 if remainingHeight > 0 {
359 maxMCPs += min(remainingHeight, DefaultMaxMCPsShown-maxMCPs)
360 }
361 }
362 }
363
364 return maxFiles, maxLSPs, maxMCPs
365}
366
367// renderSectionsHorizontal renders the files, LSPs, and MCPs sections horizontally
368func (m *sidebarCmp) renderSectionsHorizontal() string {
369 // Calculate available width for each section
370 totalWidth := m.width - 4 // Account for padding and spacing
371 sectionWidth := min(50, totalWidth/3)
372
373 // Get the sections content with limited height
374 var filesContent, lspContent, mcpContent string
375
376 filesContent = m.filesBlockCompact(sectionWidth)
377 lspContent = m.lspBlockCompact(sectionWidth)
378 mcpContent = m.mcpBlockCompact(sectionWidth)
379
380 return lipgloss.JoinHorizontal(lipgloss.Top, filesContent, " ", lspContent, " ", mcpContent)
381}
382
383// filesBlockCompact renders the files block with limited width and height for horizontal layout
384func (m *sidebarCmp) filesBlockCompact(maxWidth int) string {
385 t := styles.CurrentTheme()
386
387 section := t.S().Subtle.Render("Modified Files")
388
389 files := slices.Collect(m.files.Seq())
390
391 if len(files) == 0 {
392 content := lipgloss.JoinVertical(
393 lipgloss.Left,
394 section,
395 "",
396 t.S().Base.Foreground(t.Border).Render("None"),
397 )
398 return lipgloss.NewStyle().Width(maxWidth).Render(content)
399 }
400
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
407 maxItems := min(5, len(files))
408 availableHeight := m.height - 8 // Reserve space for header and other content
409 if availableHeight > 0 {
410 maxItems = min(maxItems, availableHeight)
411 }
412
413 filesShown := 0
414 for _, file := range files {
415 if file.Additions == 0 && file.Deletions == 0 {
416 continue
417 }
418 if filesShown >= maxItems {
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}
465
466// lspBlockCompact renders the LSP block with limited width and height for horizontal layout
467func (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
486 maxItems := min(5, len(lsp))
487 availableHeight := m.height - 8
488 if availableHeight > 0 {
489 maxItems = min(maxItems, availableHeight)
490 }
491
492 for i, l := range lsp {
493 if i >= maxItems {
494 break
495 }
496
497 iconColor := t.Success
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}
553
554// mcpBlockCompact renders the MCP block with limited width and height for horizontal layout
555func (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
574 maxItems := min(5, len(mcps))
575 availableHeight := m.height - 8
576 if availableHeight > 0 {
577 maxItems = min(maxItems, availableHeight)
578 }
579
580 for i, l := range mcps {
581 if i >= maxItems {
582 break
583 }
584
585 iconColor := t.Success
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}
610
611func (m *sidebarCmp) filesBlock() string {
612 t := styles.CurrentTheme()
613
614 section := t.S().Subtle.Render(
615 core.Section("Modified Files", m.getMaxWidth()),
616 )
617
618 files := slices.Collect(m.files.Seq())
619 if len(files) == 0 {
620 return lipgloss.JoinVertical(
621 lipgloss.Left,
622 section,
623 "",
624 t.S().Base.Foreground(t.Border).Render("None"),
625 )
626 }
627
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
635 maxFiles, _, _ := m.getDynamicLimits()
636 maxFiles = min(len(files), maxFiles)
637 filesShown := 0
638
639 for _, file := range files {
640 if file.Additions == 0 && file.Deletions == 0 {
641 continue // skip files with no changes
642 }
643 if filesShown >= maxFiles {
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}
694
695func (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
715 _, maxLSPs, _ := m.getDynamicLimits()
716 maxLSPs = min(len(lsp), maxLSPs)
717 for i, l := range lsp {
718 if i >= maxLSPs {
719 break
720 }
721
722 iconColor := t.Success
723 if l.LSP.Disabled {
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}
782
783func (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
803 _, _, maxMCPs := m.getDynamicLimits()
804 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
834 return lipgloss.JoinVertical(
835 lipgloss.Left,
836 mcpList...,
837 )
838}
839
840func formatTokensAndCost(tokens, contextWindow int64, cost float64) string {
841 t := styles.CurrentTheme()
842 // Format tokens in human-readable format (e.g., 110K, 1.2M)
843 var formattedTokens string
844 switch {
845 case tokens >= 1_000_000:
846 formattedTokens = fmt.Sprintf("%.1fM", float64(tokens)/1_000_000)
847 case tokens >= 1_000:
848 formattedTokens = fmt.Sprintf("%.1fK", float64(tokens)/1_000)
849 default:
850 formattedTokens = fmt.Sprintf("%d", tokens)
851 }
852
853 // Remove .0 suffix if present
854 if strings.HasSuffix(formattedTokens, ".0K") {
855 formattedTokens = strings.Replace(formattedTokens, ".0K", "K", 1)
856 }
857 if strings.HasSuffix(formattedTokens, ".0M") {
858 formattedTokens = strings.Replace(formattedTokens, ".0M", "M", 1)
859 }
860
861 percentage := (float64(tokens) / float64(contextWindow)) * 100
862
863 baseStyle := t.S().Base
864
865 formattedCost := baseStyle.Foreground(t.FgMuted).Render(fmt.Sprintf("$%.2f", cost))
866
867 formattedTokens = baseStyle.Foreground(t.FgSubtle).Render(fmt.Sprintf("(%s)", formattedTokens))
868 formattedPercentage := baseStyle.Foreground(t.FgMuted).Render(fmt.Sprintf("%d%%", int(percentage)))
869 formattedTokens = fmt.Sprintf("%s %s", formattedPercentage, formattedTokens)
870 if percentage > 80 {
871 // add the warning icon
872 formattedTokens = fmt.Sprintf("%s %s", styles.WarningIcon, formattedTokens)
873 }
874
875 return fmt.Sprintf("%s %s", formattedTokens, formattedCost)
876}
877
878func (s *sidebarCmp) currentModelBlock() string {
879 cfg := config.Get()
880 agentCfg := cfg.Agents["coder"]
881
882 selectedModel := cfg.Models[agentCfg.Model]
883
884 model := config.Get().GetModelByType(agentCfg.Model)
885 modelProvider := config.Get().GetProviderForModel(agentCfg.Model)
886
887 t := styles.CurrentTheme()
888
889 modelIcon := t.S().Base.Foreground(t.FgSubtle).Render(styles.ModelIcon)
890 modelName := t.S().Text.Render(model.Name)
891 modelInfo := fmt.Sprintf("%s %s", modelIcon, modelName)
892 parts := []string{
893 modelInfo,
894 }
895 if model.CanReason {
896 reasoningInfoStyle := t.S().Subtle.PaddingLeft(2)
897 switch modelProvider.Type {
898 case catwalk.TypeOpenAI:
899 reasoningEffort := model.DefaultReasoningEffort
900 if selectedModel.ReasoningEffort != "" {
901 reasoningEffort = selectedModel.ReasoningEffort
902 }
903 formatter := cases.Title(language.English, cases.NoLower)
904 parts = append(parts, reasoningInfoStyle.Render(formatter.String(fmt.Sprintf("Reasoning %s", reasoningEffort))))
905 case catwalk.TypeAnthropic:
906 formatter := cases.Title(language.English, cases.NoLower)
907 if selectedModel.Think {
908 parts = append(parts, reasoningInfoStyle.Render(formatter.String("Thinking on")))
909 } else {
910 parts = append(parts, reasoningInfoStyle.Render(formatter.String("Thinking off")))
911 }
912 }
913 }
914 if s.session.ID != "" {
915 parts = append(
916 parts,
917 " "+formatTokensAndCost(
918 s.session.CompletionTokens+s.session.PromptTokens,
919 model.ContextWindow,
920 s.session.Cost,
921 ),
922 )
923 }
924 return lipgloss.JoinVertical(
925 lipgloss.Left,
926 parts...,
927 )
928}
929
930// SetSession implements Sidebar.
931func (m *sidebarCmp) SetSession(session session.Session) tea.Cmd {
932 m.session = session
933 return m.loadSessionFiles
934}
935
936// SetCompactMode sets the compact mode for the sidebar.
937func (m *sidebarCmp) SetCompactMode(compact bool) {
938 m.compactMode = compact
939}
940
941func cwd() string {
942 cwd := config.Get().WorkingDir()
943 t := styles.CurrentTheme()
944 // Replace home directory with ~, unless we're at the top level of the
945 // home directory).
946 homeDir, err := os.UserHomeDir()
947 if err == nil && cwd != homeDir {
948 cwd = strings.ReplaceAll(cwd, homeDir, "~")
949 }
950 return t.S().Muted.Render(cwd)
951}