status.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  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. queue []status.StatusMessage
  25. width int
  26. messageTTL time.Duration
  27. activeUntil time.Time
  28. }
  29. // clearMessageCmd is a command that clears status messages after a timeout
  30. func (m statusCmp) clearMessageCmd() tea.Cmd {
  31. return tea.Tick(time.Second, func(t time.Time) tea.Msg {
  32. return statusCleanupMsg{time: t}
  33. })
  34. }
  35. // statusCleanupMsg is a message that triggers cleanup of expired status messages
  36. type statusCleanupMsg struct {
  37. time time.Time
  38. }
  39. func (m statusCmp) Init() tea.Cmd {
  40. return m.clearMessageCmd()
  41. }
  42. func (m statusCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
  43. switch msg := msg.(type) {
  44. case tea.WindowSizeMsg:
  45. m.width = msg.Width
  46. return m, nil
  47. case pubsub.Event[status.StatusMessage]:
  48. if msg.Type == status.EventStatusPublished {
  49. // If this is a critical message, move it to the front of the queue
  50. if msg.Payload.Critical {
  51. // Insert at the front of the queue
  52. m.queue = append([]status.StatusMessage{msg.Payload}, m.queue...)
  53. // Reset active time to show critical message immediately
  54. m.activeUntil = time.Time{}
  55. } else {
  56. // Otherwise, just add it to the queue
  57. m.queue = append(m.queue, msg.Payload)
  58. // If this is the first message and nothing is active, activate it immediately
  59. if len(m.queue) == 1 && m.activeUntil.IsZero() {
  60. now := time.Now()
  61. duration := m.messageTTL
  62. if msg.Payload.Duration > 0 {
  63. duration = msg.Payload.Duration
  64. }
  65. m.activeUntil = now.Add(duration)
  66. }
  67. }
  68. }
  69. case statusCleanupMsg:
  70. now := msg.time
  71. // If the active message has expired, remove it and activate the next one
  72. if !m.activeUntil.IsZero() && m.activeUntil.Before(now) {
  73. // Current message expired, remove it if we have one
  74. if len(m.queue) > 0 {
  75. m.queue = m.queue[1:]
  76. }
  77. m.activeUntil = time.Time{}
  78. }
  79. // If we have messages in queue but none are active, activate the first one
  80. if len(m.queue) > 0 && m.activeUntil.IsZero() {
  81. // Use custom duration if specified, otherwise use default
  82. duration := m.messageTTL
  83. if m.queue[0].Duration > 0 {
  84. duration = m.queue[0].Duration
  85. }
  86. m.activeUntil = now.Add(duration)
  87. }
  88. return m, m.clearMessageCmd()
  89. }
  90. return m, nil
  91. }
  92. var helpWidget = ""
  93. // getHelpWidget returns the help widget with current theme colors
  94. func getHelpWidget(helpText string) string {
  95. t := theme.CurrentTheme()
  96. if helpText == "" {
  97. helpText = "ctrl+? help"
  98. }
  99. return styles.Padded().
  100. Background(t.TextMuted()).
  101. Foreground(t.BackgroundDarker()).
  102. Bold(true).
  103. Render(helpText)
  104. }
  105. func formatTokensAndCost(tokens int64, contextWindow int64, cost float64) string {
  106. // Format tokens in human-readable format (e.g., 110K, 1.2M)
  107. var formattedTokens string
  108. switch {
  109. case tokens >= 1_000_000:
  110. formattedTokens = fmt.Sprintf("%.1fM", float64(tokens)/1_000_000)
  111. case tokens >= 1_000:
  112. formattedTokens = fmt.Sprintf("%.1fK", float64(tokens)/1_000)
  113. default:
  114. formattedTokens = fmt.Sprintf("%d", tokens)
  115. }
  116. // Remove .0 suffix if present
  117. if strings.HasSuffix(formattedTokens, ".0K") {
  118. formattedTokens = strings.Replace(formattedTokens, ".0K", "K", 1)
  119. }
  120. if strings.HasSuffix(formattedTokens, ".0M") {
  121. formattedTokens = strings.Replace(formattedTokens, ".0M", "M", 1)
  122. }
  123. // Format cost with $ symbol and 2 decimal places
  124. formattedCost := fmt.Sprintf("$%.2f", cost)
  125. percentage := (float64(tokens) / float64(contextWindow)) * 100
  126. return fmt.Sprintf("Tokens: %s (%d%%), Cost: %s", formattedTokens, int(percentage), formattedCost)
  127. }
  128. func (m statusCmp) View() string {
  129. t := theme.CurrentTheme()
  130. modelID := config.Get().Agents[config.AgentPrimary].Model
  131. model := models.SupportedModels[modelID]
  132. // Initialize the help widget
  133. status := getHelpWidget("")
  134. if m.app.CurrentSession.ID != "" {
  135. tokens := formatTokensAndCost(m.app.CurrentSession.PromptTokens+m.app.CurrentSession.CompletionTokens, model.ContextWindow, m.app.CurrentSession.Cost)
  136. tokensStyle := styles.Padded().
  137. Background(t.Text()).
  138. Foreground(t.BackgroundSecondary()).
  139. Render(tokens)
  140. status += tokensStyle
  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. if len(errorDiagnostics) == 0 &&
  244. len(warnDiagnostics) == 0 &&
  245. len(infoDiagnostics) == 0 &&
  246. len(hintDiagnostics) == 0 {
  247. return styles.ForceReplaceBackgroundWithLipgloss(
  248. styles.Padded().Render("No diagnostics"),
  249. t.BackgroundDarker(),
  250. )
  251. }
  252. diagnostics := []string{}
  253. errStr := lipgloss.NewStyle().
  254. Background(t.BackgroundDarker()).
  255. Foreground(t.Error()).
  256. Render(fmt.Sprintf("%s %d", styles.ErrorIcon, len(errorDiagnostics)))
  257. diagnostics = append(diagnostics, errStr)
  258. warnStr := lipgloss.NewStyle().
  259. Background(t.BackgroundDarker()).
  260. Foreground(t.Warning()).
  261. Render(fmt.Sprintf("%s %d", styles.WarningIcon, len(warnDiagnostics)))
  262. diagnostics = append(diagnostics, warnStr)
  263. infoStr := lipgloss.NewStyle().
  264. Background(t.BackgroundDarker()).
  265. Foreground(t.Info()).
  266. Render(fmt.Sprintf("%s %d", styles.InfoIcon, len(infoDiagnostics)))
  267. diagnostics = append(diagnostics, infoStr)
  268. hintStr := lipgloss.NewStyle().
  269. Background(t.BackgroundDarker()).
  270. Foreground(t.Text()).
  271. Render(fmt.Sprintf("%s %d", styles.HintIcon, len(hintDiagnostics)))
  272. diagnostics = append(diagnostics, hintStr)
  273. return styles.ForceReplaceBackgroundWithLipgloss(
  274. styles.Padded().Render(strings.Join(diagnostics, " ")),
  275. t.BackgroundDarker(),
  276. )
  277. }
  278. func (m statusCmp) model() string {
  279. t := theme.CurrentTheme()
  280. cfg := config.Get()
  281. coder, ok := cfg.Agents[config.AgentPrimary]
  282. if !ok {
  283. return "Unknown"
  284. }
  285. model := models.SupportedModels[coder.Model]
  286. return styles.Padded().
  287. Background(t.Secondary()).
  288. Foreground(t.Background()).
  289. Render(model.Name)
  290. }
  291. func (m statusCmp) SetHelpWidgetMsg(s string) {
  292. // Update the help widget text using the getHelpWidget function
  293. helpWidget = getHelpWidget(s)
  294. }
  295. func NewStatusCmp(app *app.App) StatusCmp {
  296. // Initialize the help widget with default text
  297. helpWidget = getHelpWidget("")
  298. statusComponent := &statusCmp{
  299. app: app,
  300. queue: []status.StatusMessage{},
  301. messageTTL: 4 * time.Second,
  302. activeUntil: time.Time{},
  303. }
  304. return statusComponent
  305. }