message.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  1. package chat
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "slices"
  6. "strings"
  7. "time"
  8. "github.com/charmbracelet/lipgloss/v2"
  9. "github.com/charmbracelet/lipgloss/v2/compat"
  10. "github.com/charmbracelet/x/ansi"
  11. "github.com/muesli/reflow/truncate"
  12. "github.com/sst/opencode-sdk-go"
  13. "github.com/sst/opencode/internal/app"
  14. "github.com/sst/opencode/internal/components/diff"
  15. "github.com/sst/opencode/internal/styles"
  16. "github.com/sst/opencode/internal/theme"
  17. "github.com/sst/opencode/internal/util"
  18. "golang.org/x/text/cases"
  19. "golang.org/x/text/language"
  20. )
  21. type blockRenderer struct {
  22. textColor compat.AdaptiveColor
  23. border bool
  24. borderColor *compat.AdaptiveColor
  25. borderColorRight bool
  26. paddingTop int
  27. paddingBottom int
  28. paddingLeft int
  29. paddingRight int
  30. marginTop int
  31. marginBottom int
  32. }
  33. type renderingOption func(*blockRenderer)
  34. func WithTextColor(color compat.AdaptiveColor) renderingOption {
  35. return func(c *blockRenderer) {
  36. c.textColor = color
  37. }
  38. }
  39. func WithNoBorder() renderingOption {
  40. return func(c *blockRenderer) {
  41. c.border = false
  42. }
  43. }
  44. func WithBorderColor(color compat.AdaptiveColor) renderingOption {
  45. return func(c *blockRenderer) {
  46. c.borderColor = &color
  47. }
  48. }
  49. func WithBorderColorRight(color compat.AdaptiveColor) renderingOption {
  50. return func(c *blockRenderer) {
  51. c.borderColorRight = true
  52. c.borderColor = &color
  53. }
  54. }
  55. func WithMarginTop(padding int) renderingOption {
  56. return func(c *blockRenderer) {
  57. c.marginTop = padding
  58. }
  59. }
  60. func WithMarginBottom(padding int) renderingOption {
  61. return func(c *blockRenderer) {
  62. c.marginBottom = padding
  63. }
  64. }
  65. func WithPadding(padding int) renderingOption {
  66. return func(c *blockRenderer) {
  67. c.paddingTop = padding
  68. c.paddingBottom = padding
  69. c.paddingLeft = padding
  70. c.paddingRight = padding
  71. }
  72. }
  73. func WithPaddingLeft(padding int) renderingOption {
  74. return func(c *blockRenderer) {
  75. c.paddingLeft = padding
  76. }
  77. }
  78. func WithPaddingRight(padding int) renderingOption {
  79. return func(c *blockRenderer) {
  80. c.paddingRight = padding
  81. }
  82. }
  83. func WithPaddingTop(padding int) renderingOption {
  84. return func(c *blockRenderer) {
  85. c.paddingTop = padding
  86. }
  87. }
  88. func WithPaddingBottom(padding int) renderingOption {
  89. return func(c *blockRenderer) {
  90. c.paddingBottom = padding
  91. }
  92. }
  93. func renderContentBlock(
  94. app *app.App,
  95. content string,
  96. width int,
  97. options ...renderingOption,
  98. ) string {
  99. t := theme.CurrentTheme()
  100. renderer := &blockRenderer{
  101. textColor: t.TextMuted(),
  102. border: true,
  103. paddingTop: 1,
  104. paddingBottom: 1,
  105. paddingLeft: 2,
  106. paddingRight: 2,
  107. }
  108. for _, option := range options {
  109. option(renderer)
  110. }
  111. borderColor := t.BackgroundPanel()
  112. if renderer.borderColor != nil {
  113. borderColor = *renderer.borderColor
  114. }
  115. style := styles.NewStyle().
  116. Foreground(renderer.textColor).
  117. Background(t.BackgroundPanel()).
  118. PaddingTop(renderer.paddingTop).
  119. PaddingBottom(renderer.paddingBottom).
  120. PaddingLeft(renderer.paddingLeft).
  121. PaddingRight(renderer.paddingRight).
  122. AlignHorizontal(lipgloss.Left)
  123. if renderer.border {
  124. style = style.
  125. BorderStyle(lipgloss.ThickBorder()).
  126. BorderLeft(true).
  127. BorderRight(true).
  128. BorderLeftForeground(borderColor).
  129. BorderLeftBackground(t.Background()).
  130. BorderRightForeground(t.BackgroundPanel()).
  131. BorderRightBackground(t.Background())
  132. if renderer.borderColorRight {
  133. style = style.
  134. BorderLeftBackground(t.Background()).
  135. BorderLeftForeground(t.BackgroundPanel()).
  136. BorderRightForeground(borderColor).
  137. BorderRightBackground(t.Background())
  138. }
  139. }
  140. content = style.Render(content)
  141. if renderer.marginTop > 0 {
  142. for range renderer.marginTop {
  143. content = "\n" + content
  144. }
  145. }
  146. if renderer.marginBottom > 0 {
  147. for range renderer.marginBottom {
  148. content = content + "\n"
  149. }
  150. }
  151. return content
  152. }
  153. func renderText(
  154. app *app.App,
  155. message opencode.MessageUnion,
  156. text string,
  157. author string,
  158. showToolDetails bool,
  159. width int,
  160. extra string,
  161. toolCalls ...opencode.ToolPart,
  162. ) string {
  163. t := theme.CurrentTheme()
  164. var ts time.Time
  165. backgroundColor := t.BackgroundPanel()
  166. var content string
  167. switch casted := message.(type) {
  168. case opencode.AssistantMessage:
  169. ts = time.UnixMilli(int64(casted.Time.Created))
  170. content = util.ToMarkdown(text, width, backgroundColor)
  171. case opencode.UserMessage:
  172. ts = time.UnixMilli(int64(casted.Time.Created))
  173. base := styles.NewStyle().Foreground(t.Text()).Background(backgroundColor)
  174. words := strings.Fields(text)
  175. for i, word := range words {
  176. if strings.HasPrefix(word, "@") {
  177. words[i] = base.Foreground(t.Secondary()).Render(word + " ")
  178. } else {
  179. words[i] = base.Render(word + " ")
  180. }
  181. }
  182. text = strings.Join(words, "")
  183. text = ansi.WordwrapWc(text, width-6, " -")
  184. content = base.Width(width - 6).Render(text)
  185. }
  186. timestamp := ts.
  187. Local().
  188. Format("02 Jan 2006 03:04 PM")
  189. if time.Now().Format("02 Jan 2006") == timestamp[:11] {
  190. // don't show the date if it's today
  191. timestamp = timestamp[12:]
  192. }
  193. info := fmt.Sprintf("%s (%s)", author, timestamp)
  194. info = styles.NewStyle().Foreground(t.TextMuted()).Render(info)
  195. if !showToolDetails && toolCalls != nil && len(toolCalls) > 0 {
  196. content = content + "\n\n"
  197. for _, toolCall := range toolCalls {
  198. title := renderToolTitle(toolCall, width)
  199. style := styles.NewStyle()
  200. if toolCall.State.Status == opencode.ToolPartStateStatusError {
  201. style = style.Foreground(t.Error())
  202. }
  203. title = style.Render(title)
  204. title = "∟ " + title + "\n"
  205. content = content + title
  206. }
  207. }
  208. sections := []string{content, info}
  209. if extra != "" {
  210. sections = append(sections, "\n"+extra)
  211. }
  212. content = strings.Join(sections, "\n")
  213. switch message.(type) {
  214. case opencode.UserMessage:
  215. return renderContentBlock(
  216. app,
  217. content,
  218. width,
  219. WithTextColor(t.Text()),
  220. WithBorderColorRight(t.Secondary()),
  221. )
  222. case opencode.AssistantMessage:
  223. return renderContentBlock(
  224. app,
  225. content,
  226. width,
  227. WithBorderColor(t.Accent()),
  228. )
  229. }
  230. return ""
  231. }
  232. func renderToolDetails(
  233. app *app.App,
  234. toolCall opencode.ToolPart,
  235. width int,
  236. ) string {
  237. ignoredTools := []string{"todoread"}
  238. if slices.Contains(ignoredTools, toolCall.Tool) {
  239. return ""
  240. }
  241. if toolCall.State.Status == opencode.ToolPartStateStatusPending {
  242. title := renderToolTitle(toolCall, width)
  243. return renderContentBlock(app, title, width)
  244. }
  245. var result *string
  246. if toolCall.State.Output != "" {
  247. result = &toolCall.State.Output
  248. }
  249. toolInputMap := make(map[string]any)
  250. if toolCall.State.Input != nil {
  251. value := toolCall.State.Input
  252. if m, ok := value.(map[string]any); ok {
  253. toolInputMap = m
  254. keys := make([]string, 0, len(toolInputMap))
  255. for key := range toolInputMap {
  256. keys = append(keys, key)
  257. }
  258. slices.Sort(keys)
  259. }
  260. }
  261. body := ""
  262. t := theme.CurrentTheme()
  263. backgroundColor := t.BackgroundPanel()
  264. borderColor := t.BackgroundPanel()
  265. defaultStyle := styles.NewStyle().Background(backgroundColor).Width(width - 6).Render
  266. if toolCall.State.Metadata != nil {
  267. metadata := toolCall.State.Metadata.(map[string]any)
  268. switch toolCall.Tool {
  269. case "read":
  270. var preview any
  271. if metadata != nil {
  272. preview = metadata["preview"]
  273. }
  274. if preview != nil && toolInputMap["filePath"] != nil {
  275. filename := toolInputMap["filePath"].(string)
  276. body = preview.(string)
  277. body = util.RenderFile(filename, body, width, util.WithTruncate(6))
  278. }
  279. case "edit":
  280. if filename, ok := toolInputMap["filePath"].(string); ok {
  281. var diffField any
  282. if metadata != nil {
  283. diffField = metadata["diff"]
  284. }
  285. if diffField != nil {
  286. patch := diffField.(string)
  287. var formattedDiff string
  288. if width < 120 {
  289. formattedDiff, _ = diff.FormatUnifiedDiff(
  290. filename,
  291. patch,
  292. diff.WithWidth(width-2),
  293. )
  294. } else {
  295. formattedDiff, _ = diff.FormatDiff(
  296. filename,
  297. patch,
  298. diff.WithWidth(width-2),
  299. )
  300. }
  301. body = strings.TrimSpace(formattedDiff)
  302. style := styles.NewStyle().
  303. Background(backgroundColor).
  304. Foreground(t.TextMuted()).
  305. Padding(1, 2).
  306. Width(width - 4)
  307. if diagnostics := renderDiagnostics(metadata, filename, backgroundColor, width-6); diagnostics != "" {
  308. diagnostics = style.Render(diagnostics)
  309. body += "\n" + diagnostics
  310. }
  311. title := renderToolTitle(toolCall, width)
  312. title = style.Render(title)
  313. content := title + "\n" + body
  314. content = renderContentBlock(
  315. app,
  316. content,
  317. width,
  318. WithPadding(0),
  319. WithBorderColor(borderColor),
  320. )
  321. return content
  322. }
  323. }
  324. case "write":
  325. if filename, ok := toolInputMap["filePath"].(string); ok {
  326. if content, ok := toolInputMap["content"].(string); ok {
  327. body = util.RenderFile(filename, content, width)
  328. if diagnostics := renderDiagnostics(metadata, filename, backgroundColor, width-4); diagnostics != "" {
  329. body += "\n\n" + diagnostics
  330. }
  331. }
  332. }
  333. case "bash":
  334. stdout := metadata["stdout"]
  335. if stdout != nil {
  336. command := toolInputMap["command"].(string)
  337. out := ansi.Strip(fmt.Sprintf("%s", stdout))
  338. body = fmt.Sprintf("```console\n> %s\n%s```", command, out)
  339. body = util.ToMarkdown(body, width, backgroundColor)
  340. }
  341. case "webfetch":
  342. if format, ok := toolInputMap["format"].(string); ok && result != nil {
  343. body = *result
  344. body = util.TruncateHeight(body, 10)
  345. if format == "html" || format == "markdown" {
  346. body = util.ToMarkdown(body, width, backgroundColor)
  347. }
  348. }
  349. case "todowrite":
  350. todos := metadata["todos"]
  351. if todos != nil {
  352. for _, item := range todos.([]any) {
  353. todo := item.(map[string]any)
  354. content := todo["content"].(string)
  355. switch todo["status"] {
  356. case "completed":
  357. body += fmt.Sprintf("- [x] %s\n", content)
  358. case "cancelled":
  359. // strike through cancelled todo
  360. body += fmt.Sprintf("- [~] ~~%s~~\n", content)
  361. case "in_progress":
  362. // highlight in progress todo
  363. body += fmt.Sprintf("- [ ] `%s`\n", content)
  364. default:
  365. body += fmt.Sprintf("- [ ] %s\n", content)
  366. }
  367. }
  368. body = util.ToMarkdown(body, width, backgroundColor)
  369. }
  370. case "task":
  371. summary := metadata["summary"]
  372. if summary != nil {
  373. toolcalls := summary.([]any)
  374. steps := []string{}
  375. for _, item := range toolcalls {
  376. data, _ := json.Marshal(item)
  377. var toolCall opencode.ToolPart
  378. _ = json.Unmarshal(data, &toolCall)
  379. step := renderToolTitle(toolCall, width)
  380. step = "∟ " + step
  381. steps = append(steps, step)
  382. }
  383. body = strings.Join(steps, "\n")
  384. }
  385. body = defaultStyle(body)
  386. default:
  387. if result == nil {
  388. empty := ""
  389. result = &empty
  390. }
  391. body = *result
  392. body = util.TruncateHeight(body, 10)
  393. body = defaultStyle(body)
  394. }
  395. }
  396. error := ""
  397. if toolCall.State.Status == opencode.ToolPartStateStatusError {
  398. error = toolCall.State.Error
  399. }
  400. if error != "" {
  401. body = styles.NewStyle().
  402. Width(width - 6).
  403. Foreground(t.Error()).
  404. Background(backgroundColor).
  405. Render(error)
  406. }
  407. if body == "" && error == "" && result != nil {
  408. body = *result
  409. body = util.TruncateHeight(body, 10)
  410. body = defaultStyle(body)
  411. }
  412. if body == "" {
  413. body = defaultStyle("")
  414. }
  415. title := renderToolTitle(toolCall, width)
  416. content := title + "\n\n" + body
  417. return renderContentBlock(app, content, width, WithBorderColor(borderColor))
  418. }
  419. func renderToolName(name string) string {
  420. switch name {
  421. case "webfetch":
  422. return "Fetch"
  423. default:
  424. normalizedName := name
  425. if after, ok := strings.CutPrefix(name, "opencode_"); ok {
  426. normalizedName = after
  427. }
  428. return cases.Title(language.Und).String(normalizedName)
  429. }
  430. }
  431. func getTodoPhase(metadata map[string]any) string {
  432. todos, ok := metadata["todos"].([]any)
  433. if !ok || len(todos) == 0 {
  434. return "Plan"
  435. }
  436. counts := map[string]int{"pending": 0, "completed": 0}
  437. for _, item := range todos {
  438. if todo, ok := item.(map[string]any); ok {
  439. if status, ok := todo["status"].(string); ok {
  440. counts[status]++
  441. }
  442. }
  443. }
  444. total := len(todos)
  445. switch {
  446. case counts["pending"] == total:
  447. return "Creating plan"
  448. case counts["completed"] == total:
  449. return "Completing plan"
  450. default:
  451. return "Updating plan"
  452. }
  453. }
  454. func getTodoTitle(toolCall opencode.ToolPart) string {
  455. if toolCall.State.Status == opencode.ToolPartStateStatusCompleted {
  456. if metadata, ok := toolCall.State.Metadata.(map[string]any); ok {
  457. return getTodoPhase(metadata)
  458. }
  459. }
  460. return "Plan"
  461. }
  462. func renderToolTitle(
  463. toolCall opencode.ToolPart,
  464. width int,
  465. ) string {
  466. if toolCall.State.Status == opencode.ToolPartStateStatusPending {
  467. title := renderToolAction(toolCall.Tool)
  468. return styles.NewStyle().Width(width - 6).Render(title)
  469. }
  470. toolArgs := ""
  471. toolArgsMap := make(map[string]any)
  472. if toolCall.State.Input != nil {
  473. value := toolCall.State.Input
  474. if m, ok := value.(map[string]any); ok {
  475. toolArgsMap = m
  476. keys := make([]string, 0, len(toolArgsMap))
  477. for key := range toolArgsMap {
  478. keys = append(keys, key)
  479. }
  480. slices.Sort(keys)
  481. firstKey := ""
  482. if len(keys) > 0 {
  483. firstKey = keys[0]
  484. }
  485. toolArgs = renderArgs(&toolArgsMap, firstKey)
  486. }
  487. }
  488. title := renderToolName(toolCall.Tool)
  489. switch toolCall.Tool {
  490. case "read":
  491. toolArgs = renderArgs(&toolArgsMap, "filePath")
  492. title = fmt.Sprintf("%s %s", title, toolArgs)
  493. case "edit", "write":
  494. if filename, ok := toolArgsMap["filePath"].(string); ok {
  495. title = fmt.Sprintf("%s %s", title, util.Relative(filename))
  496. }
  497. case "bash", "task":
  498. if description, ok := toolArgsMap["description"].(string); ok {
  499. title = fmt.Sprintf("%s %s", title, description)
  500. }
  501. case "webfetch":
  502. toolArgs = renderArgs(&toolArgsMap, "url")
  503. title = fmt.Sprintf("%s %s", title, toolArgs)
  504. case "todowrite":
  505. title = getTodoTitle(toolCall)
  506. case "todoread":
  507. return "Plan"
  508. default:
  509. toolName := renderToolName(toolCall.Tool)
  510. title = fmt.Sprintf("%s %s", toolName, toolArgs)
  511. }
  512. title = truncate.StringWithTail(title, uint(width-6), "...")
  513. return title
  514. }
  515. func renderToolAction(name string) string {
  516. switch name {
  517. case "task":
  518. return "Planning..."
  519. case "bash":
  520. return "Writing command..."
  521. case "edit":
  522. return "Preparing edit..."
  523. case "webfetch":
  524. return "Fetching from the web..."
  525. case "glob":
  526. return "Finding files..."
  527. case "grep":
  528. return "Searching content..."
  529. case "list":
  530. return "Listing directory..."
  531. case "read":
  532. return "Reading file..."
  533. case "write":
  534. return "Preparing write..."
  535. case "todowrite", "todoread":
  536. return "Planning..."
  537. case "patch":
  538. return "Preparing patch..."
  539. }
  540. return "Working..."
  541. }
  542. func renderArgs(args *map[string]any, titleKey string) string {
  543. if args == nil || len(*args) == 0 {
  544. return ""
  545. }
  546. keys := make([]string, 0, len(*args))
  547. for key := range *args {
  548. keys = append(keys, key)
  549. }
  550. slices.Sort(keys)
  551. title := ""
  552. parts := []string{}
  553. for _, key := range keys {
  554. value := (*args)[key]
  555. if value == nil {
  556. continue
  557. }
  558. if key == "filePath" || key == "path" {
  559. value = util.Relative(value.(string))
  560. }
  561. if key == titleKey {
  562. title = fmt.Sprintf("%s", value)
  563. continue
  564. }
  565. parts = append(parts, fmt.Sprintf("%s=%v", key, value))
  566. }
  567. if len(parts) == 0 {
  568. return title
  569. }
  570. return fmt.Sprintf("%s (%s)", title, strings.Join(parts, ", "))
  571. }
  572. // Diagnostic represents an LSP diagnostic
  573. type Diagnostic struct {
  574. Range struct {
  575. Start struct {
  576. Line int `json:"line"`
  577. Character int `json:"character"`
  578. } `json:"start"`
  579. } `json:"range"`
  580. Severity int `json:"severity"`
  581. Message string `json:"message"`
  582. }
  583. // renderDiagnostics formats LSP diagnostics for display in the TUI
  584. func renderDiagnostics(
  585. metadata map[string]any,
  586. filePath string,
  587. backgroundColor compat.AdaptiveColor,
  588. width int,
  589. ) string {
  590. if diagnosticsData, ok := metadata["diagnostics"].(map[string]any); ok {
  591. if fileDiagnostics, ok := diagnosticsData[filePath].([]any); ok {
  592. var errorDiagnostics []string
  593. for _, diagInterface := range fileDiagnostics {
  594. diagMap, ok := diagInterface.(map[string]any)
  595. if !ok {
  596. continue
  597. }
  598. // Parse the diagnostic
  599. var diag Diagnostic
  600. diagBytes, err := json.Marshal(diagMap)
  601. if err != nil {
  602. continue
  603. }
  604. if err := json.Unmarshal(diagBytes, &diag); err != nil {
  605. continue
  606. }
  607. // Only show error diagnostics (severity === 1)
  608. if diag.Severity != 1 {
  609. continue
  610. }
  611. line := diag.Range.Start.Line + 1 // 1-based
  612. column := diag.Range.Start.Character + 1 // 1-based
  613. errorDiagnostics = append(
  614. errorDiagnostics,
  615. fmt.Sprintf("Error [%d:%d] %s", line, column, diag.Message),
  616. )
  617. }
  618. if len(errorDiagnostics) == 0 {
  619. return ""
  620. }
  621. t := theme.CurrentTheme()
  622. var result strings.Builder
  623. for _, diagnostic := range errorDiagnostics {
  624. if result.Len() > 0 {
  625. result.WriteString("\n\n")
  626. }
  627. diagnostic = ansi.WordwrapWc(diagnostic, width, " -")
  628. result.WriteString(
  629. styles.NewStyle().
  630. Background(backgroundColor).
  631. Foreground(t.Error()).
  632. Render(diagnostic),
  633. )
  634. }
  635. return result.String()
  636. }
  637. }
  638. return ""
  639. // diagnosticsData should be a map[string][]Diagnostic
  640. // strDiagnosticsData := diagnosticsData.Raw()
  641. // diagnosticsMap := gjson.Parse(strDiagnosticsData).Value().(map[string]any)
  642. // fileDiagnostics, ok := diagnosticsMap[filePath]
  643. // if !ok {
  644. // return ""
  645. // }
  646. // diagnosticsList, ok := fileDiagnostics.([]any)
  647. // if !ok {
  648. // return ""
  649. // }
  650. }