message.go 25 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004
  1. package chat
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "maps"
  6. "slices"
  7. "strings"
  8. "time"
  9. "github.com/charmbracelet/lipgloss/v2"
  10. "github.com/charmbracelet/lipgloss/v2/compat"
  11. "github.com/charmbracelet/x/ansi"
  12. "github.com/muesli/reflow/truncate"
  13. "github.com/sst/opencode-sdk-go"
  14. "github.com/sst/opencode/internal/app"
  15. "github.com/sst/opencode/internal/commands"
  16. "github.com/sst/opencode/internal/components/diff"
  17. "github.com/sst/opencode/internal/styles"
  18. "github.com/sst/opencode/internal/theme"
  19. "github.com/sst/opencode/internal/util"
  20. "golang.org/x/text/cases"
  21. "golang.org/x/text/language"
  22. )
  23. type blockRenderer struct {
  24. textColor compat.AdaptiveColor
  25. backgroundColor compat.AdaptiveColor
  26. border bool
  27. borderColor *compat.AdaptiveColor
  28. borderLeft bool
  29. borderRight bool
  30. paddingTop int
  31. paddingBottom int
  32. paddingLeft int
  33. paddingRight int
  34. marginTop int
  35. marginBottom int
  36. }
  37. type renderingOption func(*blockRenderer)
  38. func WithTextColor(color compat.AdaptiveColor) renderingOption {
  39. return func(c *blockRenderer) {
  40. c.textColor = color
  41. }
  42. }
  43. func WithBackgroundColor(color compat.AdaptiveColor) renderingOption {
  44. return func(c *blockRenderer) {
  45. c.backgroundColor = color
  46. }
  47. }
  48. func WithNoBorder() renderingOption {
  49. return func(c *blockRenderer) {
  50. c.border = false
  51. }
  52. }
  53. func WithBorderColor(color compat.AdaptiveColor) renderingOption {
  54. return func(c *blockRenderer) {
  55. c.borderColor = &color
  56. }
  57. }
  58. func WithBorderLeft() renderingOption {
  59. return func(c *blockRenderer) {
  60. c.borderLeft = true
  61. c.borderRight = false
  62. }
  63. }
  64. func WithBorderRight() renderingOption {
  65. return func(c *blockRenderer) {
  66. c.borderLeft = false
  67. c.borderRight = true
  68. }
  69. }
  70. func WithBorderBoth(value bool) renderingOption {
  71. return func(c *blockRenderer) {
  72. if value {
  73. c.borderLeft = true
  74. c.borderRight = true
  75. }
  76. }
  77. }
  78. func WithMarginTop(padding int) renderingOption {
  79. return func(c *blockRenderer) {
  80. c.marginTop = padding
  81. }
  82. }
  83. func WithMarginBottom(padding int) renderingOption {
  84. return func(c *blockRenderer) {
  85. c.marginBottom = padding
  86. }
  87. }
  88. func WithPadding(padding int) renderingOption {
  89. return func(c *blockRenderer) {
  90. c.paddingTop = padding
  91. c.paddingBottom = padding
  92. c.paddingLeft = padding
  93. c.paddingRight = padding
  94. }
  95. }
  96. func WithPaddingLeft(padding int) renderingOption {
  97. return func(c *blockRenderer) {
  98. c.paddingLeft = padding
  99. }
  100. }
  101. func WithPaddingRight(padding int) renderingOption {
  102. return func(c *blockRenderer) {
  103. c.paddingRight = padding
  104. }
  105. }
  106. func WithPaddingTop(padding int) renderingOption {
  107. return func(c *blockRenderer) {
  108. c.paddingTop = padding
  109. }
  110. }
  111. func WithPaddingBottom(padding int) renderingOption {
  112. return func(c *blockRenderer) {
  113. c.paddingBottom = padding
  114. }
  115. }
  116. func renderContentBlock(
  117. app *app.App,
  118. content string,
  119. width int,
  120. options ...renderingOption,
  121. ) string {
  122. t := theme.CurrentTheme()
  123. renderer := &blockRenderer{
  124. textColor: t.TextMuted(),
  125. backgroundColor: t.BackgroundPanel(),
  126. border: true,
  127. borderLeft: true,
  128. borderRight: false,
  129. paddingTop: 1,
  130. paddingBottom: 1,
  131. paddingLeft: 2,
  132. paddingRight: 2,
  133. }
  134. for _, option := range options {
  135. option(renderer)
  136. }
  137. borderColor := t.BackgroundPanel()
  138. if renderer.borderColor != nil {
  139. borderColor = *renderer.borderColor
  140. }
  141. style := styles.NewStyle().
  142. Foreground(renderer.textColor).
  143. Background(renderer.backgroundColor).
  144. PaddingTop(renderer.paddingTop).
  145. PaddingBottom(renderer.paddingBottom).
  146. PaddingLeft(renderer.paddingLeft).
  147. PaddingRight(renderer.paddingRight).
  148. AlignHorizontal(lipgloss.Left)
  149. if renderer.border {
  150. style = style.
  151. BorderStyle(lipgloss.ThickBorder()).
  152. BorderLeft(true).
  153. BorderRight(true).
  154. BorderLeftForeground(t.BackgroundPanel()).
  155. BorderLeftBackground(t.Background()).
  156. BorderRightForeground(t.BackgroundPanel()).
  157. BorderRightBackground(t.Background())
  158. if renderer.borderLeft {
  159. style = style.BorderLeftForeground(borderColor)
  160. }
  161. if renderer.borderRight {
  162. style = style.BorderRightForeground(borderColor)
  163. }
  164. } else {
  165. style = style.PaddingLeft(renderer.paddingLeft + 1).PaddingRight(renderer.paddingRight + 1)
  166. }
  167. content = style.Render(content)
  168. if renderer.marginTop > 0 {
  169. for range renderer.marginTop {
  170. content = "\n" + content
  171. }
  172. }
  173. if renderer.marginBottom > 0 {
  174. for range renderer.marginBottom {
  175. content = content + "\n"
  176. }
  177. }
  178. return content
  179. }
  180. func renderText(
  181. app *app.App,
  182. message opencode.MessageUnion,
  183. text string,
  184. author string,
  185. showToolDetails bool,
  186. width int,
  187. extra string,
  188. isThinking bool,
  189. isQueued bool,
  190. fileParts []opencode.FilePart,
  191. agentParts []opencode.AgentPart,
  192. toolCalls ...opencode.ToolPart,
  193. ) string {
  194. t := theme.CurrentTheme()
  195. var ts time.Time
  196. backgroundColor := t.BackgroundPanel()
  197. var content string
  198. switch casted := message.(type) {
  199. case opencode.AssistantMessage:
  200. backgroundColor = t.Background()
  201. if isThinking {
  202. backgroundColor = t.BackgroundPanel()
  203. }
  204. ts = time.UnixMilli(int64(casted.Time.Created))
  205. if casted.Time.Completed > 0 {
  206. ts = time.UnixMilli(int64(casted.Time.Completed))
  207. }
  208. content = util.ToMarkdown(text, width, backgroundColor)
  209. if isThinking {
  210. label := util.Shimmer("Thinking...", backgroundColor, t.TextMuted(), t.Accent())
  211. label = styles.NewStyle().Background(backgroundColor).Width(width - 6).Render(label)
  212. content = label + "\n\n" + content
  213. } else if strings.TrimSpace(text) == "Generating..." {
  214. label := util.Shimmer(text, backgroundColor, t.TextMuted(), t.Text())
  215. label = styles.NewStyle().Background(backgroundColor).Width(width - 6).Render(label)
  216. content = label
  217. }
  218. case opencode.UserMessage:
  219. ts = time.UnixMilli(int64(casted.Time.Created))
  220. base := styles.NewStyle().Foreground(t.Text()).Background(backgroundColor)
  221. var result strings.Builder
  222. lastEnd := int64(0)
  223. // Apply highlighting to filenames and base style to rest of text BEFORE wrapping
  224. textLen := int64(len(text))
  225. // Collect all parts to highlight (both file and agent parts)
  226. type highlightPart struct {
  227. start int64
  228. end int64
  229. color compat.AdaptiveColor
  230. }
  231. var highlights []highlightPart
  232. // Add file parts with secondary color
  233. for _, filePart := range fileParts {
  234. highlights = append(highlights, highlightPart{
  235. start: filePart.Source.Text.Start,
  236. end: filePart.Source.Text.End,
  237. color: t.Secondary(),
  238. })
  239. }
  240. // Add agent parts with secondary color (same as file parts)
  241. for _, agentPart := range agentParts {
  242. highlights = append(highlights, highlightPart{
  243. start: agentPart.Source.Start,
  244. end: agentPart.Source.End,
  245. color: t.Secondary(),
  246. })
  247. }
  248. // Sort highlights by start position
  249. slices.SortFunc(highlights, func(a, b highlightPart) int {
  250. if a.start < b.start {
  251. return -1
  252. }
  253. if a.start > b.start {
  254. return 1
  255. }
  256. return 0
  257. })
  258. // Merge overlapping highlights to prevent duplication
  259. merged := make([]highlightPart, 0)
  260. for _, part := range highlights {
  261. if len(merged) == 0 {
  262. merged = append(merged, part)
  263. continue
  264. }
  265. last := &merged[len(merged)-1]
  266. // If current part overlaps with the last one, merge them
  267. if part.start <= last.end {
  268. if part.end > last.end {
  269. last.end = part.end
  270. }
  271. } else {
  272. merged = append(merged, part)
  273. }
  274. }
  275. for _, part := range merged {
  276. highlight := base.Foreground(part.color)
  277. start, end := part.start, part.end
  278. if end > textLen {
  279. end = textLen
  280. }
  281. if start > textLen {
  282. start = textLen
  283. }
  284. if start > lastEnd {
  285. result.WriteString(base.Render(text[lastEnd:start]))
  286. }
  287. if start < end {
  288. result.WriteString(highlight.Render(text[start:end]))
  289. }
  290. lastEnd = end
  291. }
  292. if lastEnd < textLen {
  293. result.WriteString(base.Render(text[lastEnd:]))
  294. }
  295. // wrap styled text
  296. styledText := result.String()
  297. styledText = strings.ReplaceAll(styledText, "-", "\u2011")
  298. wrappedText := ansi.WordwrapWc(styledText, width-6, " ")
  299. wrappedText = strings.ReplaceAll(wrappedText, "\u2011", "-")
  300. content = base.Width(width - 6).Render(wrappedText)
  301. if isQueued {
  302. queuedStyle := styles.NewStyle().Background(t.Accent()).Foreground(t.BackgroundPanel()).Bold(true).Padding(0, 1)
  303. content = queuedStyle.Render("QUEUED") + "\n\n" + content
  304. }
  305. }
  306. timestamp := ts.
  307. Local().
  308. Format("02 Jan 2006 03:04 PM")
  309. if time.Now().Format("02 Jan 2006") == timestamp[:11] {
  310. timestamp = timestamp[12:]
  311. }
  312. timestamp = styles.NewStyle().
  313. Background(backgroundColor).
  314. Foreground(t.TextMuted()).
  315. Render(" (" + timestamp + ")")
  316. // Check if this is an assistant message with agent information
  317. var modelAndAgentSuffix string
  318. if assistantMsg, ok := message.(opencode.AssistantMessage); ok && assistantMsg.Mode != "" {
  319. // Find the agent index by name to get the correct color
  320. var agentIndex int
  321. for i, agent := range app.Agents {
  322. if agent.Name == assistantMsg.Mode {
  323. agentIndex = i
  324. break
  325. }
  326. }
  327. // Get agent color based on the original agent index (same as status bar)
  328. agentColor := util.GetAgentColor(agentIndex)
  329. // Style the agent name with the same color as status bar
  330. agentName := cases.Title(language.Und).String(assistantMsg.Mode)
  331. styledAgentName := styles.NewStyle().
  332. Background(backgroundColor).
  333. Foreground(agentColor).
  334. Render(agentName + " ")
  335. styledModelID := styles.NewStyle().
  336. Background(backgroundColor).
  337. Foreground(t.TextMuted()).
  338. Render(assistantMsg.ModelID)
  339. modelAndAgentSuffix = styledAgentName + styledModelID
  340. }
  341. var info string
  342. if modelAndAgentSuffix != "" {
  343. info = modelAndAgentSuffix + timestamp
  344. } else {
  345. info = author + timestamp
  346. }
  347. if !showToolDetails && toolCalls != nil && len(toolCalls) > 0 {
  348. for _, toolCall := range toolCalls {
  349. title := renderToolTitle(toolCall, width-2)
  350. style := styles.NewStyle()
  351. if toolCall.State.Status == opencode.ToolPartStateStatusError {
  352. style = style.Foreground(t.Error())
  353. }
  354. title = style.Render(title)
  355. title = "\n∟ " + title
  356. content = content + title
  357. }
  358. }
  359. sections := []string{content}
  360. if extra != "" {
  361. sections = append(sections, "\n"+extra+"\n")
  362. }
  363. sections = append(sections, info)
  364. content = strings.Join(sections, "\n")
  365. switch message.(type) {
  366. case opencode.UserMessage:
  367. borderColor := t.Secondary()
  368. if isQueued {
  369. borderColor = t.Accent()
  370. }
  371. return renderContentBlock(
  372. app,
  373. content,
  374. width,
  375. WithTextColor(t.Text()),
  376. WithBorderColor(borderColor),
  377. )
  378. case opencode.AssistantMessage:
  379. if isThinking {
  380. return renderContentBlock(
  381. app,
  382. content,
  383. width,
  384. WithTextColor(t.Text()),
  385. WithBackgroundColor(t.BackgroundPanel()),
  386. WithBorderColor(t.BackgroundPanel()),
  387. )
  388. }
  389. return renderContentBlock(
  390. app,
  391. content,
  392. width,
  393. WithNoBorder(),
  394. WithBackgroundColor(t.Background()),
  395. )
  396. }
  397. return ""
  398. }
  399. func renderToolDetails(
  400. app *app.App,
  401. toolCall opencode.ToolPart,
  402. permission opencode.Permission,
  403. width int,
  404. ) string {
  405. measure := util.Measure("chat.renderToolDetails")
  406. defer measure("tool", toolCall.Tool)
  407. ignoredTools := []string{"todoread"}
  408. if slices.Contains(ignoredTools, toolCall.Tool) {
  409. return ""
  410. }
  411. if toolCall.State.Status == opencode.ToolPartStateStatusPending {
  412. title := renderToolTitle(toolCall, width)
  413. return renderContentBlock(app, title, width)
  414. }
  415. var result *string
  416. if toolCall.State.Output != "" {
  417. result = &toolCall.State.Output
  418. }
  419. toolInputMap := make(map[string]any)
  420. if toolCall.State.Input != nil {
  421. value := toolCall.State.Input
  422. if m, ok := value.(map[string]any); ok {
  423. toolInputMap = m
  424. keys := make([]string, 0, len(toolInputMap))
  425. for key := range toolInputMap {
  426. keys = append(keys, key)
  427. }
  428. slices.Sort(keys)
  429. }
  430. }
  431. body := ""
  432. t := theme.CurrentTheme()
  433. backgroundColor := t.BackgroundPanel()
  434. borderColor := t.BackgroundPanel()
  435. defaultStyle := styles.NewStyle().Background(backgroundColor).Width(width - 6).Render
  436. baseStyle := styles.NewStyle().Background(backgroundColor).Foreground(t.Text()).Render
  437. mutedStyle := styles.NewStyle().Background(backgroundColor).Foreground(t.TextMuted()).Render
  438. permissionContent := ""
  439. if permission.ID != "" {
  440. borderColor = t.Warning()
  441. base := styles.NewStyle().Background(backgroundColor)
  442. text := base.Foreground(t.Text()).Bold(true).Render
  443. muted := base.Foreground(t.TextMuted()).Render
  444. permissionContent = "Permission required to run this tool:\n\n"
  445. permissionContent += text(
  446. "enter ",
  447. ) + muted(
  448. "accept ",
  449. ) + text(
  450. "a",
  451. ) + muted(
  452. " accept always ",
  453. ) + text(
  454. "esc",
  455. ) + muted(
  456. " reject",
  457. )
  458. }
  459. if permission.Metadata != nil {
  460. metadata, ok := toolCall.State.Metadata.(map[string]any)
  461. if metadata == nil || !ok {
  462. metadata = map[string]any{}
  463. }
  464. maps.Copy(metadata, permission.Metadata)
  465. toolCall.State.Metadata = metadata
  466. }
  467. if toolCall.State.Metadata != nil {
  468. metadata := toolCall.State.Metadata.(map[string]any)
  469. switch toolCall.Tool {
  470. case "read":
  471. var preview any
  472. if metadata != nil {
  473. preview = metadata["preview"]
  474. }
  475. if preview != nil && toolInputMap["filePath"] != nil {
  476. filename := toolInputMap["filePath"].(string)
  477. body = preview.(string)
  478. body = util.RenderFile(filename, body, width, util.WithTruncate(6))
  479. }
  480. case "edit":
  481. if filename, ok := toolInputMap["filePath"].(string); ok {
  482. var diffField any
  483. if metadata != nil {
  484. diffField = metadata["diff"]
  485. }
  486. if diffField != nil {
  487. patch := diffField.(string)
  488. var formattedDiff string
  489. if width < 120 {
  490. formattedDiff, _ = diff.FormatUnifiedDiff(
  491. filename,
  492. patch,
  493. diff.WithWidth(width-2),
  494. )
  495. } else {
  496. formattedDiff, _ = diff.FormatDiff(
  497. filename,
  498. patch,
  499. diff.WithWidth(width-2),
  500. )
  501. }
  502. body = strings.TrimSpace(formattedDiff)
  503. style := styles.NewStyle().
  504. Background(backgroundColor).
  505. Foreground(t.TextMuted()).
  506. Padding(1, 2).
  507. Width(width - 4)
  508. if diagnostics := renderDiagnostics(metadata, filename, backgroundColor, width-6); diagnostics != "" {
  509. diagnostics = style.Render(diagnostics)
  510. body += "\n" + diagnostics
  511. }
  512. title := renderToolTitle(toolCall, width)
  513. title = style.Render(title)
  514. content := title + "\n" + body
  515. if toolCall.State.Status == opencode.ToolPartStateStatusError {
  516. errorStyle := styles.NewStyle().
  517. Background(backgroundColor).
  518. Foreground(t.Error()).
  519. Padding(1, 2).
  520. Width(width - 4)
  521. errorContent := errorStyle.Render(toolCall.State.Error)
  522. content += "\n" + errorContent
  523. }
  524. if permissionContent != "" {
  525. permissionContent = styles.NewStyle().
  526. Background(backgroundColor).
  527. Padding(1, 2).
  528. Render(permissionContent)
  529. content += "\n" + permissionContent
  530. }
  531. content = renderContentBlock(
  532. app,
  533. content,
  534. width,
  535. WithPadding(0),
  536. WithBorderColor(borderColor),
  537. WithBorderBoth(permission.ID != ""),
  538. )
  539. return content
  540. }
  541. }
  542. case "write":
  543. if filename, ok := toolInputMap["filePath"].(string); ok {
  544. if content, ok := toolInputMap["content"].(string); ok {
  545. body = util.RenderFile(filename, content, width)
  546. if diagnostics := renderDiagnostics(metadata, filename, backgroundColor, width-4); diagnostics != "" {
  547. body += "\n\n" + diagnostics
  548. }
  549. }
  550. }
  551. case "bash":
  552. if command, ok := toolInputMap["command"].(string); ok {
  553. body = fmt.Sprintf("```console\n$ %s\n", command)
  554. output := metadata["output"]
  555. if output != nil {
  556. body += ansi.Strip(fmt.Sprintf("%s", output))
  557. }
  558. body += "```"
  559. body = util.ToMarkdown(body, width, backgroundColor)
  560. }
  561. case "webfetch":
  562. if format, ok := toolInputMap["format"].(string); ok && result != nil {
  563. body = *result
  564. body = util.TruncateHeight(body, 10)
  565. if format == "html" || format == "markdown" {
  566. body = util.ToMarkdown(body, width, backgroundColor)
  567. }
  568. }
  569. case "todowrite":
  570. todos := metadata["todos"]
  571. if todos != nil {
  572. for _, item := range todos.([]any) {
  573. todo := item.(map[string]any)
  574. content := todo["content"].(string)
  575. switch todo["status"] {
  576. case "completed":
  577. body += fmt.Sprintf("- [x] %s\n", content)
  578. case "cancelled":
  579. // strike through cancelled todo
  580. body += fmt.Sprintf("- [ ] ~~%s~~\n", content)
  581. case "in_progress":
  582. // highlight in progress todo
  583. body += fmt.Sprintf("- [ ] `%s`\n", content)
  584. default:
  585. body += fmt.Sprintf("- [ ] %s\n", content)
  586. }
  587. }
  588. body = util.ToMarkdown(body, width, backgroundColor)
  589. }
  590. case "task":
  591. summary := metadata["summary"]
  592. if summary != nil {
  593. toolcalls := summary.([]any)
  594. steps := []string{}
  595. for _, item := range toolcalls {
  596. data, _ := json.Marshal(item)
  597. var toolCall opencode.ToolPart
  598. _ = json.Unmarshal(data, &toolCall)
  599. step := renderToolTitle(toolCall, width-2)
  600. step = "∟ " + step
  601. steps = append(steps, step)
  602. }
  603. body = strings.Join(steps, "\n")
  604. body += "\n\n"
  605. body += baseStyle(app.Keybind(commands.SessionChildCycleCommand)) +
  606. mutedStyle(", ") +
  607. baseStyle(app.Keybind(commands.SessionChildCycleReverseCommand)) +
  608. mutedStyle(" navigate child sessions")
  609. }
  610. body = defaultStyle(body)
  611. default:
  612. if result == nil {
  613. empty := ""
  614. result = &empty
  615. }
  616. body = *result
  617. body = util.TruncateHeight(body, 10)
  618. body = defaultStyle(body)
  619. }
  620. }
  621. error := ""
  622. if toolCall.State.Status == opencode.ToolPartStateStatusError {
  623. error = toolCall.State.Error
  624. }
  625. if error != "" {
  626. errorContent := styles.NewStyle().
  627. Width(width - 6).
  628. Foreground(t.Error()).
  629. Background(backgroundColor).
  630. Render(error)
  631. if body == "" {
  632. body = errorContent
  633. } else {
  634. body += "\n\n" + errorContent
  635. }
  636. }
  637. if body == "" && error == "" && result != nil {
  638. body = *result
  639. body = util.TruncateHeight(body, 10)
  640. body = defaultStyle(body)
  641. }
  642. if body == "" {
  643. body = defaultStyle("")
  644. }
  645. title := renderToolTitle(toolCall, width)
  646. content := title + "\n\n" + body
  647. if permissionContent != "" {
  648. content += "\n\n\n" + permissionContent
  649. }
  650. return renderContentBlock(
  651. app,
  652. content,
  653. width,
  654. WithBorderColor(borderColor),
  655. WithBorderBoth(permission.ID != ""),
  656. )
  657. }
  658. func renderToolName(name string) string {
  659. switch name {
  660. case "bash":
  661. return "Shell"
  662. case "webfetch":
  663. return "Fetch"
  664. case "invalid":
  665. return "Invalid"
  666. default:
  667. normalizedName := name
  668. if after, ok := strings.CutPrefix(name, "opencode_"); ok {
  669. normalizedName = after
  670. }
  671. return cases.Title(language.Und).String(normalizedName)
  672. }
  673. }
  674. func getTodoPhase(metadata map[string]any) string {
  675. todos, ok := metadata["todos"].([]any)
  676. if !ok || len(todos) == 0 {
  677. return "Plan"
  678. }
  679. counts := map[string]int{"pending": 0, "completed": 0}
  680. for _, item := range todos {
  681. if todo, ok := item.(map[string]any); ok {
  682. if status, ok := todo["status"].(string); ok {
  683. counts[status]++
  684. }
  685. }
  686. }
  687. total := len(todos)
  688. switch {
  689. case counts["pending"] == total:
  690. return "Creating plan"
  691. case counts["completed"] == total:
  692. return "Completing plan"
  693. default:
  694. return "Updating plan"
  695. }
  696. }
  697. func getTodoTitle(toolCall opencode.ToolPart) string {
  698. if toolCall.State.Status == opencode.ToolPartStateStatusCompleted {
  699. if metadata, ok := toolCall.State.Metadata.(map[string]any); ok {
  700. return getTodoPhase(metadata)
  701. }
  702. }
  703. return "Plan"
  704. }
  705. func renderToolTitle(
  706. toolCall opencode.ToolPart,
  707. width int,
  708. ) string {
  709. if toolCall.State.Status == opencode.ToolPartStateStatusPending {
  710. title := renderToolAction(toolCall.Tool)
  711. t := theme.CurrentTheme()
  712. shiny := util.Shimmer(title, t.BackgroundPanel(), t.TextMuted(), t.Accent())
  713. return styles.NewStyle().Background(t.BackgroundPanel()).Width(width - 6).Render(shiny)
  714. }
  715. toolArgs := ""
  716. toolArgsMap := make(map[string]any)
  717. if toolCall.State.Input != nil {
  718. value := toolCall.State.Input
  719. if m, ok := value.(map[string]any); ok {
  720. toolArgsMap = m
  721. keys := make([]string, 0, len(toolArgsMap))
  722. for key := range toolArgsMap {
  723. keys = append(keys, key)
  724. }
  725. slices.Sort(keys)
  726. firstKey := ""
  727. if len(keys) > 0 {
  728. firstKey = keys[0]
  729. }
  730. toolArgs = renderArgs(&toolArgsMap, firstKey)
  731. }
  732. }
  733. title := renderToolName(toolCall.Tool)
  734. switch toolCall.Tool {
  735. case "read":
  736. toolArgs = renderArgs(&toolArgsMap, "filePath")
  737. title = fmt.Sprintf("%s %s", title, toolArgs)
  738. case "edit", "write":
  739. if filename, ok := toolArgsMap["filePath"].(string); ok {
  740. title = fmt.Sprintf("%s %s", title, util.Relative(filename))
  741. }
  742. case "bash":
  743. if description, ok := toolArgsMap["description"].(string); ok {
  744. title = fmt.Sprintf("%s %s", title, description)
  745. }
  746. case "task":
  747. description := toolArgsMap["description"]
  748. subagent := toolArgsMap["subagent_type"]
  749. if description != nil && subagent != nil {
  750. title = fmt.Sprintf("%s[%s] %s", title, subagent, description)
  751. } else if description != nil {
  752. title = fmt.Sprintf("%s %s", title, description)
  753. }
  754. case "webfetch":
  755. toolArgs = renderArgs(&toolArgsMap, "url")
  756. title = fmt.Sprintf("%s %s", title, toolArgs)
  757. case "todowrite":
  758. title = getTodoTitle(toolCall)
  759. case "todoread":
  760. return "Plan"
  761. case "invalid":
  762. if actualTool, ok := toolArgsMap["tool"].(string); ok {
  763. title = renderToolName(actualTool)
  764. }
  765. default:
  766. toolName := renderToolName(toolCall.Tool)
  767. title = fmt.Sprintf("%s %s", toolName, toolArgs)
  768. }
  769. title = truncate.StringWithTail(title, uint(width-6), "...")
  770. if toolCall.State.Error != "" {
  771. t := theme.CurrentTheme()
  772. title = styles.NewStyle().Foreground(t.Error()).Render(title)
  773. }
  774. return title
  775. }
  776. func renderToolAction(name string) string {
  777. switch name {
  778. case "task":
  779. return "Delegating..."
  780. case "bash":
  781. return "Writing command..."
  782. case "edit":
  783. return "Preparing edit..."
  784. case "webfetch":
  785. return "Fetching from the web..."
  786. case "glob":
  787. return "Finding files..."
  788. case "grep":
  789. return "Searching content..."
  790. case "list":
  791. return "Listing directory..."
  792. case "read":
  793. return "Reading file..."
  794. case "write":
  795. return "Preparing write..."
  796. case "todowrite", "todoread":
  797. return "Planning..."
  798. case "patch":
  799. return "Preparing patch..."
  800. }
  801. return "Working..."
  802. }
  803. func renderArgs(args *map[string]any, titleKey string) string {
  804. if args == nil || len(*args) == 0 {
  805. return ""
  806. }
  807. keys := make([]string, 0, len(*args))
  808. for key := range *args {
  809. keys = append(keys, key)
  810. }
  811. slices.Sort(keys)
  812. title := ""
  813. parts := []string{}
  814. for _, key := range keys {
  815. value := (*args)[key]
  816. if value == nil {
  817. continue
  818. }
  819. if key == "filePath" || key == "path" {
  820. if strValue, ok := value.(string); ok {
  821. value = util.Relative(strValue)
  822. }
  823. }
  824. if key == titleKey {
  825. title = fmt.Sprintf("%s", value)
  826. continue
  827. }
  828. parts = append(parts, fmt.Sprintf("%s=%v", key, value))
  829. }
  830. if len(parts) == 0 {
  831. return title
  832. }
  833. return fmt.Sprintf("%s (%s)", title, strings.Join(parts, ", "))
  834. }
  835. // Diagnostic represents an LSP diagnostic
  836. type Diagnostic struct {
  837. Range struct {
  838. Start struct {
  839. Line int `json:"line"`
  840. Character int `json:"character"`
  841. } `json:"start"`
  842. } `json:"range"`
  843. Severity int `json:"severity"`
  844. Message string `json:"message"`
  845. }
  846. // renderDiagnostics formats LSP diagnostics for display in the TUI
  847. func renderDiagnostics(
  848. metadata map[string]any,
  849. filePath string,
  850. backgroundColor compat.AdaptiveColor,
  851. width int,
  852. ) string {
  853. if diagnosticsData, ok := metadata["diagnostics"].(map[string]any); ok {
  854. if fileDiagnostics, ok := diagnosticsData[filePath].([]any); ok {
  855. var errorDiagnostics []string
  856. for _, diagInterface := range fileDiagnostics {
  857. diagMap, ok := diagInterface.(map[string]any)
  858. if !ok {
  859. continue
  860. }
  861. // Parse the diagnostic
  862. var diag Diagnostic
  863. diagBytes, err := json.Marshal(diagMap)
  864. if err != nil {
  865. continue
  866. }
  867. if err := json.Unmarshal(diagBytes, &diag); err != nil {
  868. continue
  869. }
  870. // Only show error diagnostics (severity === 1)
  871. if diag.Severity != 1 {
  872. continue
  873. }
  874. line := diag.Range.Start.Line + 1 // 1-based
  875. column := diag.Range.Start.Character + 1 // 1-based
  876. errorDiagnostics = append(
  877. errorDiagnostics,
  878. fmt.Sprintf("Error [%d:%d] %s", line, column, diag.Message),
  879. )
  880. }
  881. if len(errorDiagnostics) == 0 {
  882. return ""
  883. }
  884. t := theme.CurrentTheme()
  885. var result strings.Builder
  886. for _, diagnostic := range errorDiagnostics {
  887. if result.Len() > 0 {
  888. result.WriteString("\n\n")
  889. }
  890. diagnostic = ansi.WordwrapWc(diagnostic, width, " -")
  891. result.WriteString(
  892. styles.NewStyle().
  893. Background(backgroundColor).
  894. Foreground(t.Error()).
  895. Render(diagnostic),
  896. )
  897. }
  898. return result.String()
  899. }
  900. }
  901. return ""
  902. // diagnosticsData should be a map[string][]Diagnostic
  903. // strDiagnosticsData := diagnosticsData.Raw()
  904. // diagnosticsMap := gjson.Parse(strDiagnosticsData).Value().(map[string]any)
  905. // fileDiagnostics, ok := diagnosticsMap[filePath]
  906. // if !ok {
  907. // return ""
  908. // }
  909. // diagnosticsList, ok := fileDiagnostics.([]any)
  910. // if !ok {
  911. // return ""
  912. // }
  913. }