message.go 17 KB

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