message.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  1. package chat
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "path/filepath"
  6. "slices"
  7. "strings"
  8. "time"
  9. "unicode"
  10. "github.com/charmbracelet/lipgloss/v2"
  11. "github.com/charmbracelet/lipgloss/v2/compat"
  12. "github.com/charmbracelet/x/ansi"
  13. "github.com/sst/opencode/internal/app"
  14. "github.com/sst/opencode/internal/components/diff"
  15. "github.com/sst/opencode/internal/layout"
  16. "github.com/sst/opencode/internal/styles"
  17. "github.com/sst/opencode/internal/theme"
  18. "github.com/sst/opencode/pkg/client"
  19. "golang.org/x/text/cases"
  20. "golang.org/x/text/language"
  21. )
  22. func toMarkdown(content string, width int, backgroundColor compat.AdaptiveColor) string {
  23. r := styles.GetMarkdownRenderer(width, backgroundColor)
  24. content = strings.ReplaceAll(content, app.RootPath+"/", "")
  25. rendered, _ := r.Render(content)
  26. lines := strings.Split(rendered, "\n")
  27. if len(lines) > 0 {
  28. firstLine := lines[0]
  29. cleaned := ansi.Strip(firstLine)
  30. nospace := strings.ReplaceAll(cleaned, " ", "")
  31. if nospace == "" {
  32. lines = lines[1:]
  33. }
  34. if len(lines) > 0 {
  35. lastLine := lines[len(lines)-1]
  36. cleaned = ansi.Strip(lastLine)
  37. nospace = strings.ReplaceAll(cleaned, " ", "")
  38. if nospace == "" {
  39. lines = lines[:len(lines)-1]
  40. }
  41. }
  42. }
  43. content = strings.Join(lines, "\n")
  44. return strings.TrimSuffix(content, "\n")
  45. }
  46. type blockRenderer struct {
  47. align *lipgloss.Position
  48. borderColor *compat.AdaptiveColor
  49. fullWidth bool
  50. paddingTop int
  51. paddingBottom int
  52. paddingLeft int
  53. paddingRight int
  54. marginTop int
  55. marginBottom int
  56. }
  57. type renderingOption func(*blockRenderer)
  58. func WithFullWidth() renderingOption {
  59. return func(c *blockRenderer) {
  60. c.fullWidth = true
  61. }
  62. }
  63. func WithAlign(align lipgloss.Position) renderingOption {
  64. return func(c *blockRenderer) {
  65. c.align = &align
  66. }
  67. }
  68. func WithBorderColor(color compat.AdaptiveColor) renderingOption {
  69. return func(c *blockRenderer) {
  70. c.borderColor = &color
  71. }
  72. }
  73. func WithMarginTop(padding int) renderingOption {
  74. return func(c *blockRenderer) {
  75. c.marginTop = padding
  76. }
  77. }
  78. func WithMarginBottom(padding int) renderingOption {
  79. return func(c *blockRenderer) {
  80. c.marginBottom = padding
  81. }
  82. }
  83. func WithPaddingLeft(padding int) renderingOption {
  84. return func(c *blockRenderer) {
  85. c.paddingLeft = padding
  86. }
  87. }
  88. func WithPaddingRight(padding int) renderingOption {
  89. return func(c *blockRenderer) {
  90. c.paddingRight = padding
  91. }
  92. }
  93. func WithPaddingTop(padding int) renderingOption {
  94. return func(c *blockRenderer) {
  95. c.paddingTop = padding
  96. }
  97. }
  98. func WithPaddingBottom(padding int) renderingOption {
  99. return func(c *blockRenderer) {
  100. c.paddingBottom = padding
  101. }
  102. }
  103. func renderContentBlock(content string, options ...renderingOption) string {
  104. t := theme.CurrentTheme()
  105. renderer := &blockRenderer{
  106. fullWidth: false,
  107. paddingTop: 1,
  108. paddingBottom: 1,
  109. paddingLeft: 2,
  110. paddingRight: 2,
  111. }
  112. for _, option := range options {
  113. option(renderer)
  114. }
  115. style := styles.BaseStyle().
  116. // MarginTop(renderer.marginTop).
  117. // MarginBottom(renderer.marginBottom).
  118. PaddingTop(renderer.paddingTop).
  119. PaddingBottom(renderer.paddingBottom).
  120. PaddingLeft(renderer.paddingLeft).
  121. PaddingRight(renderer.paddingRight).
  122. Background(t.BackgroundPanel()).
  123. Foreground(t.TextMuted()).
  124. BorderStyle(lipgloss.ThickBorder())
  125. align := lipgloss.Left
  126. if renderer.align != nil {
  127. align = *renderer.align
  128. }
  129. borderColor := t.BackgroundPanel()
  130. if renderer.borderColor != nil {
  131. borderColor = *renderer.borderColor
  132. }
  133. switch align {
  134. case lipgloss.Left:
  135. style = style.
  136. BorderLeft(true).
  137. BorderRight(true).
  138. AlignHorizontal(align).
  139. BorderLeftForeground(borderColor).
  140. BorderLeftBackground(t.Background()).
  141. BorderRightForeground(t.BackgroundPanel()).
  142. BorderRightBackground(t.Background())
  143. case lipgloss.Right:
  144. style = style.
  145. BorderRight(true).
  146. BorderLeft(true).
  147. AlignHorizontal(align).
  148. BorderRightForeground(borderColor).
  149. BorderRightBackground(t.Background()).
  150. BorderLeftForeground(t.BackgroundPanel()).
  151. BorderLeftBackground(t.Background())
  152. }
  153. if renderer.fullWidth {
  154. style = style.Width(layout.Current.Container.Width)
  155. }
  156. content = style.Render(content)
  157. content = lipgloss.PlaceHorizontal(
  158. layout.Current.Container.Width,
  159. align,
  160. content,
  161. lipgloss.WithWhitespaceStyle(lipgloss.NewStyle().Background(t.Background())),
  162. )
  163. content = lipgloss.PlaceHorizontal(
  164. layout.Current.Viewport.Width,
  165. lipgloss.Center,
  166. content,
  167. lipgloss.WithWhitespaceStyle(lipgloss.NewStyle().Background(t.Background())),
  168. )
  169. if renderer.marginTop > 0 {
  170. for range renderer.marginTop {
  171. content = "\n" + content
  172. }
  173. }
  174. if renderer.marginBottom > 0 {
  175. for range renderer.marginBottom {
  176. content = content + "\n"
  177. }
  178. }
  179. return content
  180. }
  181. func calculatePadding() int {
  182. if layout.Current.Viewport.Width < 80 {
  183. return 5
  184. } else if layout.Current.Viewport.Width < 120 {
  185. return 15
  186. } else {
  187. return 20
  188. }
  189. }
  190. func renderText(message client.MessageInfo, text string, author string) string {
  191. t := theme.CurrentTheme()
  192. width := layout.Current.Container.Width
  193. padding := calculatePadding()
  194. timestamp := time.UnixMilli(int64(message.Metadata.Time.Created)).Local().Format("02 Jan 2006 03:04 PM")
  195. if time.Now().Format("02 Jan 2006") == timestamp[:11] {
  196. // don't show the date if it's today
  197. timestamp = timestamp[12:]
  198. }
  199. info := fmt.Sprintf("%s (%s)", author, timestamp)
  200. textWidth := max(lipgloss.Width(text), lipgloss.Width(info))
  201. markdownWidth := min(textWidth, width-padding-4) // -4 for the border and padding
  202. if message.Role == client.Assistant {
  203. markdownWidth = width - padding - 4
  204. }
  205. content := toMarkdown(text, markdownWidth, t.BackgroundPanel())
  206. content = strings.Join([]string{content, info}, "\n")
  207. switch message.Role {
  208. case client.User:
  209. return renderContentBlock(content,
  210. WithAlign(lipgloss.Right),
  211. WithBorderColor(t.Secondary()),
  212. )
  213. case client.Assistant:
  214. return renderContentBlock(content,
  215. WithAlign(lipgloss.Left),
  216. WithBorderColor(t.Accent()),
  217. )
  218. }
  219. return ""
  220. }
  221. func renderToolInvocation(
  222. toolCall client.MessageToolInvocationToolCall,
  223. result *string,
  224. metadata client.MessageInfo_Metadata_Tool_AdditionalProperties,
  225. showDetails bool,
  226. isLast bool,
  227. contentOnly bool,
  228. ) string {
  229. ignoredTools := []string{"todoread"}
  230. if slices.Contains(ignoredTools, toolCall.ToolName) {
  231. return ""
  232. }
  233. outerWidth := layout.Current.Container.Width
  234. innerWidth := outerWidth - 6
  235. paddingTop := 0
  236. paddingBottom := 0
  237. if showDetails {
  238. paddingTop = 1
  239. if result == nil || *result == "" {
  240. paddingBottom = 1
  241. }
  242. }
  243. t := theme.CurrentTheme()
  244. style := styles.Muted().
  245. Width(outerWidth).
  246. Background(t.BackgroundPanel()).
  247. PaddingTop(paddingTop).
  248. PaddingBottom(paddingBottom).
  249. PaddingLeft(2).
  250. PaddingRight(2).
  251. BorderLeft(true).
  252. BorderRight(true).
  253. BorderBackground(t.Background()).
  254. BorderForeground(t.BackgroundPanel()).
  255. BorderStyle(lipgloss.ThickBorder())
  256. if toolCall.State == "partial-call" {
  257. title := renderToolAction(toolCall.ToolName)
  258. if !showDetails {
  259. title = "∟ " + title
  260. padding := calculatePadding()
  261. style := lipgloss.NewStyle().Width(outerWidth - padding - 4).Background(t.BackgroundPanel())
  262. return renderContentBlock(style.Render(title),
  263. WithAlign(lipgloss.Left),
  264. WithBorderColor(t.Accent()),
  265. WithPaddingTop(0),
  266. WithPaddingBottom(1),
  267. )
  268. }
  269. style = style.Foreground(t.TextMuted())
  270. return style.Render(title)
  271. }
  272. toolArgs := ""
  273. toolArgsMap := make(map[string]any)
  274. if toolCall.Args != nil {
  275. value := *toolCall.Args
  276. if m, ok := value.(map[string]any); ok {
  277. toolArgsMap = m
  278. keys := make([]string, 0, len(toolArgsMap))
  279. for key := range toolArgsMap {
  280. keys = append(keys, key)
  281. }
  282. slices.Sort(keys)
  283. firstKey := ""
  284. if len(keys) > 0 {
  285. firstKey = keys[0]
  286. }
  287. toolArgs = renderArgs(&toolArgsMap, firstKey)
  288. }
  289. }
  290. body := ""
  291. error := ""
  292. finished := result != nil && *result != ""
  293. if e, ok := metadata.Get("error"); ok && e.(bool) == true {
  294. if m, ok := metadata.Get("message"); ok {
  295. style = style.BorderLeftForeground(t.Error())
  296. error = styles.BaseStyle().
  297. Background(t.BackgroundPanel()).
  298. Foreground(t.Error()).
  299. Render(m.(string))
  300. error = renderContentBlock(
  301. error,
  302. WithFullWidth(),
  303. WithBorderColor(t.Error()),
  304. WithMarginBottom(1),
  305. )
  306. }
  307. }
  308. title := ""
  309. switch toolCall.ToolName {
  310. case "read":
  311. toolArgs = renderArgs(&toolArgsMap, "filePath")
  312. title = fmt.Sprintf("READ %s", toolArgs)
  313. if preview, ok := metadata.Get("preview"); ok && toolArgsMap["filePath"] != nil {
  314. filename := toolArgsMap["filePath"].(string)
  315. body = preview.(string)
  316. body = renderFile(filename, body, WithTruncate(6))
  317. }
  318. case "edit":
  319. if filename, ok := toolArgsMap["filePath"].(string); ok {
  320. title = fmt.Sprintf("EDIT %s", relative(filename))
  321. if d, ok := metadata.Get("diff"); ok {
  322. patch := d.(string)
  323. var formattedDiff string
  324. if layout.Current.Viewport.Width < 80 {
  325. formattedDiff, _ = diff.FormatUnifiedDiff(
  326. filename,
  327. patch,
  328. diff.WithWidth(layout.Current.Container.Width-2),
  329. )
  330. } else {
  331. diffWidth := min(layout.Current.Viewport.Width-2, 120)
  332. formattedDiff, _ = diff.FormatDiff(filename, patch, diff.WithTotalWidth(diffWidth))
  333. }
  334. formattedDiff = strings.TrimSpace(formattedDiff)
  335. formattedDiff = lipgloss.NewStyle().
  336. BorderStyle(lipgloss.ThickBorder()).
  337. BorderBackground(t.Background()).
  338. BorderForeground(t.BackgroundPanel()).
  339. BorderLeft(true).
  340. BorderRight(true).
  341. Render(formattedDiff)
  342. if showDetails {
  343. style = style.Width(lipgloss.Width(formattedDiff))
  344. title += "\n"
  345. }
  346. body = strings.TrimSpace(formattedDiff)
  347. body = lipgloss.Place(
  348. layout.Current.Viewport.Width,
  349. lipgloss.Height(body)+1,
  350. lipgloss.Center,
  351. lipgloss.Top,
  352. body,
  353. lipgloss.WithWhitespaceStyle(lipgloss.NewStyle().Background(t.Background())),
  354. )
  355. }
  356. }
  357. case "write":
  358. if filename, ok := toolArgsMap["filePath"].(string); ok {
  359. title = fmt.Sprintf("WRITE %s", relative(filename))
  360. if content, ok := toolArgsMap["content"].(string); ok {
  361. body = renderFile(filename, content)
  362. }
  363. }
  364. case "bash":
  365. if description, ok := toolArgsMap["description"].(string); ok {
  366. title = fmt.Sprintf("SHELL %s", description)
  367. }
  368. if stdout, ok := metadata.Get("stdout"); ok {
  369. command := toolArgsMap["command"].(string)
  370. stdout := stdout.(string)
  371. body = fmt.Sprintf("```console\n> %s\n%s```", command, stdout)
  372. body = toMarkdown(body, innerWidth, t.BackgroundPanel())
  373. body = renderContentBlock(body, WithFullWidth(), WithMarginBottom(1))
  374. }
  375. case "webfetch":
  376. toolArgs = renderArgs(&toolArgsMap, "url")
  377. title = fmt.Sprintf("FETCH %s", toolArgs)
  378. if format, ok := toolArgsMap["format"].(string); ok {
  379. if result != nil {
  380. body = *result
  381. body = truncateHeight(body, 10)
  382. if format == "html" || format == "markdown" {
  383. body = toMarkdown(body, innerWidth, t.BackgroundPanel())
  384. }
  385. body = renderContentBlock(body, WithFullWidth(), WithMarginBottom(1))
  386. }
  387. }
  388. case "todowrite":
  389. title = fmt.Sprintf("PLAN")
  390. if to, ok := metadata.Get("todos"); ok && finished {
  391. todos := to.([]any)
  392. for _, todo := range todos {
  393. t := todo.(map[string]any)
  394. content := t["content"].(string)
  395. switch t["status"].(string) {
  396. case "completed":
  397. body += fmt.Sprintf("- [x] %s\n", content)
  398. // case "in-progress":
  399. // body += fmt.Sprintf("- [ ] %s\n", content)
  400. default:
  401. body += fmt.Sprintf("- [ ] %s\n", content)
  402. }
  403. }
  404. body = toMarkdown(body, innerWidth, t.BackgroundPanel())
  405. body = renderContentBlock(body, WithFullWidth(), WithMarginBottom(1))
  406. }
  407. case "task":
  408. if description, ok := toolArgsMap["description"].(string); ok {
  409. title = fmt.Sprintf("TASK %s", description)
  410. if summary, ok := metadata.Get("summary"); ok {
  411. toolcalls := summary.([]any)
  412. // toolcalls :=
  413. steps := []string{}
  414. for _, toolcall := range toolcalls {
  415. call := toolcall.(map[string]any)
  416. if toolInvocation, ok := call["toolInvocation"].(map[string]any); ok {
  417. data, _ := json.Marshal(toolInvocation)
  418. var toolCall client.MessageToolInvocationToolCall
  419. _ = json.Unmarshal(data, &toolCall)
  420. if metadata, ok := call["metadata"].(map[string]any); ok {
  421. data, _ = json.Marshal(metadata)
  422. var toolMetadata client.MessageInfo_Metadata_Tool_AdditionalProperties
  423. _ = json.Unmarshal(data, &toolMetadata)
  424. step := renderToolInvocation(
  425. toolCall,
  426. nil,
  427. toolMetadata,
  428. false,
  429. false,
  430. true,
  431. )
  432. steps = append(steps, step)
  433. }
  434. }
  435. }
  436. body = strings.Join(steps, "\n")
  437. body = renderContentBlock(body, WithFullWidth(), WithMarginBottom(1))
  438. }
  439. }
  440. default:
  441. toolName := renderToolName(toolCall.ToolName)
  442. title = fmt.Sprintf("%s %s", toolName, toolArgs)
  443. if result == nil {
  444. empty := ""
  445. result = &empty
  446. }
  447. body = *result
  448. body = truncateHeight(body, 10)
  449. body = renderContentBlock(body, WithFullWidth(), WithMarginBottom(1))
  450. }
  451. if contentOnly {
  452. title = "∟ " + title
  453. return title
  454. }
  455. if !showDetails {
  456. title = "∟ " + title
  457. padding := calculatePadding()
  458. style := lipgloss.NewStyle().Width(outerWidth - padding - 4).Background(t.BackgroundPanel())
  459. paddingBottom := 0
  460. if isLast {
  461. paddingBottom = 1
  462. }
  463. return renderContentBlock(style.Render(title),
  464. WithAlign(lipgloss.Left),
  465. WithBorderColor(t.Accent()),
  466. WithPaddingTop(0),
  467. WithPaddingBottom(paddingBottom),
  468. )
  469. }
  470. if body == "" && error == "" {
  471. body = *result
  472. body = truncateHeight(body, 10)
  473. body = renderContentBlock(body, WithFullWidth(), WithMarginBottom(1))
  474. }
  475. content := style.Render(title)
  476. content = lipgloss.PlaceHorizontal(
  477. layout.Current.Viewport.Width,
  478. lipgloss.Center,
  479. content,
  480. lipgloss.WithWhitespaceStyle(lipgloss.NewStyle().Background(t.Background())),
  481. )
  482. if showDetails && body != "" && error == "" {
  483. content += "\n" + body
  484. }
  485. if showDetails && error != "" {
  486. content += "\n" + error
  487. }
  488. return content
  489. }
  490. func renderToolName(name string) string {
  491. switch name {
  492. case "list":
  493. return "LIST"
  494. case "webfetch":
  495. return "FETCH"
  496. case "todowrite":
  497. return "PLAN"
  498. default:
  499. normalizedName := name
  500. if strings.HasPrefix(name, "opencode_") {
  501. normalizedName = strings.TrimPrefix(name, "opencode_")
  502. }
  503. return cases.Upper(language.Und).String(normalizedName)
  504. }
  505. }
  506. type fileRenderer struct {
  507. filename string
  508. content string
  509. height int
  510. }
  511. type fileRenderingOption func(*fileRenderer)
  512. func WithTruncate(height int) fileRenderingOption {
  513. return func(c *fileRenderer) {
  514. c.height = height
  515. }
  516. }
  517. func renderFile(filename string, content string, options ...fileRenderingOption) string {
  518. t := theme.CurrentTheme()
  519. renderer := &fileRenderer{
  520. filename: filename,
  521. content: content,
  522. }
  523. for _, option := range options {
  524. option(renderer)
  525. }
  526. lines := []string{}
  527. for line := range strings.SplitSeq(content, "\n") {
  528. line = strings.TrimRightFunc(line, unicode.IsSpace)
  529. line = strings.ReplaceAll(line, "\t", " ")
  530. lines = append(lines, line)
  531. }
  532. content = strings.Join(lines, "\n")
  533. width := layout.Current.Container.Width - 8
  534. if renderer.height > 0 {
  535. content = truncateHeight(content, renderer.height)
  536. }
  537. content = fmt.Sprintf("```%s\n%s\n```", extension(renderer.filename), content)
  538. content = toMarkdown(content, width, t.BackgroundPanel())
  539. return renderContentBlock(content, WithFullWidth(), WithMarginBottom(1))
  540. }
  541. func renderToolAction(name string) string {
  542. switch name {
  543. case "task":
  544. return "Searching..."
  545. case "bash":
  546. return "Building 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. case "batch":
  566. return "Running batch operations..."
  567. }
  568. return "Working..."
  569. }
  570. func renderArgs(args *map[string]any, titleKey string) string {
  571. if args == nil || len(*args) == 0 {
  572. return ""
  573. }
  574. keys := make([]string, 0, len(*args))
  575. for key := range *args {
  576. keys = append(keys, key)
  577. }
  578. slices.Sort(keys)
  579. title := ""
  580. parts := []string{}
  581. for _, key := range keys {
  582. value := (*args)[key]
  583. if value == nil {
  584. continue
  585. }
  586. if key == "filePath" || key == "path" {
  587. value = relative(value.(string))
  588. }
  589. if key == titleKey {
  590. title = fmt.Sprintf("%s", value)
  591. continue
  592. }
  593. parts = append(parts, fmt.Sprintf("%s=%v", key, value))
  594. }
  595. if len(parts) == 0 {
  596. return title
  597. }
  598. return fmt.Sprintf("%s (%s)", title, strings.Join(parts, ", "))
  599. }
  600. func truncateHeight(content string, height int) string {
  601. lines := strings.Split(content, "\n")
  602. if len(lines) > height {
  603. return strings.Join(lines[:height], "\n")
  604. }
  605. return content
  606. }
  607. func relative(path string) string {
  608. return strings.TrimPrefix(path, app.RootPath+"/")
  609. }
  610. func extension(path string) string {
  611. ext := filepath.Ext(path)
  612. if ext == "" {
  613. ext = ""
  614. } else {
  615. ext = strings.ToLower(ext[1:])
  616. }
  617. return ext
  618. }