status.go 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. package core
  2. import (
  3. "fmt"
  4. "strings"
  5. "time"
  6. tea "github.com/charmbracelet/bubbletea"
  7. "github.com/charmbracelet/lipgloss"
  8. "github.com/sst/opencode/internal/app"
  9. "github.com/sst/opencode/internal/config"
  10. "github.com/sst/opencode/internal/llm/models"
  11. "github.com/sst/opencode/internal/lsp"
  12. "github.com/sst/opencode/internal/lsp/protocol"
  13. "github.com/sst/opencode/internal/pubsub"
  14. "github.com/sst/opencode/internal/status"
  15. "github.com/sst/opencode/internal/tui/styles"
  16. "github.com/sst/opencode/internal/tui/theme"
  17. )
  18. type StatusCmp interface {
  19. tea.Model
  20. SetHelpWidgetMsg(string)
  21. }
  22. type statusCmp struct {
  23. app *app.App
  24. statusMessages []statusMessage
  25. width int
  26. messageTTL time.Duration
  27. }
  28. type statusMessage struct {
  29. Level status.Level
  30. Message string
  31. Timestamp time.Time
  32. ExpiresAt time.Time
  33. }
  34. // clearMessageCmd is a command that clears status messages after a timeout
  35. func (m statusCmp) clearMessageCmd() tea.Cmd {
  36. return tea.Tick(time.Second, func(t time.Time) tea.Msg {
  37. return statusCleanupMsg{time: t}
  38. })
  39. }
  40. // statusCleanupMsg is a message that triggers cleanup of expired status messages
  41. type statusCleanupMsg struct {
  42. time time.Time
  43. }
  44. func (m statusCmp) Init() tea.Cmd {
  45. return m.clearMessageCmd()
  46. }
  47. func (m statusCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
  48. switch msg := msg.(type) {
  49. case tea.WindowSizeMsg:
  50. m.width = msg.Width
  51. return m, nil
  52. case pubsub.Event[status.StatusMessage]:
  53. if msg.Type == status.EventStatusPublished {
  54. statusMsg := statusMessage{
  55. Level: msg.Payload.Level,
  56. Message: msg.Payload.Message,
  57. Timestamp: msg.Payload.Timestamp,
  58. ExpiresAt: msg.Payload.Timestamp.Add(m.messageTTL),
  59. }
  60. m.statusMessages = append(m.statusMessages, statusMsg)
  61. }
  62. case statusCleanupMsg:
  63. // Remove expired messages
  64. var activeMessages []statusMessage
  65. for _, sm := range m.statusMessages {
  66. if sm.ExpiresAt.After(msg.time) {
  67. activeMessages = append(activeMessages, sm)
  68. }
  69. }
  70. m.statusMessages = activeMessages
  71. return m, m.clearMessageCmd()
  72. }
  73. return m, nil
  74. }
  75. var helpWidget = ""
  76. // getHelpWidget returns the help widget with current theme colors
  77. func getHelpWidget(helpText string) string {
  78. t := theme.CurrentTheme()
  79. if helpText == "" {
  80. helpText = "ctrl+? help"
  81. }
  82. return styles.Padded().
  83. Background(t.TextMuted()).
  84. Foreground(t.BackgroundDarker()).
  85. Bold(true).
  86. Render(helpText)
  87. }
  88. func formatTokensAndCost(tokens int64, contextWindow int64, cost float64) string {
  89. // Format tokens in human-readable format (e.g., 110K, 1.2M)
  90. var formattedTokens string
  91. switch {
  92. case tokens >= 1_000_000:
  93. formattedTokens = fmt.Sprintf("%.1fM", float64(tokens)/1_000_000)
  94. case tokens >= 1_000:
  95. formattedTokens = fmt.Sprintf("%.1fK", float64(tokens)/1_000)
  96. default:
  97. formattedTokens = fmt.Sprintf("%d", tokens)
  98. }
  99. // Remove .0 suffix if present
  100. if strings.HasSuffix(formattedTokens, ".0K") {
  101. formattedTokens = strings.Replace(formattedTokens, ".0K", "K", 1)
  102. }
  103. if strings.HasSuffix(formattedTokens, ".0M") {
  104. formattedTokens = strings.Replace(formattedTokens, ".0M", "M", 1)
  105. }
  106. // Format cost with $ symbol and 2 decimal places
  107. formattedCost := fmt.Sprintf("$%.2f", cost)
  108. percentage := (float64(tokens) / float64(contextWindow)) * 100
  109. return fmt.Sprintf("Tokens: %s (%d%%), Cost: %s", formattedTokens, int(percentage), formattedCost)
  110. }
  111. func (m statusCmp) View() string {
  112. t := theme.CurrentTheme()
  113. modelID := config.Get().Agents[config.AgentPrimary].Model
  114. model := models.SupportedModels[modelID]
  115. // Initialize the help widget
  116. status := getHelpWidget("")
  117. if m.app.CurrentSession.ID != "" {
  118. tokens := formatTokensAndCost(m.app.CurrentSession.PromptTokens+m.app.CurrentSession.CompletionTokens, model.ContextWindow, m.app.CurrentSession.Cost)
  119. tokensStyle := styles.Padded().
  120. Background(t.Text()).
  121. Foreground(t.BackgroundSecondary()).
  122. Render(tokens)
  123. status += tokensStyle
  124. }
  125. diagnostics := styles.Padded().Background(t.BackgroundDarker()).Render(m.projectDiagnostics())
  126. modelName := m.model()
  127. statusWidth := max(
  128. 0,
  129. m.width-
  130. lipgloss.Width(status)-
  131. lipgloss.Width(modelName)-
  132. lipgloss.Width(diagnostics),
  133. )
  134. // Display the first status message if available
  135. if len(m.statusMessages) > 0 {
  136. sm := m.statusMessages[0]
  137. infoStyle := styles.Padded().
  138. Foreground(t.Background()).
  139. Width(statusWidth)
  140. switch sm.Level {
  141. case "info":
  142. infoStyle = infoStyle.Background(t.Info())
  143. case "warn":
  144. infoStyle = infoStyle.Background(t.Warning())
  145. case "error":
  146. infoStyle = infoStyle.Background(t.Error())
  147. case "debug":
  148. infoStyle = infoStyle.Background(t.TextMuted())
  149. }
  150. // Truncate message if it's longer than available width
  151. msg := sm.Message
  152. availWidth := statusWidth - 10
  153. if len(msg) > availWidth && availWidth > 0 {
  154. msg = msg[:availWidth] + "..."
  155. }
  156. status += infoStyle.Render(msg)
  157. } else {
  158. status += styles.Padded().
  159. Foreground(t.Text()).
  160. Background(t.BackgroundSecondary()).
  161. Width(statusWidth).
  162. Render("")
  163. }
  164. status += diagnostics
  165. status += modelName
  166. return status
  167. }
  168. func (m *statusCmp) projectDiagnostics() string {
  169. t := theme.CurrentTheme()
  170. // Check if any LSP server is still initializing
  171. initializing := false
  172. for _, client := range m.app.LSPClients {
  173. if client.GetServerState() == lsp.StateStarting {
  174. initializing = true
  175. break
  176. }
  177. }
  178. // If any server is initializing, show that status
  179. if initializing {
  180. return lipgloss.NewStyle().
  181. Foreground(t.Warning()).
  182. Render(fmt.Sprintf("%s Initializing LSP...", styles.SpinnerIcon))
  183. }
  184. errorDiagnostics := []protocol.Diagnostic{}
  185. warnDiagnostics := []protocol.Diagnostic{}
  186. hintDiagnostics := []protocol.Diagnostic{}
  187. infoDiagnostics := []protocol.Diagnostic{}
  188. for _, client := range m.app.LSPClients {
  189. for _, d := range client.GetDiagnostics() {
  190. for _, diag := range d {
  191. switch diag.Severity {
  192. case protocol.SeverityError:
  193. errorDiagnostics = append(errorDiagnostics, diag)
  194. case protocol.SeverityWarning:
  195. warnDiagnostics = append(warnDiagnostics, diag)
  196. case protocol.SeverityHint:
  197. hintDiagnostics = append(hintDiagnostics, diag)
  198. case protocol.SeverityInformation:
  199. infoDiagnostics = append(infoDiagnostics, diag)
  200. }
  201. }
  202. }
  203. }
  204. diagnostics := []string{}
  205. errStr := lipgloss.NewStyle().
  206. Background(t.BackgroundDarker()).
  207. Foreground(t.Error()).
  208. Render(fmt.Sprintf("%s %d", styles.ErrorIcon, len(errorDiagnostics)))
  209. diagnostics = append(diagnostics, errStr)
  210. warnStr := lipgloss.NewStyle().
  211. Background(t.BackgroundDarker()).
  212. Foreground(t.Warning()).
  213. Render(fmt.Sprintf("%s %d", styles.WarningIcon, len(warnDiagnostics)))
  214. diagnostics = append(diagnostics, warnStr)
  215. infoStr := lipgloss.NewStyle().
  216. Background(t.BackgroundDarker()).
  217. Foreground(t.Info()).
  218. Render(fmt.Sprintf("%s %d", styles.InfoIcon, len(infoDiagnostics)))
  219. diagnostics = append(diagnostics, infoStr)
  220. hintStr := lipgloss.NewStyle().
  221. Background(t.BackgroundDarker()).
  222. Foreground(t.Text()).
  223. Render(fmt.Sprintf("%s %d", styles.HintIcon, len(hintDiagnostics)))
  224. diagnostics = append(diagnostics, hintStr)
  225. return styles.ForceReplaceBackgroundWithLipgloss(
  226. styles.Padded().Render(strings.Join(diagnostics, " ")),
  227. t.BackgroundDarker(),
  228. )
  229. }
  230. func (m statusCmp) model() string {
  231. t := theme.CurrentTheme()
  232. cfg := config.Get()
  233. coder, ok := cfg.Agents[config.AgentPrimary]
  234. if !ok {
  235. return "Unknown"
  236. }
  237. model := models.SupportedModels[coder.Model]
  238. return styles.Padded().
  239. Background(t.Secondary()).
  240. Foreground(t.Background()).
  241. Render(model.Name)
  242. }
  243. func (m statusCmp) SetHelpWidgetMsg(s string) {
  244. // Update the help widget text using the getHelpWidget function
  245. helpWidget = getHelpWidget(s)
  246. }
  247. func NewStatusCmp(app *app.App) StatusCmp {
  248. // Initialize the help widget with default text
  249. helpWidget = getHelpWidget("")
  250. statusComponent := &statusCmp{
  251. app: app,
  252. statusMessages: []statusMessage{},
  253. messageTTL: 4 * time.Second,
  254. }
  255. return statusComponent
  256. }