message.go 17 KB

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