message.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  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. body = fmt.Sprintf("```console\n> %s\n%s```", command, stdout)
  338. body = util.ToMarkdown(body, width, backgroundColor)
  339. }
  340. case "webfetch":
  341. if format, ok := toolInputMap["format"].(string); ok && result != nil {
  342. body = *result
  343. body = util.TruncateHeight(body, 10)
  344. if format == "html" || format == "markdown" {
  345. body = util.ToMarkdown(body, width, backgroundColor)
  346. }
  347. }
  348. case "todowrite":
  349. todos := metadata["todos"]
  350. if todos != nil {
  351. for _, item := range todos.([]any) {
  352. todo := item.(map[string]any)
  353. content := todo["content"].(string)
  354. switch todo["status"] {
  355. case "completed":
  356. body += fmt.Sprintf("- [x] %s\n", content)
  357. case "cancelled":
  358. // strike through cancelled todo
  359. body += fmt.Sprintf("- [~] ~~%s~~\n", content)
  360. case "in_progress":
  361. // highlight in progress todo
  362. body += fmt.Sprintf("- [ ] `%s`\n", content)
  363. default:
  364. body += fmt.Sprintf("- [ ] %s\n", content)
  365. }
  366. }
  367. body = util.ToMarkdown(body, width, backgroundColor)
  368. }
  369. case "task":
  370. summary := metadata["summary"]
  371. if summary != nil {
  372. toolcalls := summary.([]any)
  373. steps := []string{}
  374. for _, item := range toolcalls {
  375. data, _ := json.Marshal(item)
  376. var toolCall opencode.ToolPart
  377. _ = json.Unmarshal(data, &toolCall)
  378. step := renderToolTitle(toolCall, width)
  379. step = "∟ " + step
  380. steps = append(steps, step)
  381. }
  382. body = strings.Join(steps, "\n")
  383. }
  384. body = defaultStyle(body)
  385. default:
  386. if result == nil {
  387. empty := ""
  388. result = &empty
  389. }
  390. body = *result
  391. body = util.TruncateHeight(body, 10)
  392. body = defaultStyle(body)
  393. }
  394. }
  395. error := ""
  396. if toolCall.State.Status == opencode.ToolPartStateStatusError {
  397. error = toolCall.State.Error
  398. }
  399. if error != "" {
  400. body = styles.NewStyle().
  401. Width(width - 6).
  402. Foreground(t.Error()).
  403. Background(backgroundColor).
  404. Render(error)
  405. }
  406. if body == "" && error == "" && result != nil {
  407. body = *result
  408. body = util.TruncateHeight(body, 10)
  409. body = defaultStyle(body)
  410. }
  411. if body == "" {
  412. body = defaultStyle("")
  413. }
  414. title := renderToolTitle(toolCall, width)
  415. content := title + "\n\n" + body
  416. return renderContentBlock(app, content, width, WithBorderColor(borderColor))
  417. }
  418. func renderToolName(name string) string {
  419. switch name {
  420. case "webfetch":
  421. return "Fetch"
  422. default:
  423. normalizedName := name
  424. if after, ok := strings.CutPrefix(name, "opencode_"); ok {
  425. normalizedName = after
  426. }
  427. return cases.Title(language.Und).String(normalizedName)
  428. }
  429. }
  430. func getTodoPhase(metadata map[string]any) string {
  431. todos, ok := metadata["todos"].([]any)
  432. if !ok || len(todos) == 0 {
  433. return "Plan"
  434. }
  435. counts := map[string]int{"pending": 0, "completed": 0}
  436. for _, item := range todos {
  437. if todo, ok := item.(map[string]any); ok {
  438. if status, ok := todo["status"].(string); ok {
  439. counts[status]++
  440. }
  441. }
  442. }
  443. total := len(todos)
  444. switch {
  445. case counts["pending"] == total:
  446. return "Creating plan"
  447. case counts["completed"] == total:
  448. return "Completing plan"
  449. default:
  450. return "Updating plan"
  451. }
  452. }
  453. func getTodoTitle(toolCall opencode.ToolPart) string {
  454. if toolCall.State.Status == opencode.ToolPartStateStatusCompleted {
  455. if metadata, ok := toolCall.State.Metadata.(map[string]any); ok {
  456. return getTodoPhase(metadata)
  457. }
  458. }
  459. return "Plan"
  460. }
  461. func renderToolTitle(
  462. toolCall opencode.ToolPart,
  463. width int,
  464. ) string {
  465. if toolCall.State.Status == opencode.ToolPartStateStatusPending {
  466. title := renderToolAction(toolCall.Tool)
  467. return styles.NewStyle().Width(width - 6).Render(title)
  468. }
  469. toolArgs := ""
  470. toolArgsMap := make(map[string]any)
  471. if toolCall.State.Input != nil {
  472. value := toolCall.State.Input
  473. if m, ok := value.(map[string]any); ok {
  474. toolArgsMap = m
  475. keys := make([]string, 0, len(toolArgsMap))
  476. for key := range toolArgsMap {
  477. keys = append(keys, key)
  478. }
  479. slices.Sort(keys)
  480. firstKey := ""
  481. if len(keys) > 0 {
  482. firstKey = keys[0]
  483. }
  484. toolArgs = renderArgs(&toolArgsMap, firstKey)
  485. }
  486. }
  487. title := renderToolName(toolCall.Tool)
  488. switch toolCall.Tool {
  489. case "read":
  490. toolArgs = renderArgs(&toolArgsMap, "filePath")
  491. title = fmt.Sprintf("%s %s", title, toolArgs)
  492. case "edit", "write":
  493. if filename, ok := toolArgsMap["filePath"].(string); ok {
  494. title = fmt.Sprintf("%s %s", title, util.Relative(filename))
  495. }
  496. case "bash", "task":
  497. if description, ok := toolArgsMap["description"].(string); ok {
  498. title = fmt.Sprintf("%s %s", title, description)
  499. }
  500. case "webfetch":
  501. toolArgs = renderArgs(&toolArgsMap, "url")
  502. title = fmt.Sprintf("%s %s", title, toolArgs)
  503. case "todowrite":
  504. title = getTodoTitle(toolCall)
  505. case "todoread":
  506. return "Plan"
  507. default:
  508. toolName := renderToolName(toolCall.Tool)
  509. title = fmt.Sprintf("%s %s", toolName, toolArgs)
  510. }
  511. title = truncate.StringWithTail(title, uint(width-6), "...")
  512. return title
  513. }
  514. func renderToolAction(name string) string {
  515. switch name {
  516. case "task":
  517. return "Planning..."
  518. case "bash":
  519. return "Writing command..."
  520. case "edit":
  521. return "Preparing edit..."
  522. case "webfetch":
  523. return "Fetching from the web..."
  524. case "glob":
  525. return "Finding files..."
  526. case "grep":
  527. return "Searching content..."
  528. case "list":
  529. return "Listing directory..."
  530. case "read":
  531. return "Reading file..."
  532. case "write":
  533. return "Preparing write..."
  534. case "todowrite", "todoread":
  535. return "Planning..."
  536. case "patch":
  537. return "Preparing patch..."
  538. }
  539. return "Working..."
  540. }
  541. func renderArgs(args *map[string]any, titleKey string) string {
  542. if args == nil || len(*args) == 0 {
  543. return ""
  544. }
  545. keys := make([]string, 0, len(*args))
  546. for key := range *args {
  547. keys = append(keys, key)
  548. }
  549. slices.Sort(keys)
  550. title := ""
  551. parts := []string{}
  552. for _, key := range keys {
  553. value := (*args)[key]
  554. if value == nil {
  555. continue
  556. }
  557. if key == "filePath" || key == "path" {
  558. value = util.Relative(value.(string))
  559. }
  560. if key == titleKey {
  561. title = fmt.Sprintf("%s", value)
  562. continue
  563. }
  564. parts = append(parts, fmt.Sprintf("%s=%v", key, value))
  565. }
  566. if len(parts) == 0 {
  567. return title
  568. }
  569. return fmt.Sprintf("%s (%s)", title, strings.Join(parts, ", "))
  570. }
  571. // Diagnostic represents an LSP diagnostic
  572. type Diagnostic struct {
  573. Range struct {
  574. Start struct {
  575. Line int `json:"line"`
  576. Character int `json:"character"`
  577. } `json:"start"`
  578. } `json:"range"`
  579. Severity int `json:"severity"`
  580. Message string `json:"message"`
  581. }
  582. // renderDiagnostics formats LSP diagnostics for display in the TUI
  583. func renderDiagnostics(
  584. metadata map[string]any,
  585. filePath string,
  586. backgroundColor compat.AdaptiveColor,
  587. width int,
  588. ) string {
  589. if diagnosticsData, ok := metadata["diagnostics"].(map[string]any); ok {
  590. if fileDiagnostics, ok := diagnosticsData[filePath].([]any); ok {
  591. var errorDiagnostics []string
  592. for _, diagInterface := range fileDiagnostics {
  593. diagMap, ok := diagInterface.(map[string]any)
  594. if !ok {
  595. continue
  596. }
  597. // Parse the diagnostic
  598. var diag Diagnostic
  599. diagBytes, err := json.Marshal(diagMap)
  600. if err != nil {
  601. continue
  602. }
  603. if err := json.Unmarshal(diagBytes, &diag); err != nil {
  604. continue
  605. }
  606. // Only show error diagnostics (severity === 1)
  607. if diag.Severity != 1 {
  608. continue
  609. }
  610. line := diag.Range.Start.Line + 1 // 1-based
  611. column := diag.Range.Start.Character + 1 // 1-based
  612. errorDiagnostics = append(
  613. errorDiagnostics,
  614. fmt.Sprintf("Error [%d:%d] %s", line, column, diag.Message),
  615. )
  616. }
  617. if len(errorDiagnostics) == 0 {
  618. return ""
  619. }
  620. t := theme.CurrentTheme()
  621. var result strings.Builder
  622. for _, diagnostic := range errorDiagnostics {
  623. if result.Len() > 0 {
  624. result.WriteString("\n\n")
  625. }
  626. diagnostic = ansi.WordwrapWc(diagnostic, width, " -")
  627. result.WriteString(
  628. styles.NewStyle().
  629. Background(backgroundColor).
  630. Foreground(t.Error()).
  631. Render(diagnostic),
  632. )
  633. }
  634. return result.String()
  635. }
  636. }
  637. return ""
  638. // diagnosticsData should be a map[string][]Diagnostic
  639. // strDiagnosticsData := diagnosticsData.Raw()
  640. // diagnosticsMap := gjson.Parse(strDiagnosticsData).Value().(map[string]any)
  641. // fileDiagnostics, ok := diagnosticsMap[filePath]
  642. // if !ok {
  643. // return ""
  644. // }
  645. // diagnosticsList, ok := fileDiagnostics.([]any)
  646. // if !ok {
  647. // return ""
  648. // }
  649. }