message.go 15 KB

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