status.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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/pubsub"
  10. "github.com/sst/opencode/internal/status"
  11. "github.com/sst/opencode/internal/styles"
  12. "github.com/sst/opencode/internal/theme"
  13. )
  14. type StatusCmp interface {
  15. tea.Model
  16. }
  17. type statusCmp struct {
  18. app *app.App
  19. queue []status.StatusMessage
  20. width int
  21. messageTTL time.Duration
  22. activeUntil time.Time
  23. }
  24. // clearMessageCmd is a command that clears status messages after a timeout
  25. func (m statusCmp) clearMessageCmd() tea.Cmd {
  26. return tea.Tick(time.Second, func(t time.Time) tea.Msg {
  27. return statusCleanupMsg{time: t}
  28. })
  29. }
  30. // statusCleanupMsg is a message that triggers cleanup of expired status messages
  31. type statusCleanupMsg struct {
  32. time time.Time
  33. }
  34. func (m statusCmp) Init() tea.Cmd {
  35. return m.clearMessageCmd()
  36. }
  37. func (m statusCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
  38. switch msg := msg.(type) {
  39. case tea.WindowSizeMsg:
  40. m.width = msg.Width
  41. return m, nil
  42. case pubsub.Event[status.StatusMessage]:
  43. if msg.Type == status.EventStatusPublished {
  44. // If this is a critical message, move it to the front of the queue
  45. if msg.Payload.Critical {
  46. // Insert at the front of the queue
  47. m.queue = append([]status.StatusMessage{msg.Payload}, m.queue...)
  48. // Reset active time to show critical message immediately
  49. m.activeUntil = time.Time{}
  50. } else {
  51. // Otherwise, just add it to the queue
  52. m.queue = append(m.queue, msg.Payload)
  53. // If this is the first message and nothing is active, activate it immediately
  54. if len(m.queue) == 1 && m.activeUntil.IsZero() {
  55. now := time.Now()
  56. duration := m.messageTTL
  57. if msg.Payload.Duration > 0 {
  58. duration = msg.Payload.Duration
  59. }
  60. m.activeUntil = now.Add(duration)
  61. }
  62. }
  63. }
  64. case statusCleanupMsg:
  65. now := msg.time
  66. // If the active message has expired, remove it and activate the next one
  67. if !m.activeUntil.IsZero() && m.activeUntil.Before(now) {
  68. // Current message expired, remove it if we have one
  69. if len(m.queue) > 0 {
  70. m.queue = m.queue[1:]
  71. }
  72. m.activeUntil = time.Time{}
  73. }
  74. // If we have messages in queue but none are active, activate the first one
  75. if len(m.queue) > 0 && m.activeUntil.IsZero() {
  76. // Use custom duration if specified, otherwise use default
  77. duration := m.messageTTL
  78. if m.queue[0].Duration > 0 {
  79. duration = m.queue[0].Duration
  80. }
  81. m.activeUntil = now.Add(duration)
  82. }
  83. return m, m.clearMessageCmd()
  84. }
  85. return m, nil
  86. }
  87. // getHelpWidget returns the help widget with current theme colors
  88. func getHelpWidget() string {
  89. t := theme.CurrentTheme()
  90. helpText := "ctrl+? help"
  91. return styles.Padded().
  92. Background(t.TextMuted()).
  93. Foreground(t.BackgroundDarker()).
  94. Bold(true).
  95. Render(helpText)
  96. }
  97. func formatTokensAndCost(tokens float32, contextWindow float32, cost float32) string {
  98. // Format tokens in human-readable format (e.g., 110K, 1.2M)
  99. var formattedTokens string
  100. switch {
  101. case tokens >= 1_000_000:
  102. formattedTokens = fmt.Sprintf("%.1fM", float64(tokens)/1_000_000)
  103. case tokens >= 1_000:
  104. formattedTokens = fmt.Sprintf("%.1fK", float64(tokens)/1_000)
  105. default:
  106. formattedTokens = fmt.Sprintf("%d", int(tokens))
  107. }
  108. // Remove .0 suffix if present
  109. if strings.HasSuffix(formattedTokens, ".0K") {
  110. formattedTokens = strings.Replace(formattedTokens, ".0K", "K", 1)
  111. }
  112. if strings.HasSuffix(formattedTokens, ".0M") {
  113. formattedTokens = strings.Replace(formattedTokens, ".0M", "M", 1)
  114. }
  115. // Format cost with $ symbol and 2 decimal places
  116. formattedCost := fmt.Sprintf("$%.2f", cost)
  117. percentage := (float64(tokens) / float64(contextWindow)) * 100
  118. return fmt.Sprintf("Tokens: %s (%d%%), Cost: %s", formattedTokens, int(percentage), formattedCost)
  119. }
  120. func (m statusCmp) View() string {
  121. t := theme.CurrentTheme()
  122. status := getHelpWidget()
  123. if m.app.Session.Id != "" {
  124. tokens := float32(0)
  125. cost := float32(0)
  126. contextWindow := m.app.Model.Limit.Context
  127. for _, message := range m.app.Messages {
  128. if message.Metadata.Assistant != nil {
  129. cost += message.Metadata.Assistant.Cost
  130. usage := message.Metadata.Assistant.Tokens
  131. if usage.Output > 0 {
  132. tokens = (usage.Input + usage.Output + usage.Reasoning)
  133. }
  134. }
  135. }
  136. tokensInfo := styles.Padded().
  137. Background(t.Text()).
  138. Foreground(t.BackgroundSecondary()).
  139. Render(formatTokensAndCost(tokens, contextWindow, cost))
  140. status += tokensInfo
  141. }
  142. diagnostics := styles.Padded().Background(t.BackgroundDarker()).Render(m.projectDiagnostics())
  143. modelName := m.model()
  144. statusWidth := max(
  145. 0,
  146. m.width-
  147. lipgloss.Width(status)-
  148. lipgloss.Width(modelName)-
  149. lipgloss.Width(diagnostics),
  150. )
  151. const minInlineWidth = 30
  152. // Display the first status message if available
  153. var statusMessage string
  154. if len(m.queue) > 0 {
  155. sm := m.queue[0]
  156. infoStyle := styles.Padded().
  157. Foreground(t.Background())
  158. switch sm.Level {
  159. case "info":
  160. infoStyle = infoStyle.Background(t.Info())
  161. case "warn":
  162. infoStyle = infoStyle.Background(t.Warning())
  163. case "error":
  164. infoStyle = infoStyle.Background(t.Error())
  165. case "debug":
  166. infoStyle = infoStyle.Background(t.TextMuted())
  167. }
  168. // Truncate message if it's longer than available width
  169. msg := sm.Message
  170. availWidth := statusWidth - 10
  171. // If we have enough space, show inline
  172. if availWidth >= minInlineWidth {
  173. if len(msg) > availWidth && availWidth > 0 {
  174. msg = msg[:availWidth] + "..."
  175. }
  176. status += infoStyle.Width(statusWidth).Render(msg)
  177. } else {
  178. // Otherwise, prepare a full-width message to show above
  179. if len(msg) > m.width-10 && m.width > 10 {
  180. msg = msg[:m.width-10] + "..."
  181. }
  182. statusMessage = infoStyle.Width(m.width).Render(msg)
  183. // Add empty space in the status bar
  184. status += styles.Padded().
  185. Foreground(t.Text()).
  186. Background(t.BackgroundSecondary()).
  187. Width(statusWidth).
  188. Render("")
  189. }
  190. } else {
  191. status += styles.Padded().
  192. Foreground(t.Text()).
  193. Background(t.BackgroundSecondary()).
  194. Width(statusWidth).
  195. Render("")
  196. }
  197. status += diagnostics
  198. status += modelName
  199. // If we have a separate status message, prepend it
  200. if statusMessage != "" {
  201. return statusMessage + "\n" + status
  202. } else {
  203. blank := styles.BaseStyle().Background(t.Background()).Width(m.width).Render("")
  204. return blank + "\n" + status
  205. }
  206. }
  207. func (m *statusCmp) projectDiagnostics() string {
  208. t := theme.CurrentTheme()
  209. // Check if any LSP server is still initializing
  210. initializing := false
  211. // for _, client := range m.app.LSPClients {
  212. // if client.GetServerState() == lsp.StateStarting {
  213. // initializing = true
  214. // break
  215. // }
  216. // }
  217. // If any server is initializing, show that status
  218. if initializing {
  219. return lipgloss.NewStyle().
  220. Foreground(t.Warning()).
  221. Render(fmt.Sprintf("%s Initializing LSP...", styles.SpinnerIcon))
  222. }
  223. // errorDiagnostics := []protocol.Diagnostic{}
  224. // warnDiagnostics := []protocol.Diagnostic{}
  225. // hintDiagnostics := []protocol.Diagnostic{}
  226. // infoDiagnostics := []protocol.Diagnostic{}
  227. // for _, client := range m.app.LSPClients {
  228. // for _, d := range client.GetDiagnostics() {
  229. // for _, diag := range d {
  230. // switch diag.Severity {
  231. // case protocol.SeverityError:
  232. // errorDiagnostics = append(errorDiagnostics, diag)
  233. // case protocol.SeverityWarning:
  234. // warnDiagnostics = append(warnDiagnostics, diag)
  235. // case protocol.SeverityHint:
  236. // hintDiagnostics = append(hintDiagnostics, diag)
  237. // case protocol.SeverityInformation:
  238. // infoDiagnostics = append(infoDiagnostics, diag)
  239. // }
  240. // }
  241. // }
  242. // }
  243. return styles.ForceReplaceBackgroundWithLipgloss(
  244. styles.Padded().Render("No diagnostics"),
  245. t.BackgroundDarker(),
  246. )
  247. // if len(errorDiagnostics) == 0 &&
  248. // len(warnDiagnostics) == 0 &&
  249. // len(infoDiagnostics) == 0 &&
  250. // len(hintDiagnostics) == 0 {
  251. // return styles.ForceReplaceBackgroundWithLipgloss(
  252. // styles.Padded().Render("No diagnostics"),
  253. // t.BackgroundDarker(),
  254. // )
  255. // }
  256. // diagnostics := []string{}
  257. //
  258. // errStr := lipgloss.NewStyle().
  259. // Background(t.BackgroundDarker()).
  260. // Foreground(t.Error()).
  261. // Render(fmt.Sprintf("%s %d", styles.ErrorIcon, len(errorDiagnostics)))
  262. // diagnostics = append(diagnostics, errStr)
  263. //
  264. // warnStr := lipgloss.NewStyle().
  265. // Background(t.BackgroundDarker()).
  266. // Foreground(t.Warning()).
  267. // Render(fmt.Sprintf("%s %d", styles.WarningIcon, len(warnDiagnostics)))
  268. // diagnostics = append(diagnostics, warnStr)
  269. //
  270. // infoStr := lipgloss.NewStyle().
  271. // Background(t.BackgroundDarker()).
  272. // Foreground(t.Info()).
  273. // Render(fmt.Sprintf("%s %d", styles.InfoIcon, len(infoDiagnostics)))
  274. // diagnostics = append(diagnostics, infoStr)
  275. //
  276. // hintStr := lipgloss.NewStyle().
  277. // Background(t.BackgroundDarker()).
  278. // Foreground(t.Text()).
  279. // Render(fmt.Sprintf("%s %d", styles.HintIcon, len(hintDiagnostics)))
  280. // diagnostics = append(diagnostics, hintStr)
  281. //
  282. // return styles.ForceReplaceBackgroundWithLipgloss(
  283. // styles.Padded().Render(strings.Join(diagnostics, " ")),
  284. // t.BackgroundDarker(),
  285. // )
  286. }
  287. func (m statusCmp) model() string {
  288. t := theme.CurrentTheme()
  289. model := "None"
  290. if m.app.Model != nil {
  291. model = *m.app.Model.Name
  292. }
  293. return styles.Padded().
  294. Background(t.Secondary()).
  295. Foreground(t.Background()).
  296. Render(model)
  297. }
  298. func NewStatusCmp(app *app.App) StatusCmp {
  299. statusComponent := &statusCmp{
  300. app: app,
  301. queue: []status.StatusMessage{},
  302. messageTTL: 4 * time.Second,
  303. activeUntil: time.Time{},
  304. }
  305. return statusComponent
  306. }