message.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. package chat
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "path/filepath"
  7. "strings"
  8. "time"
  9. "github.com/charmbracelet/lipgloss"
  10. "github.com/charmbracelet/x/ansi"
  11. "github.com/opencode-ai/opencode/internal/config"
  12. "github.com/opencode-ai/opencode/internal/diff"
  13. "github.com/opencode-ai/opencode/internal/llm/agent"
  14. "github.com/opencode-ai/opencode/internal/llm/models"
  15. "github.com/opencode-ai/opencode/internal/llm/tools"
  16. "github.com/opencode-ai/opencode/internal/message"
  17. "github.com/opencode-ai/opencode/internal/tui/styles"
  18. "github.com/opencode-ai/opencode/internal/tui/theme"
  19. )
  20. type uiMessageType int
  21. const (
  22. userMessageType uiMessageType = iota
  23. assistantMessageType
  24. toolMessageType
  25. maxResultHeight = 10
  26. )
  27. // getDiffWidth returns the width for the diff formatting
  28. func getDiffWidth(width int) int {
  29. return width
  30. }
  31. type uiMessage struct {
  32. ID string
  33. messageType uiMessageType
  34. position int
  35. height int
  36. content string
  37. }
  38. func toMarkdown(content string, focused bool, width int) string {
  39. r := styles.GetMarkdownRenderer(width)
  40. rendered, _ := r.Render(content)
  41. return rendered
  42. }
  43. func renderMessage(msg string, isUser bool, isFocused bool, width int, info ...string) string {
  44. t := theme.CurrentTheme()
  45. style := styles.BaseStyle().
  46. Width(width - 1).
  47. BorderLeft(true).
  48. Foreground(t.TextMuted()).
  49. BorderForeground(t.Primary()).
  50. BorderStyle(lipgloss.ThickBorder())
  51. if isUser {
  52. style = style.BorderForeground(t.Secondary())
  53. }
  54. // Apply markdown formatting and handle background color
  55. parts := []string{
  56. styles.ForceReplaceBackgroundWithLipgloss(toMarkdown(msg, isFocused, width), t.Background()),
  57. }
  58. // Remove newline at the end
  59. parts[0] = strings.TrimSuffix(parts[0], "\n")
  60. if len(info) > 0 {
  61. parts = append(parts, info...)
  62. }
  63. rendered := style.Render(
  64. lipgloss.JoinVertical(
  65. lipgloss.Left,
  66. parts...,
  67. ),
  68. )
  69. return rendered
  70. }
  71. func renderUserMessage(msg message.Message, isFocused bool, width int, position int) uiMessage {
  72. content := renderMessage(msg.Content().String(), true, isFocused, width)
  73. userMsg := uiMessage{
  74. ID: msg.ID,
  75. messageType: userMessageType,
  76. position: position,
  77. height: lipgloss.Height(content),
  78. content: content,
  79. }
  80. return userMsg
  81. }
  82. // Returns multiple uiMessages because of the tool calls
  83. func renderAssistantMessage(
  84. msg message.Message,
  85. msgIndex int,
  86. allMessages []message.Message, // we need this to get tool results and the user message
  87. messagesService message.Service, // We need this to get the task tool messages
  88. focusedUIMessageId string,
  89. width int,
  90. position int,
  91. ) []uiMessage {
  92. messages := []uiMessage{}
  93. content := msg.Content().String()
  94. thinking := msg.IsThinking()
  95. thinkingContent := msg.ReasoningContent().Thinking
  96. finished := msg.IsFinished()
  97. finishData := msg.FinishPart()
  98. info := []string{}
  99. t := theme.CurrentTheme()
  100. baseStyle := styles.BaseStyle()
  101. // Add finish info if available
  102. if finished {
  103. switch finishData.Reason {
  104. case message.FinishReasonEndTurn:
  105. took := formatTimestampDiff(msg.CreatedAt, finishData.Time)
  106. info = append(info, baseStyle.
  107. Width(width-1).
  108. Foreground(t.TextMuted()).
  109. Render(fmt.Sprintf(" %s (%s)", models.SupportedModels[msg.Model].Name, took)),
  110. )
  111. case message.FinishReasonCanceled:
  112. info = append(info, baseStyle.
  113. Width(width-1).
  114. Foreground(t.TextMuted()).
  115. Render(fmt.Sprintf(" %s (%s)", models.SupportedModels[msg.Model].Name, "canceled")),
  116. )
  117. case message.FinishReasonError:
  118. info = append(info, baseStyle.
  119. Width(width-1).
  120. Foreground(t.TextMuted()).
  121. Render(fmt.Sprintf(" %s (%s)", models.SupportedModels[msg.Model].Name, "error")),
  122. )
  123. case message.FinishReasonPermissionDenied:
  124. info = append(info, baseStyle.
  125. Width(width-1).
  126. Foreground(t.TextMuted()).
  127. Render(fmt.Sprintf(" %s (%s)", models.SupportedModels[msg.Model].Name, "permission denied")),
  128. )
  129. }
  130. }
  131. if content != "" || (finished && finishData.Reason == message.FinishReasonEndTurn) {
  132. if content == "" {
  133. content = "*Finished without output*"
  134. }
  135. content = renderMessage(content, false, true, width, info...)
  136. messages = append(messages, uiMessage{
  137. ID: msg.ID,
  138. messageType: assistantMessageType,
  139. position: position,
  140. height: lipgloss.Height(content),
  141. content: content,
  142. })
  143. position += messages[0].height
  144. position++ // for the space
  145. } else if thinking && thinkingContent != "" {
  146. // Render the thinking content
  147. content = renderMessage(thinkingContent, false, msg.ID == focusedUIMessageId, width)
  148. }
  149. for i, toolCall := range msg.ToolCalls() {
  150. toolCallContent := renderToolMessage(
  151. toolCall,
  152. allMessages,
  153. messagesService,
  154. focusedUIMessageId,
  155. false,
  156. width,
  157. i+1,
  158. )
  159. messages = append(messages, toolCallContent)
  160. position += toolCallContent.height
  161. position++ // for the space
  162. }
  163. return messages
  164. }
  165. func findToolResponse(toolCallID string, futureMessages []message.Message) *message.ToolResult {
  166. for _, msg := range futureMessages {
  167. for _, result := range msg.ToolResults() {
  168. if result.ToolCallID == toolCallID {
  169. return &result
  170. }
  171. }
  172. }
  173. return nil
  174. }
  175. func toolName(name string) string {
  176. switch name {
  177. case agent.AgentToolName:
  178. return "Task"
  179. case tools.BashToolName:
  180. return "Bash"
  181. case tools.EditToolName:
  182. return "Edit"
  183. case tools.FetchToolName:
  184. return "Fetch"
  185. case tools.GlobToolName:
  186. return "Glob"
  187. case tools.GrepToolName:
  188. return "Grep"
  189. case tools.LSToolName:
  190. return "List"
  191. case tools.SourcegraphToolName:
  192. return "Sourcegraph"
  193. case tools.ViewToolName:
  194. return "View"
  195. case tools.WriteToolName:
  196. return "Write"
  197. case tools.PatchToolName:
  198. return "Patch"
  199. }
  200. return name
  201. }
  202. func getToolAction(name string) string {
  203. switch name {
  204. case agent.AgentToolName:
  205. return "Preparing prompt..."
  206. case tools.BashToolName:
  207. return "Building command..."
  208. case tools.EditToolName:
  209. return "Preparing edit..."
  210. case tools.FetchToolName:
  211. return "Writing fetch..."
  212. case tools.GlobToolName:
  213. return "Finding files..."
  214. case tools.GrepToolName:
  215. return "Searching content..."
  216. case tools.LSToolName:
  217. return "Listing directory..."
  218. case tools.SourcegraphToolName:
  219. return "Searching code..."
  220. case tools.ViewToolName:
  221. return "Reading file..."
  222. case tools.WriteToolName:
  223. return "Preparing write..."
  224. case tools.PatchToolName:
  225. return "Preparing patch..."
  226. }
  227. return "Working..."
  228. }
  229. // renders params, params[0] (params[1]=params[2] ....)
  230. func renderParams(paramsWidth int, params ...string) string {
  231. if len(params) == 0 {
  232. return ""
  233. }
  234. mainParam := params[0]
  235. if len(mainParam) > paramsWidth {
  236. mainParam = mainParam[:paramsWidth-3] + "..."
  237. }
  238. if len(params) == 1 {
  239. return mainParam
  240. }
  241. otherParams := params[1:]
  242. // create pairs of key/value
  243. // if odd number of params, the last one is a key without value
  244. if len(otherParams)%2 != 0 {
  245. otherParams = append(otherParams, "")
  246. }
  247. parts := make([]string, 0, len(otherParams)/2)
  248. for i := 0; i < len(otherParams); i += 2 {
  249. key := otherParams[i]
  250. value := otherParams[i+1]
  251. if value == "" {
  252. continue
  253. }
  254. parts = append(parts, fmt.Sprintf("%s=%s", key, value))
  255. }
  256. partsRendered := strings.Join(parts, ", ")
  257. remainingWidth := paramsWidth - lipgloss.Width(partsRendered) - 5 // for the space
  258. if remainingWidth < 30 {
  259. // No space for the params, just show the main
  260. return mainParam
  261. }
  262. if len(parts) > 0 {
  263. mainParam = fmt.Sprintf("%s (%s)", mainParam, strings.Join(parts, ", "))
  264. }
  265. return ansi.Truncate(mainParam, paramsWidth, "...")
  266. }
  267. func removeWorkingDirPrefix(path string) string {
  268. wd := config.WorkingDirectory()
  269. if strings.HasPrefix(path, wd) {
  270. path = strings.TrimPrefix(path, wd)
  271. }
  272. if strings.HasPrefix(path, "/") {
  273. path = strings.TrimPrefix(path, "/")
  274. }
  275. if strings.HasPrefix(path, "./") {
  276. path = strings.TrimPrefix(path, "./")
  277. }
  278. if strings.HasPrefix(path, "../") {
  279. path = strings.TrimPrefix(path, "../")
  280. }
  281. return path
  282. }
  283. func renderToolParams(paramWidth int, toolCall message.ToolCall) string {
  284. params := ""
  285. switch toolCall.Name {
  286. case agent.AgentToolName:
  287. var params agent.AgentParams
  288. json.Unmarshal([]byte(toolCall.Input), &params)
  289. prompt := strings.ReplaceAll(params.Prompt, "\n", " ")
  290. return renderParams(paramWidth, prompt)
  291. case tools.BashToolName:
  292. var params tools.BashParams
  293. json.Unmarshal([]byte(toolCall.Input), &params)
  294. command := strings.ReplaceAll(params.Command, "\n", " ")
  295. return renderParams(paramWidth, command)
  296. case tools.EditToolName:
  297. var params tools.EditParams
  298. json.Unmarshal([]byte(toolCall.Input), &params)
  299. filePath := removeWorkingDirPrefix(params.FilePath)
  300. return renderParams(paramWidth, filePath)
  301. case tools.FetchToolName:
  302. var params tools.FetchParams
  303. json.Unmarshal([]byte(toolCall.Input), &params)
  304. url := params.URL
  305. toolParams := []string{
  306. url,
  307. }
  308. if params.Format != "" {
  309. toolParams = append(toolParams, "format", params.Format)
  310. }
  311. if params.Timeout != 0 {
  312. toolParams = append(toolParams, "timeout", (time.Duration(params.Timeout) * time.Second).String())
  313. }
  314. return renderParams(paramWidth, toolParams...)
  315. case tools.GlobToolName:
  316. var params tools.GlobParams
  317. json.Unmarshal([]byte(toolCall.Input), &params)
  318. pattern := params.Pattern
  319. toolParams := []string{
  320. pattern,
  321. }
  322. if params.Path != "" {
  323. toolParams = append(toolParams, "path", params.Path)
  324. }
  325. return renderParams(paramWidth, toolParams...)
  326. case tools.GrepToolName:
  327. var params tools.GrepParams
  328. json.Unmarshal([]byte(toolCall.Input), &params)
  329. pattern := params.Pattern
  330. toolParams := []string{
  331. pattern,
  332. }
  333. if params.Path != "" {
  334. toolParams = append(toolParams, "path", params.Path)
  335. }
  336. if params.Include != "" {
  337. toolParams = append(toolParams, "include", params.Include)
  338. }
  339. if params.LiteralText {
  340. toolParams = append(toolParams, "literal", "true")
  341. }
  342. return renderParams(paramWidth, toolParams...)
  343. case tools.LSToolName:
  344. var params tools.LSParams
  345. json.Unmarshal([]byte(toolCall.Input), &params)
  346. path := params.Path
  347. if path == "" {
  348. path = "."
  349. }
  350. return renderParams(paramWidth, path)
  351. case tools.SourcegraphToolName:
  352. var params tools.SourcegraphParams
  353. json.Unmarshal([]byte(toolCall.Input), &params)
  354. return renderParams(paramWidth, params.Query)
  355. case tools.ViewToolName:
  356. var params tools.ViewParams
  357. json.Unmarshal([]byte(toolCall.Input), &params)
  358. filePath := removeWorkingDirPrefix(params.FilePath)
  359. toolParams := []string{
  360. filePath,
  361. }
  362. if params.Limit != 0 {
  363. toolParams = append(toolParams, "limit", fmt.Sprintf("%d", params.Limit))
  364. }
  365. if params.Offset != 0 {
  366. toolParams = append(toolParams, "offset", fmt.Sprintf("%d", params.Offset))
  367. }
  368. return renderParams(paramWidth, toolParams...)
  369. case tools.WriteToolName:
  370. var params tools.WriteParams
  371. json.Unmarshal([]byte(toolCall.Input), &params)
  372. filePath := removeWorkingDirPrefix(params.FilePath)
  373. return renderParams(paramWidth, filePath)
  374. default:
  375. input := strings.ReplaceAll(toolCall.Input, "\n", " ")
  376. params = renderParams(paramWidth, input)
  377. }
  378. return params
  379. }
  380. func truncateHeight(content string, height int) string {
  381. lines := strings.Split(content, "\n")
  382. if len(lines) > height {
  383. return strings.Join(lines[:height], "\n")
  384. }
  385. return content
  386. }
  387. func renderToolResponse(toolCall message.ToolCall, response message.ToolResult, width int) string {
  388. t := theme.CurrentTheme()
  389. baseStyle := styles.BaseStyle()
  390. if response.IsError {
  391. errContent := fmt.Sprintf("Error: %s", strings.ReplaceAll(response.Content, "\n", " "))
  392. errContent = ansi.Truncate(errContent, width-1, "...")
  393. return baseStyle.
  394. Width(width).
  395. Foreground(t.Error()).
  396. Render(errContent)
  397. }
  398. resultContent := truncateHeight(response.Content, maxResultHeight)
  399. switch toolCall.Name {
  400. case agent.AgentToolName:
  401. return styles.ForceReplaceBackgroundWithLipgloss(
  402. toMarkdown(resultContent, false, width),
  403. t.Background(),
  404. )
  405. case tools.BashToolName:
  406. resultContent = fmt.Sprintf("```bash\n%s\n```", resultContent)
  407. return styles.ForceReplaceBackgroundWithLipgloss(
  408. toMarkdown(resultContent, true, width),
  409. t.Background(),
  410. )
  411. case tools.EditToolName:
  412. metadata := tools.EditResponseMetadata{}
  413. json.Unmarshal([]byte(response.Metadata), &metadata)
  414. truncDiff := truncateHeight(metadata.Diff, maxResultHeight)
  415. formattedDiff, _ := diff.FormatDiff(truncDiff, diff.WithTotalWidth(width))
  416. return formattedDiff
  417. case tools.FetchToolName:
  418. var params tools.FetchParams
  419. json.Unmarshal([]byte(toolCall.Input), &params)
  420. mdFormat := "markdown"
  421. switch params.Format {
  422. case "text":
  423. mdFormat = "text"
  424. case "html":
  425. mdFormat = "html"
  426. }
  427. resultContent = fmt.Sprintf("```%s\n%s\n```", mdFormat, resultContent)
  428. return styles.ForceReplaceBackgroundWithLipgloss(
  429. toMarkdown(resultContent, true, width),
  430. t.Background(),
  431. )
  432. case tools.GlobToolName:
  433. return baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)
  434. case tools.GrepToolName:
  435. return baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)
  436. case tools.LSToolName:
  437. return baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)
  438. case tools.SourcegraphToolName:
  439. return baseStyle.Width(width).Foreground(t.TextMuted()).Render(resultContent)
  440. case tools.ViewToolName:
  441. metadata := tools.ViewResponseMetadata{}
  442. json.Unmarshal([]byte(response.Metadata), &metadata)
  443. ext := filepath.Ext(metadata.FilePath)
  444. if ext == "" {
  445. ext = ""
  446. } else {
  447. ext = strings.ToLower(ext[1:])
  448. }
  449. resultContent = fmt.Sprintf("```%s\n%s\n```", ext, truncateHeight(metadata.Content, maxResultHeight))
  450. return styles.ForceReplaceBackgroundWithLipgloss(
  451. toMarkdown(resultContent, true, width),
  452. t.Background(),
  453. )
  454. case tools.WriteToolName:
  455. params := tools.WriteParams{}
  456. json.Unmarshal([]byte(toolCall.Input), &params)
  457. metadata := tools.WriteResponseMetadata{}
  458. json.Unmarshal([]byte(response.Metadata), &metadata)
  459. ext := filepath.Ext(params.FilePath)
  460. if ext == "" {
  461. ext = ""
  462. } else {
  463. ext = strings.ToLower(ext[1:])
  464. }
  465. resultContent = fmt.Sprintf("```%s\n%s\n```", ext, truncateHeight(params.Content, maxResultHeight))
  466. return styles.ForceReplaceBackgroundWithLipgloss(
  467. toMarkdown(resultContent, true, width),
  468. t.Background(),
  469. )
  470. default:
  471. resultContent = fmt.Sprintf("```text\n%s\n```", resultContent)
  472. return styles.ForceReplaceBackgroundWithLipgloss(
  473. toMarkdown(resultContent, true, width),
  474. t.Background(),
  475. )
  476. }
  477. }
  478. func renderToolMessage(
  479. toolCall message.ToolCall,
  480. allMessages []message.Message,
  481. messagesService message.Service,
  482. focusedUIMessageId string,
  483. nested bool,
  484. width int,
  485. position int,
  486. ) uiMessage {
  487. if nested {
  488. width = width - 3
  489. }
  490. t := theme.CurrentTheme()
  491. baseStyle := styles.BaseStyle()
  492. style := baseStyle.
  493. Width(width - 1).
  494. BorderLeft(true).
  495. BorderStyle(lipgloss.ThickBorder()).
  496. PaddingLeft(1).
  497. BorderForeground(t.TextMuted())
  498. response := findToolResponse(toolCall.ID, allMessages)
  499. toolNameText := baseStyle.Foreground(t.TextMuted()).
  500. Render(fmt.Sprintf("%s: ", toolName(toolCall.Name)))
  501. if !toolCall.Finished {
  502. // Get a brief description of what the tool is doing
  503. toolAction := getToolAction(toolCall.Name)
  504. progressText := baseStyle.
  505. Width(width - 2 - lipgloss.Width(toolNameText)).
  506. Foreground(t.TextMuted()).
  507. Render(fmt.Sprintf("%s", toolAction))
  508. content := style.Render(lipgloss.JoinHorizontal(lipgloss.Left, toolNameText, progressText))
  509. toolMsg := uiMessage{
  510. messageType: toolMessageType,
  511. position: position,
  512. height: lipgloss.Height(content),
  513. content: content,
  514. }
  515. return toolMsg
  516. }
  517. params := renderToolParams(width-2-lipgloss.Width(toolNameText), toolCall)
  518. responseContent := ""
  519. if response != nil {
  520. responseContent = renderToolResponse(toolCall, *response, width-2)
  521. responseContent = strings.TrimSuffix(responseContent, "\n")
  522. } else {
  523. responseContent = baseStyle.
  524. Italic(true).
  525. Width(width - 2).
  526. Foreground(t.TextMuted()).
  527. Render("Waiting for response...")
  528. }
  529. parts := []string{}
  530. if !nested {
  531. formattedParams := baseStyle.
  532. Width(width - 2 - lipgloss.Width(toolNameText)).
  533. Foreground(t.TextMuted()).
  534. Render(params)
  535. parts = append(parts, lipgloss.JoinHorizontal(lipgloss.Left, toolNameText, formattedParams))
  536. } else {
  537. prefix := baseStyle.
  538. Foreground(t.TextMuted()).
  539. Render(" └ ")
  540. formattedParams := baseStyle.
  541. Width(width - 2 - lipgloss.Width(toolNameText)).
  542. Foreground(t.TextMuted()).
  543. Render(params)
  544. parts = append(parts, lipgloss.JoinHorizontal(lipgloss.Left, prefix, toolNameText, formattedParams))
  545. }
  546. if toolCall.Name == agent.AgentToolName {
  547. taskMessages, _ := messagesService.List(context.Background(), toolCall.ID)
  548. toolCalls := []message.ToolCall{}
  549. for _, v := range taskMessages {
  550. toolCalls = append(toolCalls, v.ToolCalls()...)
  551. }
  552. for _, call := range toolCalls {
  553. rendered := renderToolMessage(call, []message.Message{}, messagesService, focusedUIMessageId, true, width, 0)
  554. parts = append(parts, rendered.content)
  555. }
  556. }
  557. if responseContent != "" && !nested {
  558. parts = append(parts, responseContent)
  559. }
  560. content := style.Render(
  561. lipgloss.JoinVertical(
  562. lipgloss.Left,
  563. parts...,
  564. ),
  565. )
  566. if nested {
  567. content = lipgloss.JoinVertical(
  568. lipgloss.Left,
  569. parts...,
  570. )
  571. }
  572. toolMsg := uiMessage{
  573. messageType: toolMessageType,
  574. position: position,
  575. height: lipgloss.Height(content),
  576. content: content,
  577. }
  578. return toolMsg
  579. }
  580. // Helper function to format the time difference between two Unix timestamps
  581. func formatTimestampDiff(start, end int64) string {
  582. diffSeconds := float64(end-start) / 1000.0 // Convert to seconds
  583. if diffSeconds < 1 {
  584. return fmt.Sprintf("%dms", int(diffSeconds*1000))
  585. }
  586. if diffSeconds < 60 {
  587. return fmt.Sprintf("%.1fs", diffSeconds)
  588. }
  589. return fmt.Sprintf("%.1fm", diffSeconds/60)
  590. }