status.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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/config"
  9. "github.com/sst/opencode/internal/llm/models"
  10. "github.com/sst/opencode/internal/lsp"
  11. "github.com/sst/opencode/internal/lsp/protocol"
  12. "github.com/sst/opencode/internal/pubsub"
  13. "github.com/sst/opencode/internal/session"
  14. "github.com/sst/opencode/internal/status"
  15. "github.com/sst/opencode/internal/tui/components/chat"
  16. "github.com/sst/opencode/internal/tui/styles"
  17. "github.com/sst/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, contextWindow 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. percentage := (float64(tokens) / float64(contextWindow)) * 100
  121. return fmt.Sprintf("Tokens: %s (%d%%), Cost: %s", formattedTokens, int(percentage), formattedCost)
  122. }
  123. func (m statusCmp) View() string {
  124. t := theme.CurrentTheme()
  125. modelID := config.Get().Agents[config.AgentPrimary].Model
  126. model := models.SupportedModels[modelID]
  127. // Initialize the help widget
  128. status := getHelpWidget("")
  129. if m.session.ID != "" {
  130. tokens := formatTokensAndCost(m.session.PromptTokens+m.session.CompletionTokens, model.ContextWindow, m.session.Cost)
  131. tokensStyle := styles.Padded().
  132. Background(t.Text()).
  133. Foreground(t.BackgroundSecondary()).
  134. Render(tokens)
  135. status += tokensStyle
  136. }
  137. diagnostics := styles.Padded().Background(t.BackgroundDarker()).Render(m.projectDiagnostics())
  138. modelName := m.model()
  139. statusWidth := max(
  140. 0,
  141. m.width-
  142. lipgloss.Width(status)-
  143. lipgloss.Width(modelName)-
  144. lipgloss.Width(diagnostics),
  145. )
  146. // Display the first status message if available
  147. if len(m.statusMessages) > 0 {
  148. sm := m.statusMessages[0]
  149. infoStyle := styles.Padded().
  150. Foreground(t.Background()).
  151. Width(statusWidth)
  152. switch sm.Level {
  153. case "info":
  154. infoStyle = infoStyle.Background(t.Info())
  155. case "warn":
  156. infoStyle = infoStyle.Background(t.Warning())
  157. case "error":
  158. infoStyle = infoStyle.Background(t.Error())
  159. case "debug":
  160. infoStyle = infoStyle.Background(t.TextMuted())
  161. }
  162. // Truncate message if it's longer than available width
  163. msg := sm.Message
  164. availWidth := statusWidth - 10
  165. if len(msg) > availWidth && availWidth > 0 {
  166. msg = msg[:availWidth] + "..."
  167. }
  168. status += infoStyle.Render(msg)
  169. } else {
  170. status += styles.Padded().
  171. Foreground(t.Text()).
  172. Background(t.BackgroundSecondary()).
  173. Width(statusWidth).
  174. Render("")
  175. }
  176. status += diagnostics
  177. status += modelName
  178. return status
  179. }
  180. func (m *statusCmp) projectDiagnostics() string {
  181. t := theme.CurrentTheme()
  182. // Check if any LSP server is still initializing
  183. initializing := false
  184. for _, client := range m.lspClients {
  185. if client.GetServerState() == lsp.StateStarting {
  186. initializing = true
  187. break
  188. }
  189. }
  190. // If any server is initializing, show that status
  191. if initializing {
  192. return lipgloss.NewStyle().
  193. Foreground(t.Warning()).
  194. Render(fmt.Sprintf("%s Initializing LSP...", styles.SpinnerIcon))
  195. }
  196. errorDiagnostics := []protocol.Diagnostic{}
  197. warnDiagnostics := []protocol.Diagnostic{}
  198. hintDiagnostics := []protocol.Diagnostic{}
  199. infoDiagnostics := []protocol.Diagnostic{}
  200. for _, client := range m.lspClients {
  201. for _, d := range client.GetDiagnostics() {
  202. for _, diag := range d {
  203. switch diag.Severity {
  204. case protocol.SeverityError:
  205. errorDiagnostics = append(errorDiagnostics, diag)
  206. case protocol.SeverityWarning:
  207. warnDiagnostics = append(warnDiagnostics, diag)
  208. case protocol.SeverityHint:
  209. hintDiagnostics = append(hintDiagnostics, diag)
  210. case protocol.SeverityInformation:
  211. infoDiagnostics = append(infoDiagnostics, diag)
  212. }
  213. }
  214. }
  215. }
  216. diagnostics := []string{}
  217. errStr := lipgloss.NewStyle().
  218. Background(t.BackgroundDarker()).
  219. Foreground(t.Error()).
  220. Render(fmt.Sprintf("%s %d", styles.ErrorIcon, len(errorDiagnostics)))
  221. diagnostics = append(diagnostics, errStr)
  222. warnStr := lipgloss.NewStyle().
  223. Background(t.BackgroundDarker()).
  224. Foreground(t.Warning()).
  225. Render(fmt.Sprintf("%s %d", styles.WarningIcon, len(warnDiagnostics)))
  226. diagnostics = append(diagnostics, warnStr)
  227. infoStr := lipgloss.NewStyle().
  228. Background(t.BackgroundDarker()).
  229. Foreground(t.Info()).
  230. Render(fmt.Sprintf("%s %d", styles.InfoIcon, len(infoDiagnostics)))
  231. diagnostics = append(diagnostics, infoStr)
  232. hintStr := lipgloss.NewStyle().
  233. Background(t.BackgroundDarker()).
  234. Foreground(t.Text()).
  235. Render(fmt.Sprintf("%s %d", styles.HintIcon, len(hintDiagnostics)))
  236. diagnostics = append(diagnostics, hintStr)
  237. return styles.ForceReplaceBackgroundWithLipgloss(
  238. styles.Padded().Render(strings.Join(diagnostics, " ")),
  239. t.BackgroundDarker(),
  240. )
  241. }
  242. func (m statusCmp) model() string {
  243. t := theme.CurrentTheme()
  244. cfg := config.Get()
  245. coder, ok := cfg.Agents[config.AgentPrimary]
  246. if !ok {
  247. return "Unknown"
  248. }
  249. model := models.SupportedModels[coder.Model]
  250. return styles.Padded().
  251. Background(t.Secondary()).
  252. Foreground(t.Background()).
  253. Render(model.Name)
  254. }
  255. func (m statusCmp) SetHelpWidgetMsg(s string) {
  256. // Update the help widget text using the getHelpWidget function
  257. helpWidget = getHelpWidget(s)
  258. }
  259. func NewStatusCmp(lspClients map[string]*lsp.Client) StatusCmp {
  260. // Initialize the help widget with default text
  261. helpWidget = getHelpWidget("")
  262. statusComponent := &statusCmp{
  263. statusMessages: []statusMessage{},
  264. messageTTL: 4 * time.Second,
  265. lspClients: lspClients,
  266. }
  267. return statusComponent
  268. }