message.go 17 KB

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