status.go 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  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 int64, contextWindow int64, cost float64) 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", 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.CurrentSessionOLD.ID != "" {
  131. // tokens := formatTokensAndCost(m.app.CurrentSessionOLD.PromptTokens+m.app.CurrentSessionOLD.CompletionTokens, model.ContextWindow, m.app.CurrentSessionOLD.Cost)
  132. // tokensStyle := styles.Padded().
  133. // Background(t.Text()).
  134. // Foreground(t.BackgroundSecondary()).
  135. // Render(tokens)
  136. // status += tokensStyle
  137. // }
  138. diagnostics := styles.Padded().Background(t.BackgroundDarker()).Render(m.projectDiagnostics())
  139. modelName := m.model()
  140. statusWidth := max(
  141. 0,
  142. m.width-
  143. lipgloss.Width(status)-
  144. lipgloss.Width(modelName)-
  145. lipgloss.Width(diagnostics),
  146. )
  147. const minInlineWidth = 30
  148. // Display the first status message if available
  149. var statusMessage string
  150. if len(m.queue) > 0 {
  151. sm := m.queue[0]
  152. infoStyle := styles.Padded().
  153. Foreground(t.Background())
  154. switch sm.Level {
  155. case "info":
  156. infoStyle = infoStyle.Background(t.Info())
  157. case "warn":
  158. infoStyle = infoStyle.Background(t.Warning())
  159. case "error":
  160. infoStyle = infoStyle.Background(t.Error())
  161. case "debug":
  162. infoStyle = infoStyle.Background(t.TextMuted())
  163. }
  164. // Truncate message if it's longer than available width
  165. msg := sm.Message
  166. availWidth := statusWidth - 10
  167. // If we have enough space, show inline
  168. if availWidth >= minInlineWidth {
  169. if len(msg) > availWidth && availWidth > 0 {
  170. msg = msg[:availWidth] + "..."
  171. }
  172. status += infoStyle.Width(statusWidth).Render(msg)
  173. } else {
  174. // Otherwise, prepare a full-width message to show above
  175. if len(msg) > m.width-10 && m.width > 10 {
  176. msg = msg[:m.width-10] + "..."
  177. }
  178. statusMessage = infoStyle.Width(m.width).Render(msg)
  179. // Add empty space in the status bar
  180. status += styles.Padded().
  181. Foreground(t.Text()).
  182. Background(t.BackgroundSecondary()).
  183. Width(statusWidth).
  184. Render("")
  185. }
  186. } else {
  187. status += styles.Padded().
  188. Foreground(t.Text()).
  189. Background(t.BackgroundSecondary()).
  190. Width(statusWidth).
  191. Render("")
  192. }
  193. status += diagnostics
  194. status += modelName
  195. // If we have a separate status message, prepend it
  196. if statusMessage != "" {
  197. return statusMessage + "\n" + status
  198. } else {
  199. blank := styles.BaseStyle().Background(t.Background()).Width(m.width).Render("")
  200. return blank + "\n" + status
  201. }
  202. }
  203. func (m *statusCmp) projectDiagnostics() string {
  204. t := theme.CurrentTheme()
  205. // Check if any LSP server is still initializing
  206. initializing := false
  207. // for _, client := range m.app.LSPClients {
  208. // if client.GetServerState() == lsp.StateStarting {
  209. // initializing = true
  210. // break
  211. // }
  212. // }
  213. // If any server is initializing, show that status
  214. if initializing {
  215. return lipgloss.NewStyle().
  216. Foreground(t.Warning()).
  217. Render(fmt.Sprintf("%s Initializing LSP...", styles.SpinnerIcon))
  218. }
  219. // errorDiagnostics := []protocol.Diagnostic{}
  220. // warnDiagnostics := []protocol.Diagnostic{}
  221. // hintDiagnostics := []protocol.Diagnostic{}
  222. // infoDiagnostics := []protocol.Diagnostic{}
  223. // for _, client := range m.app.LSPClients {
  224. // for _, d := range client.GetDiagnostics() {
  225. // for _, diag := range d {
  226. // switch diag.Severity {
  227. // case protocol.SeverityError:
  228. // errorDiagnostics = append(errorDiagnostics, diag)
  229. // case protocol.SeverityWarning:
  230. // warnDiagnostics = append(warnDiagnostics, diag)
  231. // case protocol.SeverityHint:
  232. // hintDiagnostics = append(hintDiagnostics, diag)
  233. // case protocol.SeverityInformation:
  234. // infoDiagnostics = append(infoDiagnostics, diag)
  235. // }
  236. // }
  237. // }
  238. // }
  239. return styles.ForceReplaceBackgroundWithLipgloss(
  240. styles.Padded().Render("No diagnostics"),
  241. t.BackgroundDarker(),
  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. //
  254. // errStr := lipgloss.NewStyle().
  255. // Background(t.BackgroundDarker()).
  256. // Foreground(t.Error()).
  257. // Render(fmt.Sprintf("%s %d", styles.ErrorIcon, len(errorDiagnostics)))
  258. // diagnostics = append(diagnostics, errStr)
  259. //
  260. // warnStr := lipgloss.NewStyle().
  261. // Background(t.BackgroundDarker()).
  262. // Foreground(t.Warning()).
  263. // Render(fmt.Sprintf("%s %d", styles.WarningIcon, len(warnDiagnostics)))
  264. // diagnostics = append(diagnostics, warnStr)
  265. //
  266. // infoStr := lipgloss.NewStyle().
  267. // Background(t.BackgroundDarker()).
  268. // Foreground(t.Info()).
  269. // Render(fmt.Sprintf("%s %d", styles.InfoIcon, len(infoDiagnostics)))
  270. // diagnostics = append(diagnostics, infoStr)
  271. //
  272. // hintStr := lipgloss.NewStyle().
  273. // Background(t.BackgroundDarker()).
  274. // Foreground(t.Text()).
  275. // Render(fmt.Sprintf("%s %d", styles.HintIcon, len(hintDiagnostics)))
  276. // diagnostics = append(diagnostics, hintStr)
  277. //
  278. // return styles.ForceReplaceBackgroundWithLipgloss(
  279. // styles.Padded().Render(strings.Join(diagnostics, " ")),
  280. // t.BackgroundDarker(),
  281. // )
  282. }
  283. func (m statusCmp) model() string {
  284. t := theme.CurrentTheme()
  285. model := "Claude Sonnet 4" // models.SupportedModels[coder.Model]
  286. return styles.Padded().
  287. Background(t.Secondary()).
  288. Foreground(t.Background()).
  289. Render(model)
  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. }