message.go 17 KB

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