status.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  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/pubsub"
  10. "github.com/sst/opencode/internal/status"
  11. "github.com/sst/opencode/internal/styles"
  12. "github.com/sst/opencode/internal/theme"
  13. )
  14. type StatusCmp interface {
  15. tea.Model
  16. }
  17. type statusCmp struct {
  18. app *app.App
  19. queue []status.StatusMessage
  20. width int
  21. messageTTL time.Duration
  22. activeUntil time.Time
  23. }
  24. // clearMessageCmd is a command that clears status messages after a timeout
  25. func (m statusCmp) clearMessageCmd() tea.Cmd {
  26. return tea.Tick(time.Second, func(t time.Time) tea.Msg {
  27. return statusCleanupMsg{time: t}
  28. })
  29. }
  30. // statusCleanupMsg is a message that triggers cleanup of expired status messages
  31. type statusCleanupMsg struct {
  32. time time.Time
  33. }
  34. func (m statusCmp) Init() tea.Cmd {
  35. return m.clearMessageCmd()
  36. }
  37. func (m statusCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
  38. switch msg := msg.(type) {
  39. case tea.WindowSizeMsg:
  40. m.width = msg.Width
  41. return m, nil
  42. case pubsub.Event[status.StatusMessage]:
  43. if msg.Type == status.EventStatusPublished {
  44. // If this is a critical message, move it to the front of the queue
  45. if msg.Payload.Critical {
  46. // Insert at the front of the queue
  47. m.queue = append([]status.StatusMessage{msg.Payload}, m.queue...)
  48. // Reset active time to show critical message immediately
  49. m.activeUntil = time.Time{}
  50. } else {
  51. // Otherwise, just add it to the queue
  52. m.queue = append(m.queue, msg.Payload)
  53. // If this is the first message and nothing is active, activate it immediately
  54. if len(m.queue) == 1 && m.activeUntil.IsZero() {
  55. now := time.Now()
  56. duration := m.messageTTL
  57. if msg.Payload.Duration > 0 {
  58. duration = msg.Payload.Duration
  59. }
  60. m.activeUntil = now.Add(duration)
  61. }
  62. }
  63. }
  64. case statusCleanupMsg:
  65. now := msg.time
  66. // If the active message has expired, remove it and activate the next one
  67. if !m.activeUntil.IsZero() && m.activeUntil.Before(now) {
  68. // Current message expired, remove it if we have one
  69. if len(m.queue) > 0 {
  70. m.queue = m.queue[1:]
  71. }
  72. m.activeUntil = time.Time{}
  73. }
  74. // If we have messages in queue but none are active, activate the first one
  75. if len(m.queue) > 0 && m.activeUntil.IsZero() {
  76. // Use custom duration if specified, otherwise use default
  77. duration := m.messageTTL
  78. if m.queue[0].Duration > 0 {
  79. duration = m.queue[0].Duration
  80. }
  81. m.activeUntil = now.Add(duration)
  82. }
  83. return m, m.clearMessageCmd()
  84. }
  85. return m, nil
  86. }
  87. func logo() string {
  88. t := theme.CurrentTheme()
  89. mark := styles.Bold().Foreground(t.Primary()).Render("◧ ")
  90. open := styles.Muted().Render("open")
  91. code := styles.BaseStyle().Bold(true).Render("code")
  92. version := styles.Muted().Render(app.Info.Version)
  93. return styles.ForceReplaceBackgroundWithLipgloss(
  94. styles.Padded().Render(mark+open+code+" "+version),
  95. t.BackgroundElement(),
  96. )
  97. }
  98. func formatTokensAndCost(tokens float32, contextWindow float32, cost float32) string {
  99. // Format tokens in human-readable format (e.g., 110K, 1.2M)
  100. var formattedTokens string
  101. switch {
  102. case tokens >= 1_000_000:
  103. formattedTokens = fmt.Sprintf("%.1fM", float64(tokens)/1_000_000)
  104. case tokens >= 1_000:
  105. formattedTokens = fmt.Sprintf("%.1fK", float64(tokens)/1_000)
  106. default:
  107. formattedTokens = fmt.Sprintf("%d", int(tokens))
  108. }
  109. // Remove .0 suffix if present
  110. if strings.HasSuffix(formattedTokens, ".0K") {
  111. formattedTokens = strings.Replace(formattedTokens, ".0K", "K", 1)
  112. }
  113. if strings.HasSuffix(formattedTokens, ".0M") {
  114. formattedTokens = strings.Replace(formattedTokens, ".0M", "M", 1)
  115. }
  116. // Format cost with $ symbol and 2 decimal places
  117. formattedCost := fmt.Sprintf("$%.2f", cost)
  118. percentage := (float64(tokens) / float64(contextWindow)) * 100
  119. return fmt.Sprintf("Tokens: %s (%d%%), Cost: %s", formattedTokens, int(percentage), formattedCost)
  120. }
  121. func (m statusCmp) View() string {
  122. if m.app.Session.Id == "" {
  123. return styles.BaseStyle().
  124. Width(m.width).
  125. Height(2).
  126. Render("")
  127. }
  128. t := theme.CurrentTheme()
  129. logo := logo()
  130. cwd := styles.Padded().
  131. Foreground(t.TextMuted()).
  132. Background(t.BackgroundSubtle()).
  133. Render(app.Info.Path.Cwd)
  134. sessionInfo := ""
  135. if m.app.Session.Id != "" {
  136. tokens := float32(0)
  137. cost := float32(0)
  138. contextWindow := m.app.Model.Limit.Context
  139. for _, message := range m.app.Messages {
  140. if message.Metadata.Assistant != nil {
  141. cost += message.Metadata.Assistant.Cost
  142. usage := message.Metadata.Assistant.Tokens
  143. if usage.Output > 0 {
  144. tokens = (usage.Input + usage.Output + usage.Reasoning)
  145. }
  146. }
  147. }
  148. sessionInfo = styles.Padded().
  149. Background(t.BackgroundElement()).
  150. Foreground(t.TextMuted()).
  151. Render(formatTokensAndCost(tokens, contextWindow, cost))
  152. }
  153. // diagnostics := styles.Padded().Background(t.BackgroundElement()).Render(m.projectDiagnostics())
  154. space := max(
  155. 0,
  156. m.width-lipgloss.Width(logo)-lipgloss.Width(cwd)-lipgloss.Width(sessionInfo),
  157. )
  158. spacer := lipgloss.NewStyle().Background(t.BackgroundSubtle()).Width(space).Render("")
  159. status := logo + cwd + spacer + sessionInfo
  160. blank := styles.BaseStyle().Background(t.Background()).Width(m.width).Render("")
  161. return blank + "\n" + status
  162. // Display the first status message if available
  163. // var statusMessage string
  164. // if len(m.queue) > 0 {
  165. // sm := m.queue[0]
  166. // infoStyle := styles.Padded().
  167. // Foreground(t.Background())
  168. //
  169. // switch sm.Level {
  170. // case "info":
  171. // infoStyle = infoStyle.Background(t.Info())
  172. // case "warn":
  173. // infoStyle = infoStyle.Background(t.Warning())
  174. // case "error":
  175. // infoStyle = infoStyle.Background(t.Error())
  176. // case "debug":
  177. // infoStyle = infoStyle.Background(t.TextMuted())
  178. // }
  179. //
  180. // // Truncate message if it's longer than available width
  181. // msg := sm.Message
  182. // availWidth := statusWidth - 10
  183. //
  184. // // If we have enough space, show inline
  185. // if availWidth >= minInlineWidth {
  186. // if len(msg) > availWidth && availWidth > 0 {
  187. // msg = msg[:availWidth] + "..."
  188. // }
  189. // status += infoStyle.Width(statusWidth).Render(msg)
  190. // } else {
  191. // // Otherwise, prepare a full-width message to show above
  192. // if len(msg) > m.width-10 && m.width > 10 {
  193. // msg = msg[:m.width-10] + "..."
  194. // }
  195. // statusMessage = infoStyle.Width(m.width).Render(msg)
  196. //
  197. // // Add empty space in the status bar
  198. // status += styles.Padded().
  199. // Foreground(t.Text()).
  200. // Background(t.BackgroundSubtle()).
  201. // Width(statusWidth).
  202. // Render("")
  203. // }
  204. // } else {
  205. // status += styles.Padded().
  206. // Foreground(t.Text()).
  207. // Background(t.BackgroundSubtle()).
  208. // Width(statusWidth).
  209. // Render("")
  210. // }
  211. // status += diagnostics
  212. // status += modelName
  213. // If we have a separate status message, prepend it
  214. // if statusMessage != "" {
  215. // return statusMessage + "\n" + status
  216. // } else {
  217. // blank := styles.BaseStyle().Background(t.Background()).Width(m.width).Render("")
  218. // return blank + "\n" + status
  219. // }
  220. }
  221. func (m *statusCmp) projectDiagnostics() string {
  222. t := theme.CurrentTheme()
  223. // Check if any LSP server is still initializing
  224. initializing := false
  225. // for _, client := range m.app.LSPClients {
  226. // if client.GetServerState() == lsp.StateStarting {
  227. // initializing = true
  228. // break
  229. // }
  230. // }
  231. // If any server is initializing, show that status
  232. if initializing {
  233. return lipgloss.NewStyle().
  234. Foreground(t.Warning()).
  235. Render(fmt.Sprintf("%s Initializing LSP...", styles.SpinnerIcon))
  236. }
  237. // errorDiagnostics := []protocol.Diagnostic{}
  238. // warnDiagnostics := []protocol.Diagnostic{}
  239. // hintDiagnostics := []protocol.Diagnostic{}
  240. // infoDiagnostics := []protocol.Diagnostic{}
  241. // for _, client := range m.app.LSPClients {
  242. // for _, d := range client.GetDiagnostics() {
  243. // for _, diag := range d {
  244. // switch diag.Severity {
  245. // case protocol.SeverityError:
  246. // errorDiagnostics = append(errorDiagnostics, diag)
  247. // case protocol.SeverityWarning:
  248. // warnDiagnostics = append(warnDiagnostics, diag)
  249. // case protocol.SeverityHint:
  250. // hintDiagnostics = append(hintDiagnostics, diag)
  251. // case protocol.SeverityInformation:
  252. // infoDiagnostics = append(infoDiagnostics, diag)
  253. // }
  254. // }
  255. // }
  256. // }
  257. return styles.ForceReplaceBackgroundWithLipgloss(
  258. styles.Padded().Render("No diagnostics"),
  259. t.BackgroundElement(),
  260. )
  261. // if len(errorDiagnostics) == 0 &&
  262. // len(warnDiagnostics) == 0 &&
  263. // len(infoDiagnostics) == 0 &&
  264. // len(hintDiagnostics) == 0 {
  265. // return styles.ForceReplaceBackgroundWithLipgloss(
  266. // styles.Padded().Render("No diagnostics"),
  267. // t.BackgroundDarker(),
  268. // )
  269. // }
  270. // diagnostics := []string{}
  271. //
  272. // errStr := lipgloss.NewStyle().
  273. // Background(t.BackgroundDarker()).
  274. // Foreground(t.Error()).
  275. // Render(fmt.Sprintf("%s %d", styles.ErrorIcon, len(errorDiagnostics)))
  276. // diagnostics = append(diagnostics, errStr)
  277. //
  278. // warnStr := lipgloss.NewStyle().
  279. // Background(t.BackgroundDarker()).
  280. // Foreground(t.Warning()).
  281. // Render(fmt.Sprintf("%s %d", styles.WarningIcon, len(warnDiagnostics)))
  282. // diagnostics = append(diagnostics, warnStr)
  283. //
  284. // infoStr := lipgloss.NewStyle().
  285. // Background(t.BackgroundDarker()).
  286. // Foreground(t.Info()).
  287. // Render(fmt.Sprintf("%s %d", styles.InfoIcon, len(infoDiagnostics)))
  288. // diagnostics = append(diagnostics, infoStr)
  289. //
  290. // hintStr := lipgloss.NewStyle().
  291. // Background(t.BackgroundDarker()).
  292. // Foreground(t.Text()).
  293. // Render(fmt.Sprintf("%s %d", styles.HintIcon, len(hintDiagnostics)))
  294. // diagnostics = append(diagnostics, hintStr)
  295. //
  296. // return styles.ForceReplaceBackgroundWithLipgloss(
  297. // styles.Padded().Render(strings.Join(diagnostics, " ")),
  298. // t.BackgroundDarker(),
  299. // )
  300. }
  301. func (m statusCmp) model() string {
  302. t := theme.CurrentTheme()
  303. model := "None"
  304. if m.app.Model != nil {
  305. model = *m.app.Model.Name
  306. }
  307. return styles.Padded().
  308. Background(t.Secondary()).
  309. Foreground(t.Background()).
  310. Render(model)
  311. }
  312. func NewStatusCmp(app *app.App) StatusCmp {
  313. statusComponent := &statusCmp{
  314. app: app,
  315. queue: []status.StatusMessage{},
  316. messageTTL: 4 * time.Second,
  317. activeUntil: time.Time{},
  318. }
  319. return statusComponent
  320. }