message.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. package chat
  2. import (
  3. "fmt"
  4. "log/slog"
  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.Info.Path.Root+"/", "")
  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. }
  53. type renderingOption func(*blockRenderer)
  54. func WithFullWidth() renderingOption {
  55. return func(c *blockRenderer) {
  56. c.fullWidth = true
  57. }
  58. }
  59. func WithAlign(align lipgloss.Position) renderingOption {
  60. return func(c *blockRenderer) {
  61. c.align = &align
  62. }
  63. }
  64. func WithBorderColor(color compat.AdaptiveColor) renderingOption {
  65. return func(c *blockRenderer) {
  66. c.borderColor = &color
  67. }
  68. }
  69. func WithPaddingTop(padding int) renderingOption {
  70. return func(c *blockRenderer) {
  71. c.paddingTop = padding
  72. }
  73. }
  74. func WithPaddingBottom(padding int) renderingOption {
  75. return func(c *blockRenderer) {
  76. c.paddingBottom = padding
  77. }
  78. }
  79. func renderContentBlock(content string, options ...renderingOption) string {
  80. t := theme.CurrentTheme()
  81. renderer := &blockRenderer{
  82. fullWidth: false,
  83. }
  84. for _, option := range options {
  85. option(renderer)
  86. }
  87. style := styles.BaseStyle().
  88. PaddingTop(1).
  89. PaddingBottom(1).
  90. PaddingLeft(2).
  91. PaddingRight(2).
  92. Background(t.BackgroundSubtle()).
  93. Foreground(t.TextMuted()).
  94. BorderStyle(lipgloss.ThickBorder())
  95. align := lipgloss.Left
  96. if renderer.align != nil {
  97. align = *renderer.align
  98. }
  99. borderColor := t.BackgroundSubtle()
  100. if renderer.borderColor != nil {
  101. borderColor = *renderer.borderColor
  102. }
  103. switch align {
  104. case lipgloss.Left:
  105. style = style.
  106. BorderLeft(true).
  107. BorderRight(true).
  108. AlignHorizontal(align).
  109. BorderLeftForeground(borderColor).
  110. BorderLeftBackground(t.Background()).
  111. BorderRightForeground(t.BackgroundSubtle()).
  112. BorderRightBackground(t.Background())
  113. case lipgloss.Right:
  114. style = style.
  115. BorderRight(true).
  116. BorderLeft(true).
  117. AlignHorizontal(align).
  118. BorderRightForeground(borderColor).
  119. BorderRightBackground(t.Background()).
  120. BorderLeftForeground(t.BackgroundSubtle()).
  121. BorderLeftBackground(t.Background())
  122. }
  123. if renderer.fullWidth {
  124. style = style.Width(layout.Current.Container.Width)
  125. }
  126. content = style.Render(content)
  127. if renderer.paddingTop > 0 {
  128. content = strings.Repeat("\n", renderer.paddingTop) + content
  129. }
  130. if renderer.paddingBottom > 0 {
  131. content = content + strings.Repeat("\n", renderer.paddingBottom)
  132. }
  133. content = lipgloss.PlaceHorizontal(
  134. layout.Current.Container.Width,
  135. align,
  136. content,
  137. )
  138. content = lipgloss.PlaceHorizontal(
  139. layout.Current.Viewport.Width,
  140. lipgloss.Center,
  141. content,
  142. )
  143. return content
  144. }
  145. func renderText(message client.MessageInfo, text string, author string) string {
  146. t := theme.CurrentTheme()
  147. width := layout.Current.Container.Width
  148. padding := 0
  149. switch layout.Current.Size {
  150. case layout.LayoutSizeSmall:
  151. padding = 5
  152. case layout.LayoutSizeNormal:
  153. padding = 10
  154. case layout.LayoutSizeLarge:
  155. padding = 15
  156. }
  157. timestamp := time.UnixMilli(int64(message.Metadata.Time.Created)).Local().Format("02 Jan 2006 03:04 PM")
  158. if time.Now().Format("02 Jan 2006") == timestamp[:11] {
  159. // don't show the date if it's today
  160. timestamp = timestamp[12:]
  161. }
  162. info := fmt.Sprintf("%s (%s)", author, timestamp)
  163. align := lipgloss.Left
  164. switch message.Role {
  165. case client.User:
  166. align = lipgloss.Right
  167. case client.Assistant:
  168. align = lipgloss.Left
  169. }
  170. textWidth := lipgloss.Width(text)
  171. markdownWidth := min(textWidth, width-padding-4) // -4 for the border and padding
  172. content := toMarkdown(text, markdownWidth, t.BackgroundSubtle())
  173. content = lipgloss.JoinVertical(align, content, info)
  174. switch message.Role {
  175. case client.User:
  176. return renderContentBlock(content,
  177. WithAlign(lipgloss.Right),
  178. WithBorderColor(t.Secondary()),
  179. )
  180. case client.Assistant:
  181. return renderContentBlock(content,
  182. WithAlign(lipgloss.Left),
  183. WithBorderColor(t.Primary()),
  184. )
  185. }
  186. return ""
  187. }
  188. func renderToolInvocation(
  189. toolCall client.MessageToolInvocationToolCall,
  190. result *string,
  191. metadata client.MessageInfo_Metadata_Tool_AdditionalProperties,
  192. showResult bool,
  193. ) string {
  194. ignoredTools := []string{"opencode_todoread"}
  195. if slices.Contains(ignoredTools, toolCall.ToolName) {
  196. return ""
  197. }
  198. padding := 1
  199. outerWidth := layout.Current.Container.Width - 1 // subtract 1 for the border
  200. innerWidth := outerWidth - padding - 4 // -4 for the border and padding
  201. t := theme.CurrentTheme()
  202. style := styles.Muted().
  203. Width(outerWidth).
  204. PaddingLeft(padding).
  205. BorderLeft(true).
  206. BorderForeground(t.BorderSubtle()).
  207. BorderStyle(lipgloss.ThickBorder())
  208. if toolCall.State == "partial-call" {
  209. style = style.Foreground(t.TextMuted())
  210. return style.Render(renderToolAction(toolCall.ToolName))
  211. }
  212. toolArgs := ""
  213. toolArgsMap := make(map[string]any)
  214. if toolCall.Args != nil {
  215. value := *toolCall.Args
  216. m, ok := value.(map[string]any)
  217. if ok {
  218. toolArgsMap = m
  219. firstKey := ""
  220. for key := range toolArgsMap {
  221. firstKey = key
  222. break
  223. }
  224. toolArgs = renderArgs(&toolArgsMap, firstKey)
  225. }
  226. }
  227. if len(toolArgsMap) == 0 {
  228. slog.Debug("no args")
  229. }
  230. body := ""
  231. error := ""
  232. finished := result != nil && *result != ""
  233. if finished {
  234. body = *result
  235. }
  236. if e, ok := metadata.Get("error"); ok && e.(bool) == true {
  237. if m, ok := metadata.Get("message"); ok {
  238. body = "" // don't show the body if there's an error
  239. error = styles.BaseStyle().
  240. Foreground(t.Error()).
  241. Render(m.(string))
  242. error = renderContentBlock(error, WithBorderColor(t.Error()), WithFullWidth(), WithPaddingTop(1), WithPaddingBottom(1))
  243. }
  244. }
  245. elapsed := ""
  246. start := metadata.Time.Start
  247. end := metadata.Time.End
  248. durationMs := end - start
  249. duration := time.Duration(durationMs * float32(time.Millisecond))
  250. roundedDuration := time.Duration(duration.Round(time.Millisecond))
  251. if durationMs > 1000 {
  252. roundedDuration = time.Duration(duration.Round(time.Second))
  253. }
  254. elapsed = styles.Muted().Render(roundedDuration.String())
  255. title := ""
  256. switch toolCall.ToolName {
  257. case "opencode_read":
  258. toolArgs = renderArgs(&toolArgsMap, "filePath")
  259. title = fmt.Sprintf("Read: %s %s", toolArgs, elapsed)
  260. body = ""
  261. if preview, ok := metadata.Get("preview"); ok && toolArgsMap["filePath"] != nil {
  262. filename := toolArgsMap["filePath"].(string)
  263. body = preview.(string)
  264. body = renderFile(filename, body, WithTruncate(6))
  265. }
  266. case "opencode_edit":
  267. filename := toolArgsMap["filePath"].(string)
  268. title = fmt.Sprintf("Edit: %s %s", relative(filename), elapsed)
  269. if d, ok := metadata.Get("diff"); ok {
  270. patch := d.(string)
  271. diffWidth := min(layout.Current.Viewport.Width, 120)
  272. formattedDiff, _ := diff.FormatDiff(filename, patch, diff.WithTotalWidth(diffWidth))
  273. body = strings.TrimSpace(formattedDiff)
  274. body = lipgloss.Place(
  275. layout.Current.Viewport.Width,
  276. lipgloss.Height(body)+2,
  277. lipgloss.Center,
  278. lipgloss.Center,
  279. body,
  280. lipgloss.WithWhitespaceStyle(lipgloss.NewStyle().Background(t.Background())),
  281. )
  282. }
  283. case "opencode_write":
  284. filename := toolArgsMap["filePath"].(string)
  285. title = fmt.Sprintf("Write: %s %s", relative(filename), elapsed)
  286. content := toolArgsMap["content"].(string)
  287. body = renderFile(filename, content)
  288. case "opencode_bash":
  289. description := toolArgsMap["description"].(string)
  290. title = fmt.Sprintf("Shell: %s %s", description, elapsed)
  291. if stdout, ok := metadata.Get("stdout"); ok {
  292. command := toolArgsMap["command"].(string)
  293. stdout := stdout.(string)
  294. body = fmt.Sprintf("```console\n> %s\n%s```", command, stdout)
  295. body = toMarkdown(body, innerWidth, t.BackgroundSubtle())
  296. body = renderContentBlock(body, WithFullWidth(), WithPaddingTop(1), WithPaddingBottom(1))
  297. }
  298. case "opencode_webfetch":
  299. title = fmt.Sprintf("Fetching: %s %s", toolArgs, elapsed)
  300. format := toolArgsMap["format"].(string)
  301. body = truncateHeight(body, 10)
  302. if format == "html" || format == "markdown" {
  303. body = toMarkdown(body, innerWidth, t.BackgroundSubtle())
  304. }
  305. body = renderContentBlock(body, WithFullWidth(), WithPaddingTop(1), WithPaddingBottom(1))
  306. case "opencode_todowrite":
  307. title = fmt.Sprintf("Planning... %s", elapsed)
  308. if to, ok := metadata.Get("todos"); ok && finished {
  309. body = ""
  310. todos := to.([]any)
  311. for _, todo := range todos {
  312. t := todo.(map[string]any)
  313. content := t["content"].(string)
  314. switch t["status"].(string) {
  315. case "completed":
  316. body += fmt.Sprintf("- [x] %s\n", content)
  317. // case "in-progress":
  318. // body += fmt.Sprintf("- [ ] _%s_\n", content)
  319. default:
  320. body += fmt.Sprintf("- [ ] %s\n", content)
  321. }
  322. }
  323. body = toMarkdown(body, innerWidth, t.BackgroundSubtle())
  324. body = renderContentBlock(body, WithFullWidth(), WithPaddingTop(1), WithPaddingBottom(1))
  325. }
  326. default:
  327. toolName := renderToolName(toolCall.ToolName)
  328. title = fmt.Sprintf("%s: %s %s", toolName, toolArgs, elapsed)
  329. body = truncateHeight(body, 10)
  330. body = renderContentBlock(body, WithFullWidth(), WithPaddingTop(1), WithPaddingBottom(1))
  331. }
  332. content := style.Render(title)
  333. content = lipgloss.PlaceHorizontal(layout.Current.Viewport.Width, lipgloss.Center, content)
  334. if showResult && body != "" && error == "" {
  335. content += "\n" + body
  336. }
  337. if showResult && error != "" {
  338. content += "\n" + error
  339. }
  340. return content
  341. }
  342. func renderToolName(name string) string {
  343. switch name {
  344. // case agent.AgentToolName:
  345. // return "Task"
  346. case "opencode_ls":
  347. return "List"
  348. case "opencode_webfetch":
  349. return "Fetch"
  350. case "opencode_todoread":
  351. return "Planning"
  352. case "opencode_todowrite":
  353. return "Planning"
  354. default:
  355. normalizedName := name
  356. if strings.HasPrefix(name, "opencode_") {
  357. normalizedName = strings.TrimPrefix(name, "opencode_")
  358. }
  359. return cases.Title(language.Und).String(normalizedName)
  360. }
  361. }
  362. type fileRenderer struct {
  363. filename string
  364. content string
  365. height int
  366. }
  367. type fileRenderingOption func(*fileRenderer)
  368. func WithTruncate(height int) fileRenderingOption {
  369. return func(c *fileRenderer) {
  370. c.height = height
  371. }
  372. }
  373. func renderFile(filename string, content string, options ...fileRenderingOption) string {
  374. t := theme.CurrentTheme()
  375. renderer := &fileRenderer{
  376. filename: filename,
  377. content: content,
  378. }
  379. for _, option := range options {
  380. option(renderer)
  381. }
  382. lines := []string{}
  383. for line := range strings.SplitSeq(content, "\n") {
  384. line = strings.TrimRightFunc(line, unicode.IsSpace)
  385. line = strings.ReplaceAll(line, "\t", " ")
  386. lines = append(lines, line)
  387. }
  388. content = strings.Join(lines, "\n")
  389. width := layout.Current.Container.Width - 8
  390. if renderer.height > 0 {
  391. content = truncateHeight(content, renderer.height)
  392. }
  393. content = fmt.Sprintf("```%s\n%s\n```", extension(renderer.filename), content)
  394. content = toMarkdown(content, width, t.BackgroundSubtle())
  395. return renderContentBlock(content, WithFullWidth(), WithPaddingTop(1), WithPaddingBottom(1))
  396. }
  397. func renderToolAction(name string) string {
  398. switch name {
  399. // case agent.AgentToolName:
  400. // return "Preparing prompt..."
  401. case "opencode_bash":
  402. return "Building command..."
  403. case "opencode_edit":
  404. return "Preparing edit..."
  405. case "opencode_fetch":
  406. return "Writing fetch..."
  407. case "opencode_glob":
  408. return "Finding files..."
  409. case "opencode_grep":
  410. return "Searching content..."
  411. case "opencode_ls":
  412. return "Listing directory..."
  413. case "opencode_read":
  414. return "Reading file..."
  415. case "opencode_write":
  416. return "Preparing write..."
  417. case "opencode_patch":
  418. return "Preparing patch..."
  419. case "opencode_batch":
  420. return "Running batch operations..."
  421. }
  422. return "Working..."
  423. }
  424. func renderArgs(args *map[string]any, titleKey string) string {
  425. if args == nil || len(*args) == 0 {
  426. return ""
  427. }
  428. title := ""
  429. parts := []string{}
  430. for key, value := range *args {
  431. if value == nil {
  432. continue
  433. }
  434. if key == "filePath" || key == "path" {
  435. value = relative(value.(string))
  436. }
  437. if key == titleKey {
  438. title = fmt.Sprintf("%s", value)
  439. continue
  440. }
  441. parts = append(parts, fmt.Sprintf("%s=%v", key, value))
  442. }
  443. if len(parts) == 0 {
  444. return title
  445. }
  446. return fmt.Sprintf("%s (%s)", title, strings.Join(parts, ", "))
  447. }
  448. func truncateHeight(content string, height int) string {
  449. lines := strings.Split(content, "\n")
  450. if len(lines) > height {
  451. return strings.Join(lines[:height], "\n")
  452. }
  453. return content
  454. }
  455. func relative(path string) string {
  456. return strings.TrimPrefix(path, app.Info.Path.Root+"/")
  457. }
  458. func extension(path string) string {
  459. ext := filepath.Ext(path)
  460. if ext == "" {
  461. ext = ""
  462. } else {
  463. ext = strings.ToLower(ext[1:])
  464. }
  465. return ext
  466. }