message.go 23 KB

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