message.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  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. wrappedText := ansi.WordwrapWc(styledText, width-6, " -")
  288. content = base.Width(width - 6).Render(wrappedText)
  289. }
  290. timestamp := ts.
  291. Local().
  292. Format("02 Jan 2006 03:04 PM")
  293. if time.Now().Format("02 Jan 2006") == timestamp[:11] {
  294. timestamp = timestamp[12:]
  295. }
  296. timestamp = styles.NewStyle().
  297. Background(backgroundColor).
  298. Foreground(t.TextMuted()).
  299. Render(" (" + timestamp + ")")
  300. // Check if this is an assistant message with agent information
  301. var modelAndAgentSuffix string
  302. if assistantMsg, ok := message.(opencode.AssistantMessage); ok && assistantMsg.Mode != "" {
  303. // Find the agent index by name to get the correct color
  304. var agentIndex int
  305. for i, agent := range app.Agents {
  306. if agent.Name == assistantMsg.Mode {
  307. agentIndex = i
  308. break
  309. }
  310. }
  311. // Get agent color based on the original agent index (same as status bar)
  312. agentColor := util.GetAgentColor(agentIndex)
  313. // Style the agent name with the same color as status bar
  314. agentName := cases.Title(language.Und).String(assistantMsg.Mode)
  315. styledAgentName := styles.NewStyle().
  316. Background(backgroundColor).
  317. Foreground(agentColor).
  318. Render(agentName + " ")
  319. styledModelID := styles.NewStyle().
  320. Background(backgroundColor).
  321. Foreground(t.TextMuted()).
  322. Render(assistantMsg.ModelID)
  323. modelAndAgentSuffix = styledAgentName + styledModelID
  324. }
  325. var info string
  326. if modelAndAgentSuffix != "" {
  327. info = modelAndAgentSuffix + timestamp
  328. } else {
  329. info = author + timestamp
  330. }
  331. if !showToolDetails && toolCalls != nil && len(toolCalls) > 0 {
  332. content = content + "\n"
  333. for _, toolCall := range toolCalls {
  334. title := renderToolTitle(toolCall, width-2)
  335. style := styles.NewStyle()
  336. if toolCall.State.Status == opencode.ToolPartStateStatusError {
  337. style = style.Foreground(t.Error())
  338. }
  339. title = style.Render(title)
  340. title = "\n∟ " + title
  341. content = content + title
  342. }
  343. }
  344. sections := []string{content}
  345. if extra != "" {
  346. sections = append(sections, "\n"+extra)
  347. }
  348. sections = append(sections, "\n"+info)
  349. content = strings.Join(sections, "\n")
  350. switch message.(type) {
  351. case opencode.UserMessage:
  352. return renderContentBlock(
  353. app,
  354. content,
  355. width,
  356. WithTextColor(t.Text()),
  357. WithBorderColor(t.Secondary()),
  358. )
  359. case opencode.AssistantMessage:
  360. if isThinking {
  361. return renderContentBlock(
  362. app,
  363. content,
  364. width,
  365. WithTextColor(t.Text()),
  366. WithBackgroundColor(t.BackgroundPanel()),
  367. WithBorderColor(t.BackgroundPanel()),
  368. )
  369. }
  370. return renderContentBlock(
  371. app,
  372. content,
  373. width,
  374. WithNoBorder(),
  375. WithBackgroundColor(t.Background()),
  376. )
  377. }
  378. return ""
  379. }
  380. func renderToolDetails(
  381. app *app.App,
  382. toolCall opencode.ToolPart,
  383. permission opencode.Permission,
  384. width int,
  385. ) string {
  386. measure := util.Measure("chat.renderToolDetails")
  387. defer measure("tool", toolCall.Tool)
  388. ignoredTools := []string{"todoread"}
  389. if slices.Contains(ignoredTools, toolCall.Tool) {
  390. return ""
  391. }
  392. if toolCall.State.Status == opencode.ToolPartStateStatusPending {
  393. title := renderToolTitle(toolCall, width)
  394. return renderContentBlock(app, title, width)
  395. }
  396. var result *string
  397. if toolCall.State.Output != "" {
  398. result = &toolCall.State.Output
  399. }
  400. toolInputMap := make(map[string]any)
  401. if toolCall.State.Input != nil {
  402. value := toolCall.State.Input
  403. if m, ok := value.(map[string]any); ok {
  404. toolInputMap = m
  405. keys := make([]string, 0, len(toolInputMap))
  406. for key := range toolInputMap {
  407. keys = append(keys, key)
  408. }
  409. slices.Sort(keys)
  410. }
  411. }
  412. body := ""
  413. t := theme.CurrentTheme()
  414. backgroundColor := t.BackgroundPanel()
  415. borderColor := t.BackgroundPanel()
  416. defaultStyle := styles.NewStyle().Background(backgroundColor).Width(width - 6).Render
  417. permissionContent := ""
  418. if permission.ID != "" {
  419. borderColor = t.Warning()
  420. base := styles.NewStyle().Background(backgroundColor)
  421. text := base.Foreground(t.Text()).Bold(true).Render
  422. muted := base.Foreground(t.TextMuted()).Render
  423. permissionContent = "Permission required to run this tool:\n\n"
  424. permissionContent += text(
  425. "enter ",
  426. ) + muted(
  427. "accept ",
  428. ) + text(
  429. "a",
  430. ) + muted(
  431. " accept always ",
  432. ) + text(
  433. "esc",
  434. ) + muted(
  435. " reject",
  436. )
  437. }
  438. if permission.Metadata != nil {
  439. metadata, ok := toolCall.State.Metadata.(map[string]any)
  440. if metadata == nil || !ok {
  441. metadata = map[string]any{}
  442. }
  443. maps.Copy(metadata, permission.Metadata)
  444. toolCall.State.Metadata = metadata
  445. }
  446. if toolCall.State.Metadata != nil {
  447. metadata := toolCall.State.Metadata.(map[string]any)
  448. switch toolCall.Tool {
  449. case "read":
  450. var preview any
  451. if metadata != nil {
  452. preview = metadata["preview"]
  453. }
  454. if preview != nil && toolInputMap["filePath"] != nil {
  455. filename := toolInputMap["filePath"].(string)
  456. body = preview.(string)
  457. body = util.RenderFile(filename, body, width, util.WithTruncate(6))
  458. }
  459. case "edit":
  460. if filename, ok := toolInputMap["filePath"].(string); ok {
  461. var diffField any
  462. if metadata != nil {
  463. diffField = metadata["diff"]
  464. }
  465. if diffField != nil {
  466. patch := diffField.(string)
  467. var formattedDiff string
  468. if width < 120 {
  469. formattedDiff, _ = diff.FormatUnifiedDiff(
  470. filename,
  471. patch,
  472. diff.WithWidth(width-2),
  473. )
  474. } else {
  475. formattedDiff, _ = diff.FormatDiff(
  476. filename,
  477. patch,
  478. diff.WithWidth(width-2),
  479. )
  480. }
  481. body = strings.TrimSpace(formattedDiff)
  482. style := styles.NewStyle().
  483. Background(backgroundColor).
  484. Foreground(t.TextMuted()).
  485. Padding(1, 2).
  486. Width(width - 4)
  487. if diagnostics := renderDiagnostics(metadata, filename, backgroundColor, width-6); diagnostics != "" {
  488. diagnostics = style.Render(diagnostics)
  489. body += "\n" + diagnostics
  490. }
  491. title := renderToolTitle(toolCall, width)
  492. title = style.Render(title)
  493. content := title + "\n" + body
  494. if permissionContent != "" {
  495. permissionContent = styles.NewStyle().
  496. Background(backgroundColor).
  497. Padding(1, 2).
  498. Render(permissionContent)
  499. content += "\n" + permissionContent
  500. }
  501. content = renderContentBlock(
  502. app,
  503. content,
  504. width,
  505. WithPadding(0),
  506. WithBorderColor(borderColor),
  507. WithBorderBoth(permission.ID != ""),
  508. )
  509. return content
  510. }
  511. }
  512. case "write":
  513. if filename, ok := toolInputMap["filePath"].(string); ok {
  514. if content, ok := toolInputMap["content"].(string); ok {
  515. body = util.RenderFile(filename, content, width)
  516. if diagnostics := renderDiagnostics(metadata, filename, backgroundColor, width-4); diagnostics != "" {
  517. body += "\n\n" + diagnostics
  518. }
  519. }
  520. }
  521. case "bash":
  522. command := toolInputMap["command"].(string)
  523. body = fmt.Sprintf("```console\n$ %s\n", command)
  524. output := metadata["output"]
  525. if output != nil {
  526. body += ansi.Strip(fmt.Sprintf("%s", output))
  527. }
  528. body += "```"
  529. body = util.ToMarkdown(body, width, backgroundColor)
  530. case "webfetch":
  531. if format, ok := toolInputMap["format"].(string); ok && result != nil {
  532. body = *result
  533. body = util.TruncateHeight(body, 10)
  534. if format == "html" || format == "markdown" {
  535. body = util.ToMarkdown(body, width, backgroundColor)
  536. }
  537. }
  538. case "todowrite":
  539. todos := metadata["todos"]
  540. if todos != nil {
  541. for _, item := range todos.([]any) {
  542. todo := item.(map[string]any)
  543. content := todo["content"].(string)
  544. switch todo["status"] {
  545. case "completed":
  546. body += fmt.Sprintf("- [x] %s\n", content)
  547. case "cancelled":
  548. // strike through cancelled todo
  549. body += fmt.Sprintf("- [ ] ~~%s~~\n", content)
  550. case "in_progress":
  551. // highlight in progress todo
  552. body += fmt.Sprintf("- [ ] `%s`\n", content)
  553. default:
  554. body += fmt.Sprintf("- [ ] %s\n", content)
  555. }
  556. }
  557. body = util.ToMarkdown(body, width, backgroundColor)
  558. }
  559. case "task":
  560. summary := metadata["summary"]
  561. if summary != nil {
  562. toolcalls := summary.([]any)
  563. steps := []string{}
  564. for _, item := range toolcalls {
  565. data, _ := json.Marshal(item)
  566. var toolCall opencode.ToolPart
  567. _ = json.Unmarshal(data, &toolCall)
  568. step := renderToolTitle(toolCall, width-2)
  569. step = "∟ " + step
  570. steps = append(steps, step)
  571. }
  572. body = strings.Join(steps, "\n")
  573. }
  574. body = defaultStyle(body)
  575. default:
  576. if result == nil {
  577. empty := ""
  578. result = &empty
  579. }
  580. body = *result
  581. body = util.TruncateHeight(body, 10)
  582. body = defaultStyle(body)
  583. }
  584. }
  585. error := ""
  586. if toolCall.State.Status == opencode.ToolPartStateStatusError {
  587. error = toolCall.State.Error
  588. }
  589. if error != "" {
  590. body = styles.NewStyle().
  591. Width(width - 6).
  592. Foreground(t.Error()).
  593. Background(backgroundColor).
  594. Render(error)
  595. }
  596. if body == "" && error == "" && result != nil {
  597. body = *result
  598. body = util.TruncateHeight(body, 10)
  599. body = defaultStyle(body)
  600. }
  601. if body == "" {
  602. body = defaultStyle("")
  603. }
  604. title := renderToolTitle(toolCall, width)
  605. content := title + "\n\n" + body
  606. if permissionContent != "" {
  607. content += "\n\n\n" + permissionContent
  608. }
  609. return renderContentBlock(
  610. app,
  611. content,
  612. width,
  613. WithBorderColor(borderColor),
  614. WithBorderBoth(permission.ID != ""),
  615. )
  616. }
  617. func renderToolName(name string) string {
  618. switch name {
  619. case "webfetch":
  620. return "Fetch"
  621. case "invalid":
  622. return "Invalid"
  623. default:
  624. normalizedName := name
  625. if after, ok := strings.CutPrefix(name, "opencode_"); ok {
  626. normalizedName = after
  627. }
  628. return cases.Title(language.Und).String(normalizedName)
  629. }
  630. }
  631. func getTodoPhase(metadata map[string]any) string {
  632. todos, ok := metadata["todos"].([]any)
  633. if !ok || len(todos) == 0 {
  634. return "Plan"
  635. }
  636. counts := map[string]int{"pending": 0, "completed": 0}
  637. for _, item := range todos {
  638. if todo, ok := item.(map[string]any); ok {
  639. if status, ok := todo["status"].(string); ok {
  640. counts[status]++
  641. }
  642. }
  643. }
  644. total := len(todos)
  645. switch {
  646. case counts["pending"] == total:
  647. return "Creating plan"
  648. case counts["completed"] == total:
  649. return "Completing plan"
  650. default:
  651. return "Updating plan"
  652. }
  653. }
  654. func getTodoTitle(toolCall opencode.ToolPart) string {
  655. if toolCall.State.Status == opencode.ToolPartStateStatusCompleted {
  656. if metadata, ok := toolCall.State.Metadata.(map[string]any); ok {
  657. return getTodoPhase(metadata)
  658. }
  659. }
  660. return "Plan"
  661. }
  662. func renderToolTitle(
  663. toolCall opencode.ToolPart,
  664. width int,
  665. ) string {
  666. if toolCall.State.Status == opencode.ToolPartStateStatusPending {
  667. title := renderToolAction(toolCall.Tool)
  668. return styles.NewStyle().Width(width - 6).Render(title)
  669. }
  670. toolArgs := ""
  671. toolArgsMap := make(map[string]any)
  672. if toolCall.State.Input != nil {
  673. value := toolCall.State.Input
  674. if m, ok := value.(map[string]any); ok {
  675. toolArgsMap = m
  676. keys := make([]string, 0, len(toolArgsMap))
  677. for key := range toolArgsMap {
  678. keys = append(keys, key)
  679. }
  680. slices.Sort(keys)
  681. firstKey := ""
  682. if len(keys) > 0 {
  683. firstKey = keys[0]
  684. }
  685. toolArgs = renderArgs(&toolArgsMap, firstKey)
  686. }
  687. }
  688. title := renderToolName(toolCall.Tool)
  689. switch toolCall.Tool {
  690. case "read":
  691. toolArgs = renderArgs(&toolArgsMap, "filePath")
  692. title = fmt.Sprintf("%s %s", title, toolArgs)
  693. case "edit", "write":
  694. if filename, ok := toolArgsMap["filePath"].(string); ok {
  695. title = fmt.Sprintf("%s %s", title, util.Relative(filename))
  696. }
  697. case "bash":
  698. if description, ok := toolArgsMap["description"].(string); ok {
  699. title = fmt.Sprintf("%s %s", title, description)
  700. }
  701. case "task":
  702. description := toolArgsMap["description"]
  703. subagent := toolArgsMap["subagent_type"]
  704. if description != nil && subagent != nil {
  705. title = fmt.Sprintf("%s[%s] %s", title, subagent, description)
  706. } else if description != nil {
  707. title = fmt.Sprintf("%s %s", title, description)
  708. }
  709. case "webfetch":
  710. toolArgs = renderArgs(&toolArgsMap, "url")
  711. title = fmt.Sprintf("%s %s", title, toolArgs)
  712. case "todowrite":
  713. title = getTodoTitle(toolCall)
  714. case "todoread":
  715. return "Plan"
  716. case "invalid":
  717. if actualTool, ok := toolArgsMap["tool"].(string); ok {
  718. title = renderToolName(actualTool)
  719. }
  720. default:
  721. toolName := renderToolName(toolCall.Tool)
  722. title = fmt.Sprintf("%s %s", toolName, toolArgs)
  723. }
  724. title = truncate.StringWithTail(title, uint(width-6), "...")
  725. if toolCall.State.Error != "" {
  726. t := theme.CurrentTheme()
  727. title = styles.NewStyle().Foreground(t.Error()).Render(title)
  728. }
  729. return title
  730. }
  731. func renderToolAction(name string) string {
  732. switch name {
  733. case "task":
  734. return "Delegating..."
  735. case "bash":
  736. return "Writing command..."
  737. case "edit":
  738. return "Preparing edit..."
  739. case "webfetch":
  740. return "Fetching from the web..."
  741. case "glob":
  742. return "Finding files..."
  743. case "grep":
  744. return "Searching content..."
  745. case "list":
  746. return "Listing directory..."
  747. case "read":
  748. return "Reading file..."
  749. case "write":
  750. return "Preparing write..."
  751. case "todowrite", "todoread":
  752. return "Planning..."
  753. case "patch":
  754. return "Preparing patch..."
  755. }
  756. return "Working..."
  757. }
  758. func renderArgs(args *map[string]any, titleKey string) string {
  759. if args == nil || len(*args) == 0 {
  760. return ""
  761. }
  762. keys := make([]string, 0, len(*args))
  763. for key := range *args {
  764. keys = append(keys, key)
  765. }
  766. slices.Sort(keys)
  767. title := ""
  768. parts := []string{}
  769. for _, key := range keys {
  770. value := (*args)[key]
  771. if value == nil {
  772. continue
  773. }
  774. if key == "filePath" || key == "path" {
  775. value = util.Relative(value.(string))
  776. }
  777. if key == titleKey {
  778. title = fmt.Sprintf("%s", value)
  779. continue
  780. }
  781. parts = append(parts, fmt.Sprintf("%s=%v", key, value))
  782. }
  783. if len(parts) == 0 {
  784. return title
  785. }
  786. return fmt.Sprintf("%s (%s)", title, strings.Join(parts, ", "))
  787. }
  788. // Diagnostic represents an LSP diagnostic
  789. type Diagnostic struct {
  790. Range struct {
  791. Start struct {
  792. Line int `json:"line"`
  793. Character int `json:"character"`
  794. } `json:"start"`
  795. } `json:"range"`
  796. Severity int `json:"severity"`
  797. Message string `json:"message"`
  798. }
  799. // renderDiagnostics formats LSP diagnostics for display in the TUI
  800. func renderDiagnostics(
  801. metadata map[string]any,
  802. filePath string,
  803. backgroundColor compat.AdaptiveColor,
  804. width int,
  805. ) string {
  806. if diagnosticsData, ok := metadata["diagnostics"].(map[string]any); ok {
  807. if fileDiagnostics, ok := diagnosticsData[filePath].([]any); ok {
  808. var errorDiagnostics []string
  809. for _, diagInterface := range fileDiagnostics {
  810. diagMap, ok := diagInterface.(map[string]any)
  811. if !ok {
  812. continue
  813. }
  814. // Parse the diagnostic
  815. var diag Diagnostic
  816. diagBytes, err := json.Marshal(diagMap)
  817. if err != nil {
  818. continue
  819. }
  820. if err := json.Unmarshal(diagBytes, &diag); err != nil {
  821. continue
  822. }
  823. // Only show error diagnostics (severity === 1)
  824. if diag.Severity != 1 {
  825. continue
  826. }
  827. line := diag.Range.Start.Line + 1 // 1-based
  828. column := diag.Range.Start.Character + 1 // 1-based
  829. errorDiagnostics = append(
  830. errorDiagnostics,
  831. fmt.Sprintf("Error [%d:%d] %s", line, column, diag.Message),
  832. )
  833. }
  834. if len(errorDiagnostics) == 0 {
  835. return ""
  836. }
  837. t := theme.CurrentTheme()
  838. var result strings.Builder
  839. for _, diagnostic := range errorDiagnostics {
  840. if result.Len() > 0 {
  841. result.WriteString("\n\n")
  842. }
  843. diagnostic = ansi.WordwrapWc(diagnostic, width, " -")
  844. result.WriteString(
  845. styles.NewStyle().
  846. Background(backgroundColor).
  847. Foreground(t.Error()).
  848. Render(diagnostic),
  849. )
  850. }
  851. return result.String()
  852. }
  853. }
  854. return ""
  855. // diagnosticsData should be a map[string][]Diagnostic
  856. // strDiagnosticsData := diagnosticsData.Raw()
  857. // diagnosticsMap := gjson.Parse(strDiagnosticsData).Value().(map[string]any)
  858. // fileDiagnostics, ok := diagnosticsMap[filePath]
  859. // if !ok {
  860. // return ""
  861. // }
  862. // diagnosticsList, ok := fileDiagnostics.([]any)
  863. // if !ok {
  864. // return ""
  865. // }
  866. }