status.go 9.9 KB

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