message.go 24 KB

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