message.go 15 KB

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