status.go 8.0 KB

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