message.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681
  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.BackgroundSubtle()).
  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.BackgroundSubtle()
  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.BackgroundSubtle()).
  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.BackgroundSubtle()).
  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.BackgroundSubtle())
  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.BackgroundSubtle()).
  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.BackgroundSubtle()).
  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.BackgroundSubtle())
  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.BackgroundSubtle()).
  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.BackgroundSubtle()).
  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.BackgroundSubtle())
  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. body = *result
  380. body = truncateHeight(body, 10)
  381. if format == "html" || format == "markdown" {
  382. body = toMarkdown(body, innerWidth, t.BackgroundSubtle())
  383. }
  384. body = renderContentBlock(body, WithFullWidth(), WithMarginBottom(1))
  385. }
  386. case "todowrite":
  387. title = fmt.Sprintf("PLAN")
  388. if to, ok := metadata.Get("todos"); ok && finished {
  389. todos := to.([]any)
  390. for _, todo := range todos {
  391. t := todo.(map[string]any)
  392. content := t["content"].(string)
  393. switch t["status"].(string) {
  394. case "completed":
  395. body += fmt.Sprintf("- [x] %s\n", content)
  396. // case "in-progress":
  397. // body += fmt.Sprintf("- [ ] %s\n", content)
  398. default:
  399. body += fmt.Sprintf("- [ ] %s\n", content)
  400. }
  401. }
  402. body = toMarkdown(body, innerWidth, t.BackgroundSubtle())
  403. body = renderContentBlock(body, WithFullWidth(), WithMarginBottom(1))
  404. }
  405. case "task":
  406. if description, ok := toolArgsMap["description"].(string); ok {
  407. title = fmt.Sprintf("TASK %s", description)
  408. if summary, ok := metadata.Get("summary"); ok {
  409. toolcalls := summary.([]any)
  410. // toolcalls :=
  411. steps := []string{}
  412. for _, toolcall := range toolcalls {
  413. call := toolcall.(map[string]any)
  414. if toolInvocation, ok := call["toolInvocation"].(map[string]any); ok {
  415. data, _ := json.Marshal(toolInvocation)
  416. var toolCall client.MessageToolInvocationToolCall
  417. _ = json.Unmarshal(data, &toolCall)
  418. if metadata, ok := call["metadata"].(map[string]any); ok {
  419. data, _ = json.Marshal(metadata)
  420. var toolMetadata client.MessageInfo_Metadata_Tool_AdditionalProperties
  421. _ = json.Unmarshal(data, &toolMetadata)
  422. step := renderToolInvocation(
  423. toolCall,
  424. nil,
  425. toolMetadata,
  426. false,
  427. false,
  428. true,
  429. )
  430. steps = append(steps, step)
  431. }
  432. }
  433. }
  434. body = strings.Join(steps, "\n")
  435. body = renderContentBlock(body, WithFullWidth(), WithMarginBottom(1))
  436. }
  437. }
  438. default:
  439. toolName := renderToolName(toolCall.ToolName)
  440. title = fmt.Sprintf("%s %s", toolName, toolArgs)
  441. if result == nil {
  442. empty := ""
  443. result = &empty
  444. }
  445. body = *result
  446. body = truncateHeight(body, 10)
  447. body = renderContentBlock(body, WithFullWidth(), WithMarginBottom(1))
  448. }
  449. if contentOnly {
  450. title = "∟ " + title
  451. return title
  452. }
  453. if !showDetails {
  454. title = "∟ " + title
  455. padding := calculatePadding()
  456. style := lipgloss.NewStyle().Width(outerWidth - padding - 4).Background(t.BackgroundSubtle())
  457. paddingBottom := 0
  458. if isLast {
  459. paddingBottom = 1
  460. }
  461. return renderContentBlock(style.Render(title),
  462. WithAlign(lipgloss.Left),
  463. WithBorderColor(t.Accent()),
  464. WithPaddingTop(0),
  465. WithPaddingBottom(paddingBottom),
  466. )
  467. }
  468. if body == "" && error == "" {
  469. body = *result
  470. body = truncateHeight(body, 10)
  471. body = renderContentBlock(body, WithFullWidth(), WithMarginBottom(1))
  472. }
  473. content := style.Render(title)
  474. content = lipgloss.PlaceHorizontal(
  475. layout.Current.Viewport.Width,
  476. lipgloss.Center,
  477. content,
  478. lipgloss.WithWhitespaceStyle(lipgloss.NewStyle().Background(t.Background())),
  479. )
  480. if showDetails && body != "" && error == "" {
  481. content += "\n" + body
  482. }
  483. if showDetails && error != "" {
  484. content += "\n" + error
  485. }
  486. return content
  487. }
  488. func renderToolName(name string) string {
  489. switch name {
  490. case "list":
  491. return "LIST"
  492. case "webfetch":
  493. return "FETCH"
  494. case "todowrite":
  495. return "PLAN"
  496. default:
  497. normalizedName := name
  498. if strings.HasPrefix(name, "opencode_") {
  499. normalizedName = strings.TrimPrefix(name, "opencode_")
  500. }
  501. return cases.Upper(language.Und).String(normalizedName)
  502. }
  503. }
  504. type fileRenderer struct {
  505. filename string
  506. content string
  507. height int
  508. }
  509. type fileRenderingOption func(*fileRenderer)
  510. func WithTruncate(height int) fileRenderingOption {
  511. return func(c *fileRenderer) {
  512. c.height = height
  513. }
  514. }
  515. func renderFile(filename string, content string, options ...fileRenderingOption) string {
  516. t := theme.CurrentTheme()
  517. renderer := &fileRenderer{
  518. filename: filename,
  519. content: content,
  520. }
  521. for _, option := range options {
  522. option(renderer)
  523. }
  524. lines := []string{}
  525. for line := range strings.SplitSeq(content, "\n") {
  526. line = strings.TrimRightFunc(line, unicode.IsSpace)
  527. line = strings.ReplaceAll(line, "\t", " ")
  528. lines = append(lines, line)
  529. }
  530. content = strings.Join(lines, "\n")
  531. width := layout.Current.Container.Width - 8
  532. if renderer.height > 0 {
  533. content = truncateHeight(content, renderer.height)
  534. }
  535. content = fmt.Sprintf("```%s\n%s\n```", extension(renderer.filename), content)
  536. content = toMarkdown(content, width, t.BackgroundSubtle())
  537. return renderContentBlock(content, WithFullWidth(), WithMarginBottom(1))
  538. }
  539. func renderToolAction(name string) string {
  540. switch name {
  541. case "task":
  542. return "Searching..."
  543. case "bash":
  544. return "Building command..."
  545. case "edit":
  546. return "Preparing edit..."
  547. case "webfetch":
  548. return "Writing fetch..."
  549. case "glob":
  550. return "Finding files..."
  551. case "grep":
  552. return "Searching content..."
  553. case "list":
  554. return "Listing directory..."
  555. case "read":
  556. return "Reading file..."
  557. case "write":
  558. return "Preparing write..."
  559. case "todowrite", "todoread":
  560. return "Planning..."
  561. case "patch":
  562. return "Preparing patch..."
  563. case "batch":
  564. return "Running batch operations..."
  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 = 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. func truncateHeight(content string, height int) string {
  599. lines := strings.Split(content, "\n")
  600. if len(lines) > height {
  601. return strings.Join(lines[:height], "\n")
  602. }
  603. return content
  604. }
  605. func relative(path string) string {
  606. return strings.TrimPrefix(path, app.RootPath+"/")
  607. }
  608. func extension(path string) string {
  609. ext := filepath.Ext(path)
  610. if ext == "" {
  611. ext = ""
  612. } else {
  613. ext = strings.ToLower(ext[1:])
  614. }
  615. return ext
  616. }