messages.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627
  1. package chat
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/charmbracelet/bubbles/v2/viewport"
  6. tea "github.com/charmbracelet/bubbletea/v2"
  7. "github.com/charmbracelet/lipgloss/v2"
  8. "github.com/sst/opencode-sdk-go"
  9. "github.com/sst/opencode/internal/app"
  10. "github.com/sst/opencode/internal/components/dialog"
  11. "github.com/sst/opencode/internal/components/toast"
  12. "github.com/sst/opencode/internal/layout"
  13. "github.com/sst/opencode/internal/styles"
  14. "github.com/sst/opencode/internal/theme"
  15. "github.com/sst/opencode/internal/util"
  16. )
  17. type MessagesComponent interface {
  18. tea.Model
  19. tea.ViewModel
  20. PageUp() (tea.Model, tea.Cmd)
  21. PageDown() (tea.Model, tea.Cmd)
  22. HalfPageUp() (tea.Model, tea.Cmd)
  23. HalfPageDown() (tea.Model, tea.Cmd)
  24. ToolDetailsVisible() bool
  25. GotoTop() (tea.Model, tea.Cmd)
  26. GotoBottom() (tea.Model, tea.Cmd)
  27. CopyLastMessage() (tea.Model, tea.Cmd)
  28. }
  29. type messagesComponent struct {
  30. width, height int
  31. app *app.App
  32. header string
  33. viewport viewport.Model
  34. cache *PartCache
  35. rendering bool
  36. showToolDetails bool
  37. tail bool
  38. partCount int
  39. lineCount int
  40. }
  41. type renderFinishedMsg struct{}
  42. type ToggleToolDetailsMsg struct{}
  43. func (m *messagesComponent) Init() tea.Cmd {
  44. return tea.Batch(m.viewport.Init())
  45. }
  46. func (m *messagesComponent) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
  47. var cmds []tea.Cmd
  48. switch msg := msg.(type) {
  49. case tea.WindowSizeMsg:
  50. effectiveWidth := msg.Width - 4
  51. // Clear cache on resize since width affects rendering
  52. if m.width != effectiveWidth {
  53. m.cache.Clear()
  54. }
  55. m.width = effectiveWidth
  56. m.height = msg.Height - 7
  57. m.viewport.SetWidth(m.width)
  58. m.header = m.renderHeader()
  59. return m, m.Reload()
  60. case app.SendMsg:
  61. m.viewport.GotoBottom()
  62. m.tail = true
  63. return m, nil
  64. case app.OptimisticMessageAddedMsg:
  65. m.tail = true
  66. m.rendering = true
  67. return m, m.Reload()
  68. case dialog.ThemeSelectedMsg:
  69. m.cache.Clear()
  70. m.rendering = true
  71. return m, m.Reload()
  72. case ToggleToolDetailsMsg:
  73. m.showToolDetails = !m.showToolDetails
  74. m.rendering = true
  75. return m, m.Reload()
  76. case app.SessionLoadedMsg, app.SessionClearedMsg:
  77. m.cache.Clear()
  78. m.tail = true
  79. m.rendering = true
  80. return m, m.Reload()
  81. case renderFinishedMsg:
  82. m.rendering = false
  83. if m.tail {
  84. m.viewport.GotoBottom()
  85. }
  86. case opencode.EventListResponseEventSessionUpdated:
  87. if msg.Properties.Info.ID == m.app.Session.ID {
  88. m.header = m.renderHeader()
  89. }
  90. case opencode.EventListResponseEventMessageUpdated:
  91. if msg.Properties.Info.SessionID == m.app.Session.ID {
  92. m.renderView()
  93. if m.tail {
  94. m.viewport.GotoBottom()
  95. }
  96. }
  97. case opencode.EventListResponseEventMessagePartUpdated:
  98. if msg.Properties.Part.SessionID == m.app.Session.ID {
  99. m.renderView()
  100. if m.tail {
  101. m.viewport.GotoBottom()
  102. }
  103. }
  104. }
  105. viewport, cmd := m.viewport.Update(msg)
  106. m.viewport = viewport
  107. m.tail = m.viewport.AtBottom()
  108. cmds = append(cmds, cmd)
  109. return m, tea.Batch(cmds...)
  110. }
  111. func (m *messagesComponent) renderView() {
  112. measure := util.Measure("messages.renderView")
  113. defer measure("messageCount", len(m.app.Messages))
  114. m.header = m.renderHeader()
  115. t := theme.CurrentTheme()
  116. blocks := make([]string, 0)
  117. m.partCount = 0
  118. m.lineCount = 0
  119. orphanedToolCalls := make([]opencode.ToolPart, 0)
  120. width := min(m.width, app.MAX_CONTAINER_WIDTH)
  121. if m.app.Config.Layout == opencode.LayoutConfigStretch {
  122. width = m.width
  123. }
  124. for _, message := range m.app.Messages {
  125. var content string
  126. var cached bool
  127. switch casted := message.Info.(type) {
  128. case opencode.UserMessage:
  129. for partIndex, part := range message.Parts {
  130. switch part := part.(type) {
  131. case opencode.TextPart:
  132. if part.Synthetic {
  133. continue
  134. }
  135. remainingParts := message.Parts[partIndex+1:]
  136. fileParts := make([]opencode.FilePart, 0)
  137. for _, part := range remainingParts {
  138. switch part := part.(type) {
  139. case opencode.FilePart:
  140. fileParts = append(fileParts, part)
  141. }
  142. }
  143. flexItems := []layout.FlexItem{}
  144. if len(fileParts) > 0 {
  145. fileStyle := styles.NewStyle().Background(t.BackgroundElement()).Foreground(t.TextMuted()).Padding(0, 1)
  146. mediaTypeStyle := styles.NewStyle().Background(t.Secondary()).Foreground(t.BackgroundPanel()).Padding(0, 1)
  147. for _, filePart := range fileParts {
  148. mediaType := ""
  149. switch filePart.Mime {
  150. case "text/plain":
  151. mediaType = "txt"
  152. case "image/png", "image/jpeg", "image/gif", "image/webp":
  153. mediaType = "img"
  154. mediaTypeStyle = mediaTypeStyle.Background(t.Accent())
  155. case "application/pdf":
  156. mediaType = "pdf"
  157. mediaTypeStyle = mediaTypeStyle.Background(t.Primary())
  158. }
  159. flexItems = append(flexItems, layout.FlexItem{
  160. View: mediaTypeStyle.Render(mediaType) + fileStyle.Render(filePart.Filename),
  161. })
  162. }
  163. }
  164. bgColor := t.BackgroundPanel()
  165. files := layout.Render(
  166. layout.FlexOptions{
  167. Background: &bgColor,
  168. Width: width - 6,
  169. Direction: layout.Column,
  170. },
  171. flexItems...,
  172. )
  173. key := m.cache.GenerateKey(casted.ID, part.Text, width, files)
  174. content, cached = m.cache.Get(key)
  175. if !cached {
  176. content = renderText(
  177. m.app,
  178. message.Info,
  179. part.Text,
  180. m.app.Config.Username,
  181. m.showToolDetails,
  182. width,
  183. files,
  184. )
  185. content = lipgloss.PlaceHorizontal(
  186. m.width,
  187. lipgloss.Center,
  188. content,
  189. styles.WhitespaceStyle(t.Background()),
  190. )
  191. m.cache.Set(key, content)
  192. }
  193. if content != "" {
  194. m.partCount++
  195. m.lineCount += lipgloss.Height(content) + 1
  196. blocks = append(blocks, content)
  197. }
  198. }
  199. }
  200. case opencode.AssistantMessage:
  201. hasTextPart := false
  202. for partIndex, p := range message.Parts {
  203. switch part := p.(type) {
  204. case opencode.TextPart:
  205. hasTextPart = true
  206. finished := casted.Time.Completed > 0
  207. remainingParts := message.Parts[partIndex+1:]
  208. toolCallParts := make([]opencode.ToolPart, 0)
  209. // sometimes tool calls happen without an assistant message
  210. // these should be included in this assistant message as well
  211. if len(orphanedToolCalls) > 0 {
  212. toolCallParts = append(toolCallParts, orphanedToolCalls...)
  213. orphanedToolCalls = make([]opencode.ToolPart, 0)
  214. }
  215. remaining := true
  216. for _, part := range remainingParts {
  217. if !remaining {
  218. break
  219. }
  220. switch part := part.(type) {
  221. case opencode.TextPart:
  222. // we only want tool calls associated with the current text part.
  223. // if we hit another text part, we're done.
  224. remaining = false
  225. case opencode.ToolPart:
  226. toolCallParts = append(toolCallParts, part)
  227. if part.State.Status != opencode.ToolPartStateStatusCompleted && part.State.Status != opencode.ToolPartStateStatusError {
  228. // i don't think there's a case where a tool call isn't in result state
  229. // and the message time is 0, but just in case
  230. finished = false
  231. }
  232. }
  233. }
  234. if finished {
  235. key := m.cache.GenerateKey(casted.ID, part.Text, width, m.showToolDetails)
  236. content, cached = m.cache.Get(key)
  237. if !cached {
  238. content = renderText(
  239. m.app,
  240. message.Info,
  241. part.Text,
  242. casted.ModelID,
  243. m.showToolDetails,
  244. width,
  245. "",
  246. toolCallParts...,
  247. )
  248. content = lipgloss.PlaceHorizontal(
  249. m.width,
  250. lipgloss.Center,
  251. content,
  252. styles.WhitespaceStyle(t.Background()),
  253. )
  254. m.cache.Set(key, content)
  255. }
  256. } else {
  257. content = renderText(
  258. m.app,
  259. message.Info,
  260. part.Text,
  261. casted.ModelID,
  262. m.showToolDetails,
  263. width,
  264. "",
  265. toolCallParts...,
  266. )
  267. content = lipgloss.PlaceHorizontal(
  268. m.width,
  269. lipgloss.Center,
  270. content,
  271. styles.WhitespaceStyle(t.Background()),
  272. )
  273. }
  274. if content != "" {
  275. m.partCount++
  276. m.lineCount += lipgloss.Height(content) + 1
  277. blocks = append(blocks, content)
  278. }
  279. case opencode.ToolPart:
  280. if !m.showToolDetails {
  281. if !hasTextPart {
  282. orphanedToolCalls = append(orphanedToolCalls, part)
  283. }
  284. continue
  285. }
  286. width := width
  287. if m.app.Config.Layout == opencode.LayoutConfigAuto &&
  288. part.Tool == "edit" &&
  289. part.State.Error == "" {
  290. width = min(m.width, app.EDIT_DIFF_MAX_WIDTH)
  291. }
  292. if part.State.Status == opencode.ToolPartStateStatusCompleted || part.State.Status == opencode.ToolPartStateStatusError {
  293. key := m.cache.GenerateKey(casted.ID,
  294. part.ID,
  295. m.showToolDetails,
  296. width,
  297. )
  298. content, cached = m.cache.Get(key)
  299. if !cached {
  300. content = renderToolDetails(
  301. m.app,
  302. part,
  303. width,
  304. )
  305. content = lipgloss.PlaceHorizontal(
  306. m.width,
  307. lipgloss.Center,
  308. content,
  309. styles.WhitespaceStyle(t.Background()),
  310. )
  311. m.cache.Set(key, content)
  312. }
  313. } else {
  314. // if the tool call isn't finished, don't cache
  315. content = renderToolDetails(
  316. m.app,
  317. part,
  318. width,
  319. )
  320. content = lipgloss.PlaceHorizontal(
  321. m.width,
  322. lipgloss.Center,
  323. content,
  324. styles.WhitespaceStyle(t.Background()),
  325. )
  326. }
  327. if content != "" {
  328. m.partCount++
  329. m.lineCount += lipgloss.Height(content) + 1
  330. blocks = append(blocks, content)
  331. }
  332. }
  333. }
  334. }
  335. error := ""
  336. if assistant, ok := message.Info.(opencode.AssistantMessage); ok {
  337. switch err := assistant.Error.AsUnion().(type) {
  338. case nil:
  339. case opencode.AssistantMessageErrorMessageOutputLengthError:
  340. error = "Message output length exceeded"
  341. case opencode.ProviderAuthError:
  342. error = err.Data.Message
  343. case opencode.MessageAbortedError:
  344. error = "Request was aborted"
  345. case opencode.UnknownError:
  346. error = err.Data.Message
  347. }
  348. }
  349. if error != "" {
  350. error = styles.NewStyle().Width(width - 6).Render(error)
  351. error = renderContentBlock(
  352. m.app,
  353. error,
  354. width,
  355. WithBorderColor(t.Error()),
  356. )
  357. blocks = append(blocks, error)
  358. m.lineCount += lipgloss.Height(error) + 1
  359. }
  360. }
  361. m.viewport.SetHeight(m.height - lipgloss.Height(m.header))
  362. m.viewport.SetContent("\n" + strings.Join(blocks, "\n\n"))
  363. }
  364. func (m *messagesComponent) renderHeader() string {
  365. if m.app.Session.ID == "" {
  366. return ""
  367. }
  368. headerWidth := min(m.width, app.MAX_CONTAINER_WIDTH)
  369. if m.app.Config.Layout == opencode.LayoutConfigStretch {
  370. headerWidth = m.width
  371. }
  372. t := theme.CurrentTheme()
  373. base := styles.NewStyle().Foreground(t.Text()).Background(t.Background()).Render
  374. muted := styles.NewStyle().Foreground(t.TextMuted()).Background(t.Background()).Render
  375. headerLines := []string{}
  376. headerLines = append(
  377. headerLines,
  378. util.ToMarkdown("# "+m.app.Session.Title, headerWidth-6, t.Background()),
  379. )
  380. share := ""
  381. if m.app.Session.Share.URL != "" {
  382. share = muted(m.app.Session.Share.URL + " /unshare")
  383. } else {
  384. share = base("/share") + muted(" to create a shareable link")
  385. }
  386. sessionInfo := ""
  387. tokens := float64(0)
  388. cost := float64(0)
  389. contextWindow := m.app.Model.Limit.Context
  390. for _, message := range m.app.Messages {
  391. if assistant, ok := message.Info.(opencode.AssistantMessage); ok {
  392. cost += assistant.Cost
  393. usage := assistant.Tokens
  394. if usage.Output > 0 {
  395. if assistant.Summary {
  396. tokens = usage.Output
  397. continue
  398. }
  399. tokens = (usage.Input +
  400. usage.Cache.Write +
  401. usage.Cache.Read +
  402. usage.Output +
  403. usage.Reasoning)
  404. }
  405. }
  406. }
  407. // Check if current model is a subscription model (cost is 0 for both input and output)
  408. isSubscriptionModel := m.app.Model != nil &&
  409. m.app.Model.Cost.Input == 0 && m.app.Model.Cost.Output == 0
  410. sessionInfo = styles.NewStyle().
  411. Foreground(t.TextMuted()).
  412. Background(t.Background()).
  413. Render(formatTokensAndCost(tokens, contextWindow, cost, isSubscriptionModel))
  414. background := t.Background()
  415. share = layout.Render(
  416. layout.FlexOptions{
  417. Background: &background,
  418. Direction: layout.Row,
  419. Justify: layout.JustifySpaceBetween,
  420. Align: layout.AlignStretch,
  421. Width: headerWidth - 6,
  422. },
  423. layout.FlexItem{
  424. View: share,
  425. },
  426. layout.FlexItem{
  427. View: sessionInfo,
  428. },
  429. )
  430. headerLines = append(headerLines, share)
  431. header := strings.Join(headerLines, "\n")
  432. header = styles.NewStyle().
  433. Background(t.Background()).
  434. Width(headerWidth).
  435. PaddingLeft(2).
  436. PaddingRight(2).
  437. BorderLeft(true).
  438. BorderRight(true).
  439. BorderBackground(t.Background()).
  440. BorderForeground(t.BackgroundElement()).
  441. BorderStyle(lipgloss.ThickBorder()).
  442. Render(header)
  443. header = lipgloss.PlaceHorizontal(
  444. m.width,
  445. lipgloss.Center,
  446. header,
  447. styles.WhitespaceStyle(t.Background()),
  448. )
  449. return "\n" + header + "\n"
  450. }
  451. func formatTokensAndCost(
  452. tokens float64,
  453. contextWindow float64,
  454. cost float64,
  455. isSubscriptionModel bool,
  456. ) string {
  457. // Format tokens in human-readable format (e.g., 110K, 1.2M)
  458. var formattedTokens string
  459. switch {
  460. case tokens >= 1_000_000:
  461. formattedTokens = fmt.Sprintf("%.1fM", float64(tokens)/1_000_000)
  462. case tokens >= 1_000:
  463. formattedTokens = fmt.Sprintf("%.1fK", float64(tokens)/1_000)
  464. default:
  465. formattedTokens = fmt.Sprintf("%d", int(tokens))
  466. }
  467. // Remove .0 suffix if present
  468. if strings.HasSuffix(formattedTokens, ".0K") {
  469. formattedTokens = strings.Replace(formattedTokens, ".0K", "K", 1)
  470. }
  471. if strings.HasSuffix(formattedTokens, ".0M") {
  472. formattedTokens = strings.Replace(formattedTokens, ".0M", "M", 1)
  473. }
  474. percentage := 0.0
  475. if contextWindow > 0 {
  476. percentage = (float64(tokens) / float64(contextWindow)) * 100
  477. }
  478. if isSubscriptionModel {
  479. return fmt.Sprintf(
  480. "%s/%d%%",
  481. formattedTokens,
  482. int(percentage),
  483. )
  484. }
  485. formattedCost := fmt.Sprintf("$%.2f", cost)
  486. return fmt.Sprintf(
  487. "%s/%d%% (%s)",
  488. formattedTokens,
  489. int(percentage),
  490. formattedCost,
  491. )
  492. }
  493. func (m *messagesComponent) View() string {
  494. t := theme.CurrentTheme()
  495. if m.rendering {
  496. return lipgloss.Place(
  497. m.width,
  498. m.height,
  499. lipgloss.Center,
  500. lipgloss.Center,
  501. styles.NewStyle().Background(t.Background()).Render(""),
  502. styles.WhitespaceStyle(t.Background()),
  503. )
  504. }
  505. return styles.NewStyle().
  506. Background(t.Background()).
  507. Render(m.header + "\n" + m.viewport.View())
  508. }
  509. func (m *messagesComponent) Reload() tea.Cmd {
  510. return func() tea.Msg {
  511. m.renderView()
  512. return renderFinishedMsg{}
  513. }
  514. }
  515. func (m *messagesComponent) PageUp() (tea.Model, tea.Cmd) {
  516. m.viewport.ViewUp()
  517. return m, nil
  518. }
  519. func (m *messagesComponent) PageDown() (tea.Model, tea.Cmd) {
  520. m.viewport.ViewDown()
  521. return m, nil
  522. }
  523. func (m *messagesComponent) HalfPageUp() (tea.Model, tea.Cmd) {
  524. m.viewport.HalfViewUp()
  525. return m, nil
  526. }
  527. func (m *messagesComponent) HalfPageDown() (tea.Model, tea.Cmd) {
  528. m.viewport.HalfViewDown()
  529. return m, nil
  530. }
  531. func (m *messagesComponent) ToolDetailsVisible() bool {
  532. return m.showToolDetails
  533. }
  534. func (m *messagesComponent) GotoTop() (tea.Model, tea.Cmd) {
  535. m.viewport.GotoTop()
  536. return m, nil
  537. }
  538. func (m *messagesComponent) GotoBottom() (tea.Model, tea.Cmd) {
  539. m.viewport.GotoBottom()
  540. return m, nil
  541. }
  542. func (m *messagesComponent) CopyLastMessage() (tea.Model, tea.Cmd) {
  543. if len(m.app.Messages) == 0 {
  544. return m, nil
  545. }
  546. lastMessage := m.app.Messages[len(m.app.Messages)-1]
  547. var lastTextPart *opencode.TextPart
  548. for _, part := range lastMessage.Parts {
  549. if p, ok := part.(opencode.TextPart); ok {
  550. lastTextPart = &p
  551. }
  552. }
  553. if lastTextPart == nil {
  554. return m, nil
  555. }
  556. var cmds []tea.Cmd
  557. cmds = append(cmds, m.app.SetClipboard(lastTextPart.Text))
  558. cmds = append(cmds, toast.NewSuccessToast("Message copied to clipboard"))
  559. return m, tea.Batch(cmds...)
  560. }
  561. func NewMessagesComponent(app *app.App) MessagesComponent {
  562. vp := viewport.New()
  563. vp.KeyMap = viewport.KeyMap{}
  564. return &messagesComponent{
  565. app: app,
  566. viewport: vp,
  567. showToolDetails: true,
  568. cache: NewPartCache(),
  569. tail: true,
  570. }
  571. }