message.go 16 KB

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