message.go 17 KB

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