message.go 18 KB

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