message.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598
  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 renderText(message client.MessageInfo, text string, author string) string {
  181. t := theme.CurrentTheme()
  182. width := layout.Current.Container.Width
  183. padding := 0
  184. if layout.Current.Viewport.Width < 80 {
  185. padding = 5
  186. } else if layout.Current.Viewport.Width < 120 {
  187. padding = 15
  188. } else {
  189. padding = 20
  190. }
  191. timestamp := time.UnixMilli(int64(message.Metadata.Time.Created)).Local().Format("02 Jan 2006 03:04 PM")
  192. if time.Now().Format("02 Jan 2006") == timestamp[:11] {
  193. // don't show the date if it's today
  194. timestamp = timestamp[12:]
  195. }
  196. info := fmt.Sprintf("%s (%s)", author, timestamp)
  197. textWidth := max(lipgloss.Width(text), lipgloss.Width(info))
  198. markdownWidth := min(textWidth, width-padding-4) // -4 for the border and padding
  199. content := toMarkdown(text, markdownWidth, t.BackgroundSubtle())
  200. content = strings.Join([]string{content, info}, "\n")
  201. // content = lipgloss.JoinVertical(align, content, info)
  202. switch message.Role {
  203. case client.User:
  204. return renderContentBlock(content,
  205. WithAlign(lipgloss.Right),
  206. WithBorderColor(t.Secondary()),
  207. )
  208. case client.Assistant:
  209. return renderContentBlock(content,
  210. WithAlign(lipgloss.Left),
  211. WithBorderColor(t.Accent()),
  212. )
  213. }
  214. return ""
  215. }
  216. func renderToolInvocation(
  217. toolCall client.MessageToolInvocationToolCall,
  218. result *string,
  219. metadata client.MessageInfo_Metadata_Tool_AdditionalProperties,
  220. showResult bool,
  221. ) string {
  222. ignoredTools := []string{"opencode_todoread"}
  223. if slices.Contains(ignoredTools, toolCall.ToolName) {
  224. return ""
  225. }
  226. outerWidth := layout.Current.Container.Width
  227. innerWidth := outerWidth - 6
  228. paddingTop := 0
  229. paddingBottom := 0
  230. if showResult {
  231. paddingTop = 1
  232. if result == nil || *result == "" {
  233. paddingBottom = 1
  234. }
  235. }
  236. t := theme.CurrentTheme()
  237. style := styles.Muted().
  238. Width(outerWidth).
  239. Background(t.BackgroundSubtle()).
  240. PaddingTop(paddingTop).
  241. PaddingBottom(paddingBottom).
  242. PaddingLeft(2).
  243. PaddingRight(2).
  244. BorderLeft(true).
  245. BorderRight(true).
  246. BorderBackground(t.Background()).
  247. BorderForeground(t.BackgroundSubtle()).
  248. BorderStyle(lipgloss.ThickBorder())
  249. if toolCall.State == "partial-call" {
  250. style = style.Foreground(t.TextMuted())
  251. return style.Render(renderToolAction(toolCall.ToolName))
  252. }
  253. toolArgs := ""
  254. toolArgsMap := make(map[string]any)
  255. if toolCall.Args != nil {
  256. value := *toolCall.Args
  257. m, ok := value.(map[string]any)
  258. if ok {
  259. toolArgsMap = m
  260. firstKey := ""
  261. for key := range toolArgsMap {
  262. firstKey = key
  263. break
  264. }
  265. toolArgs = renderArgs(&toolArgsMap, firstKey)
  266. }
  267. }
  268. body := ""
  269. error := ""
  270. finished := result != nil && *result != ""
  271. if e, ok := metadata.Get("error"); ok && e.(bool) == true {
  272. if m, ok := metadata.Get("message"); ok {
  273. style = style.BorderLeftForeground(t.Error())
  274. error = styles.BaseStyle().
  275. Background(t.BackgroundSubtle()).
  276. Foreground(t.Error()).
  277. Render(m.(string))
  278. error = renderContentBlock(
  279. error,
  280. WithFullWidth(),
  281. WithBorderColor(t.Error()),
  282. WithMarginBottom(1),
  283. )
  284. }
  285. }
  286. elapsed := ""
  287. start := metadata.Time.Start
  288. end := metadata.Time.End
  289. durationMs := end - start
  290. duration := time.Duration(durationMs * float32(time.Millisecond))
  291. roundedDuration := time.Duration(duration.Round(time.Millisecond))
  292. if durationMs > 1000 {
  293. roundedDuration = time.Duration(duration.Round(time.Second))
  294. }
  295. elapsed = styles.Muted().Render(roundedDuration.String())
  296. title := ""
  297. switch toolCall.ToolName {
  298. case "opencode_read":
  299. toolArgs = renderArgs(&toolArgsMap, "filePath")
  300. title = fmt.Sprintf("Read: %s %s", toolArgs, elapsed)
  301. if preview, ok := metadata.Get("preview"); ok && toolArgsMap["filePath"] != nil {
  302. filename := toolArgsMap["filePath"].(string)
  303. body = preview.(string)
  304. body = renderFile(filename, body, WithTruncate(6))
  305. }
  306. case "opencode_edit":
  307. if filename, ok := toolArgsMap["filePath"].(string); ok {
  308. title = fmt.Sprintf("Edit: %s %s", relative(filename), elapsed)
  309. if d, ok := metadata.Get("diff"); ok {
  310. patch := d.(string)
  311. var formattedDiff string
  312. if layout.Current.Viewport.Width < 80 {
  313. formattedDiff, _ = diff.FormatUnifiedDiff(
  314. filename,
  315. patch,
  316. diff.WithWidth(layout.Current.Container.Width-2),
  317. )
  318. } else {
  319. diffWidth := min(layout.Current.Viewport.Width-2, 120)
  320. formattedDiff, _ = diff.FormatDiff(filename, patch, diff.WithTotalWidth(diffWidth))
  321. }
  322. formattedDiff = strings.TrimSpace(formattedDiff)
  323. formattedDiff = lipgloss.NewStyle().
  324. BorderStyle(lipgloss.ThickBorder()).
  325. BorderBackground(t.Background()).
  326. BorderForeground(t.BackgroundSubtle()).
  327. BorderLeft(true).
  328. BorderRight(true).
  329. Render(formattedDiff)
  330. if showResult {
  331. style = style.Width(lipgloss.Width(formattedDiff))
  332. title += "\n"
  333. }
  334. body = strings.TrimSpace(formattedDiff)
  335. body = lipgloss.Place(
  336. layout.Current.Viewport.Width,
  337. lipgloss.Height(body)+1,
  338. lipgloss.Center,
  339. lipgloss.Top,
  340. body,
  341. lipgloss.WithWhitespaceStyle(lipgloss.NewStyle().Background(t.Background())),
  342. )
  343. }
  344. }
  345. case "opencode_write":
  346. if filename, ok := toolArgsMap["filePath"].(string); ok {
  347. title = fmt.Sprintf("Write: %s %s", relative(filename), elapsed)
  348. if content, ok := toolArgsMap["content"].(string); ok {
  349. body = renderFile(filename, content)
  350. }
  351. }
  352. case "opencode_bash":
  353. if description, ok := toolArgsMap["description"].(string); ok {
  354. title = fmt.Sprintf("Shell: %s %s", description, elapsed)
  355. }
  356. if stdout, ok := metadata.Get("stdout"); ok {
  357. command := toolArgsMap["command"].(string)
  358. stdout := stdout.(string)
  359. body = fmt.Sprintf("```console\n> %s\n%s```", command, stdout)
  360. body = toMarkdown(body, innerWidth, t.BackgroundSubtle())
  361. body = renderContentBlock(body, WithFullWidth(), WithMarginBottom(1))
  362. }
  363. case "opencode_webfetch":
  364. toolArgs = renderArgs(&toolArgsMap, "url")
  365. title = fmt.Sprintf("Fetching: %s %s", toolArgs, elapsed)
  366. if format, ok := toolArgsMap["format"].(string); ok {
  367. body = *result
  368. body = truncateHeight(body, 10)
  369. if format == "html" || format == "markdown" {
  370. body = toMarkdown(body, innerWidth, t.BackgroundSubtle())
  371. }
  372. body = renderContentBlock(body, WithFullWidth(), WithMarginBottom(1))
  373. }
  374. case "opencode_todowrite":
  375. title = fmt.Sprintf("Planning %s", elapsed)
  376. if to, ok := metadata.Get("todos"); ok && finished {
  377. todos := to.([]any)
  378. for _, todo := range todos {
  379. t := todo.(map[string]any)
  380. content := t["content"].(string)
  381. switch t["status"].(string) {
  382. case "completed":
  383. body += fmt.Sprintf("- [x] %s\n", content)
  384. // case "in-progress":
  385. // body += fmt.Sprintf("- [ ] %s\n", content)
  386. default:
  387. body += fmt.Sprintf("- [ ] %s\n", content)
  388. }
  389. }
  390. body = toMarkdown(body, innerWidth, t.BackgroundSubtle())
  391. body = renderContentBlock(body, WithFullWidth(), WithMarginBottom(1))
  392. }
  393. default:
  394. toolName := renderToolName(toolCall.ToolName)
  395. title = fmt.Sprintf("%s: %s %s", toolName, toolArgs, elapsed)
  396. body = *result
  397. body = truncateHeight(body, 10)
  398. body = renderContentBlock(body, WithFullWidth(), WithMarginBottom(1))
  399. }
  400. if body == "" && error == "" {
  401. body = *result
  402. body = truncateHeight(body, 10)
  403. body = renderContentBlock(body, WithFullWidth(), WithMarginBottom(1))
  404. }
  405. content := style.Render(title)
  406. content = lipgloss.PlaceHorizontal(
  407. layout.Current.Viewport.Width,
  408. lipgloss.Center,
  409. content,
  410. lipgloss.WithWhitespaceStyle(lipgloss.NewStyle().Background(t.Background())),
  411. )
  412. if showResult && body != "" && error == "" {
  413. content += "\n" + body
  414. }
  415. if showResult && error != "" {
  416. content += "\n" + error
  417. }
  418. return content
  419. }
  420. func renderToolName(name string) string {
  421. switch name {
  422. // case agent.AgentToolName:
  423. // return "Task"
  424. case "opencode_ls":
  425. return "List"
  426. case "opencode_webfetch":
  427. return "Fetch"
  428. case "opencode_todoread":
  429. return "Planning"
  430. case "opencode_todowrite":
  431. return "Planning"
  432. default:
  433. normalizedName := name
  434. if strings.HasPrefix(name, "opencode_") {
  435. normalizedName = strings.TrimPrefix(name, "opencode_")
  436. }
  437. return cases.Title(language.Und).String(normalizedName)
  438. }
  439. }
  440. type fileRenderer struct {
  441. filename string
  442. content string
  443. height int
  444. }
  445. type fileRenderingOption func(*fileRenderer)
  446. func WithTruncate(height int) fileRenderingOption {
  447. return func(c *fileRenderer) {
  448. c.height = height
  449. }
  450. }
  451. func renderFile(filename string, content string, options ...fileRenderingOption) string {
  452. t := theme.CurrentTheme()
  453. renderer := &fileRenderer{
  454. filename: filename,
  455. content: content,
  456. }
  457. for _, option := range options {
  458. option(renderer)
  459. }
  460. lines := []string{}
  461. for line := range strings.SplitSeq(content, "\n") {
  462. line = strings.TrimRightFunc(line, unicode.IsSpace)
  463. line = strings.ReplaceAll(line, "\t", " ")
  464. lines = append(lines, line)
  465. }
  466. content = strings.Join(lines, "\n")
  467. width := layout.Current.Container.Width - 8
  468. if renderer.height > 0 {
  469. content = truncateHeight(content, renderer.height)
  470. }
  471. content = fmt.Sprintf("```%s\n%s\n```", extension(renderer.filename), content)
  472. content = toMarkdown(content, width, t.BackgroundSubtle())
  473. return renderContentBlock(content, WithFullWidth(), WithMarginBottom(1))
  474. }
  475. func renderToolAction(name string) string {
  476. switch name {
  477. // case agent.AgentToolName:
  478. // return "Preparing prompt..."
  479. case "opencode_bash":
  480. return "Building command..."
  481. case "opencode_edit":
  482. return "Preparing edit..."
  483. case "opencode_fetch":
  484. return "Writing fetch..."
  485. case "opencode_glob":
  486. return "Finding files..."
  487. case "opencode_grep":
  488. return "Searching content..."
  489. case "opencode_ls":
  490. return "Listing directory..."
  491. case "opencode_read":
  492. return "Reading file..."
  493. case "opencode_write":
  494. return "Preparing write..."
  495. case "opencode_patch":
  496. return "Preparing patch..."
  497. case "opencode_batch":
  498. return "Running batch operations..."
  499. }
  500. return "Working..."
  501. }
  502. func renderArgs(args *map[string]any, titleKey string) string {
  503. if args == nil || len(*args) == 0 {
  504. return ""
  505. }
  506. title := ""
  507. parts := []string{}
  508. for key, value := range *args {
  509. if value == nil {
  510. continue
  511. }
  512. if key == "filePath" || key == "path" {
  513. value = relative(value.(string))
  514. }
  515. if key == titleKey {
  516. title = fmt.Sprintf("%s", value)
  517. continue
  518. }
  519. parts = append(parts, fmt.Sprintf("%s=%v", key, value))
  520. }
  521. if len(parts) == 0 {
  522. return title
  523. }
  524. return fmt.Sprintf("%s (%s)", title, strings.Join(parts, ", "))
  525. }
  526. func truncateHeight(content string, height int) string {
  527. lines := strings.Split(content, "\n")
  528. if len(lines) > height {
  529. return strings.Join(lines[:height], "\n")
  530. }
  531. return content
  532. }
  533. func relative(path string) string {
  534. return strings.TrimPrefix(path, app.RootPath+"/")
  535. }
  536. func extension(path string) string {
  537. ext := filepath.Ext(path)
  538. if ext == "" {
  539. ext = ""
  540. } else {
  541. ext = strings.ToLower(ext[1:])
  542. }
  543. return ext
  544. }