status.go 7.1 KB

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