message.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782
  1. package chat
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "path/filepath"
  6. "slices"
  7. "strings"
  8. "time"
  9. "unicode"
  10. "github.com/charmbracelet/lipgloss/v2"
  11. "github.com/charmbracelet/lipgloss/v2/compat"
  12. "github.com/charmbracelet/x/ansi"
  13. "github.com/sst/opencode/internal/app"
  14. "github.com/sst/opencode/internal/components/diff"
  15. "github.com/sst/opencode/internal/layout"
  16. "github.com/sst/opencode/internal/styles"
  17. "github.com/sst/opencode/internal/theme"
  18. "github.com/sst/opencode/pkg/client"
  19. "golang.org/x/text/cases"
  20. "golang.org/x/text/language"
  21. )
  22. func toMarkdown(content string, width int, backgroundColor compat.AdaptiveColor) string {
  23. r := styles.GetMarkdownRenderer(width, backgroundColor)
  24. content = strings.ReplaceAll(content, app.RootPath+"/", "")
  25. rendered, _ := r.Render(content)
  26. lines := strings.Split(rendered, "\n")
  27. if len(lines) > 0 {
  28. firstLine := lines[0]
  29. cleaned := ansi.Strip(firstLine)
  30. nospace := strings.ReplaceAll(cleaned, " ", "")
  31. if nospace == "" {
  32. lines = lines[1:]
  33. }
  34. if len(lines) > 0 {
  35. lastLine := lines[len(lines)-1]
  36. cleaned = ansi.Strip(lastLine)
  37. nospace = strings.ReplaceAll(cleaned, " ", "")
  38. if nospace == "" {
  39. lines = lines[:len(lines)-1]
  40. }
  41. }
  42. }
  43. content = strings.Join(lines, "\n")
  44. return strings.TrimSuffix(content, "\n")
  45. }
  46. type blockRenderer struct {
  47. align *lipgloss.Position
  48. borderColor *compat.AdaptiveColor
  49. fullWidth bool
  50. paddingTop int
  51. paddingBottom int
  52. paddingLeft int
  53. paddingRight int
  54. marginTop int
  55. marginBottom int
  56. }
  57. type renderingOption func(*blockRenderer)
  58. func WithFullWidth() renderingOption {
  59. return func(c *blockRenderer) {
  60. c.fullWidth = true
  61. }
  62. }
  63. func WithAlign(align lipgloss.Position) renderingOption {
  64. return func(c *blockRenderer) {
  65. c.align = &align
  66. }
  67. }
  68. func WithBorderColor(color compat.AdaptiveColor) renderingOption {
  69. return func(c *blockRenderer) {
  70. c.borderColor = &color
  71. }
  72. }
  73. func WithMarginTop(padding int) renderingOption {
  74. return func(c *blockRenderer) {
  75. c.marginTop = padding
  76. }
  77. }
  78. func WithMarginBottom(padding int) renderingOption {
  79. return func(c *blockRenderer) {
  80. c.marginBottom = padding
  81. }
  82. }
  83. func WithPaddingLeft(padding int) renderingOption {
  84. return func(c *blockRenderer) {
  85. c.paddingLeft = padding
  86. }
  87. }
  88. func WithPaddingRight(padding int) renderingOption {
  89. return func(c *blockRenderer) {
  90. c.paddingRight = padding
  91. }
  92. }
  93. func WithPaddingTop(padding int) renderingOption {
  94. return func(c *blockRenderer) {
  95. c.paddingTop = padding
  96. }
  97. }
  98. func WithPaddingBottom(padding int) renderingOption {
  99. return func(c *blockRenderer) {
  100. c.paddingBottom = padding
  101. }
  102. }
  103. func renderContentBlock(content string, options ...renderingOption) string {
  104. t := theme.CurrentTheme()
  105. renderer := &blockRenderer{
  106. fullWidth: false,
  107. paddingTop: 1,
  108. paddingBottom: 1,
  109. paddingLeft: 2,
  110. paddingRight: 2,
  111. }
  112. for _, option := range options {
  113. option(renderer)
  114. }
  115. style := styles.NewStyle().Foreground(t.TextMuted()).Background(t.BackgroundPanel()).
  116. // MarginTop(renderer.marginTop).
  117. // MarginBottom(renderer.marginBottom).
  118. PaddingTop(renderer.paddingTop).
  119. PaddingBottom(renderer.paddingBottom).
  120. PaddingLeft(renderer.paddingLeft).
  121. PaddingRight(renderer.paddingRight).
  122. BorderStyle(lipgloss.ThickBorder())
  123. align := lipgloss.Left
  124. if renderer.align != nil {
  125. align = *renderer.align
  126. }
  127. borderColor := t.BackgroundPanel()
  128. if renderer.borderColor != nil {
  129. borderColor = *renderer.borderColor
  130. }
  131. switch align {
  132. case lipgloss.Left:
  133. style = style.
  134. BorderLeft(true).
  135. BorderRight(true).
  136. AlignHorizontal(align).
  137. BorderLeftForeground(borderColor).
  138. BorderLeftBackground(t.Background()).
  139. BorderRightForeground(t.BackgroundPanel()).
  140. BorderRightBackground(t.Background())
  141. case lipgloss.Right:
  142. style = style.
  143. BorderRight(true).
  144. BorderLeft(true).
  145. AlignHorizontal(align).
  146. BorderRightForeground(borderColor).
  147. BorderRightBackground(t.Background()).
  148. BorderLeftForeground(t.BackgroundPanel()).
  149. BorderLeftBackground(t.Background())
  150. }
  151. if renderer.fullWidth {
  152. style = style.Width(layout.Current.Container.Width)
  153. }
  154. content = style.Render(content)
  155. content = lipgloss.PlaceHorizontal(
  156. layout.Current.Container.Width,
  157. align,
  158. content,
  159. styles.WhitespaceStyle(t.Background()),
  160. )
  161. content = lipgloss.PlaceHorizontal(
  162. layout.Current.Viewport.Width,
  163. lipgloss.Center,
  164. content,
  165. styles.WhitespaceStyle(t.Background()),
  166. )
  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 calculatePadding() int {
  180. if layout.Current.Viewport.Width < 80 {
  181. return 5
  182. } else if layout.Current.Viewport.Width < 120 {
  183. return 15
  184. } else {
  185. return 20
  186. }
  187. }
  188. func renderText(message client.MessageInfo, text string, author string) string {
  189. t := theme.CurrentTheme()
  190. width := layout.Current.Container.Width
  191. padding := calculatePadding()
  192. timestamp := time.UnixMilli(int64(message.Metadata.Time.Created)).Local().Format("02 Jan 2006 03:04 PM")
  193. if time.Now().Format("02 Jan 2006") == timestamp[:11] {
  194. // don't show the date if it's today
  195. timestamp = timestamp[12:]
  196. }
  197. info := fmt.Sprintf("%s (%s)", author, timestamp)
  198. textWidth := max(lipgloss.Width(text), lipgloss.Width(info))
  199. markdownWidth := min(textWidth, width-padding-4) // -4 for the border and padding
  200. if message.Role == client.Assistant {
  201. markdownWidth = width - padding - 4 - 3
  202. }
  203. minWidth := max(markdownWidth, (width-4)/2)
  204. messageStyle := styles.NewStyle().
  205. Width(minWidth).
  206. Background(t.BackgroundPanel()).
  207. Foreground(t.Text())
  208. if textWidth < minWidth {
  209. messageStyle = messageStyle.AlignHorizontal(lipgloss.Right)
  210. }
  211. content := messageStyle.Render(text)
  212. if message.Role == client.Assistant {
  213. content = toMarkdown(text, markdownWidth, t.BackgroundPanel())
  214. }
  215. content = strings.Join([]string{content, info}, "\n")
  216. switch message.Role {
  217. case client.User:
  218. return renderContentBlock(content,
  219. WithAlign(lipgloss.Right),
  220. WithBorderColor(t.Secondary()),
  221. )
  222. case client.Assistant:
  223. return renderContentBlock(content,
  224. WithAlign(lipgloss.Left),
  225. WithBorderColor(t.Accent()),
  226. )
  227. }
  228. return ""
  229. }
  230. func renderToolInvocation(
  231. toolCall client.MessageToolInvocationToolCall,
  232. result *string,
  233. metadata client.MessageMetadata_Tool_AdditionalProperties,
  234. showDetails bool,
  235. isLast bool,
  236. contentOnly bool,
  237. ) string {
  238. ignoredTools := []string{"todoread"}
  239. if slices.Contains(ignoredTools, toolCall.ToolName) {
  240. return ""
  241. }
  242. outerWidth := layout.Current.Container.Width
  243. innerWidth := outerWidth - 6
  244. paddingTop := 0
  245. paddingBottom := 0
  246. if showDetails {
  247. paddingTop = 1
  248. if result == nil || *result == "" {
  249. paddingBottom = 1
  250. }
  251. }
  252. t := theme.CurrentTheme()
  253. style := styles.NewStyle().
  254. Foreground(t.TextMuted()).
  255. Background(t.BackgroundPanel()).
  256. Width(outerWidth).
  257. PaddingTop(paddingTop).
  258. PaddingBottom(paddingBottom).
  259. PaddingLeft(2).
  260. PaddingRight(2).
  261. BorderLeft(true).
  262. BorderRight(true).
  263. BorderBackground(t.Background()).
  264. BorderForeground(t.BackgroundPanel()).
  265. BorderStyle(lipgloss.ThickBorder())
  266. if toolCall.State == "partial-call" {
  267. title := renderToolAction(toolCall.ToolName)
  268. if !showDetails {
  269. title = "∟ " + title
  270. padding := calculatePadding()
  271. style := styles.NewStyle().
  272. Background(t.BackgroundPanel()).
  273. Width(outerWidth - padding - 4 - 3)
  274. return renderContentBlock(style.Render(title),
  275. WithAlign(lipgloss.Left),
  276. WithBorderColor(t.Accent()),
  277. WithPaddingTop(0),
  278. WithPaddingBottom(1),
  279. )
  280. }
  281. style = style.Foreground(t.TextMuted())
  282. return style.Render(title)
  283. }
  284. toolArgs := ""
  285. toolArgsMap := make(map[string]any)
  286. if toolCall.Args != nil {
  287. value := *toolCall.Args
  288. if m, ok := value.(map[string]any); ok {
  289. toolArgsMap = m
  290. keys := make([]string, 0, len(toolArgsMap))
  291. for key := range toolArgsMap {
  292. keys = append(keys, key)
  293. }
  294. slices.Sort(keys)
  295. firstKey := ""
  296. if len(keys) > 0 {
  297. firstKey = keys[0]
  298. }
  299. toolArgs = renderArgs(&toolArgsMap, firstKey)
  300. }
  301. }
  302. body := ""
  303. error := ""
  304. finished := result != nil && *result != ""
  305. if e, ok := metadata.Get("error"); ok && e.(bool) == true {
  306. if m, ok := metadata.Get("message"); ok {
  307. style = style.BorderLeftForeground(t.Error())
  308. error = styles.NewStyle().
  309. Foreground(t.Error()).
  310. Background(t.BackgroundPanel()).
  311. Render(m.(string))
  312. error = renderContentBlock(
  313. error,
  314. WithFullWidth(),
  315. WithBorderColor(t.Error()),
  316. WithMarginBottom(1),
  317. )
  318. }
  319. }
  320. title := ""
  321. switch toolCall.ToolName {
  322. case "read":
  323. toolArgs = renderArgs(&toolArgsMap, "filePath")
  324. title = fmt.Sprintf("READ %s", toolArgs)
  325. if preview, ok := metadata.Get("preview"); ok && toolArgsMap["filePath"] != nil {
  326. filename := toolArgsMap["filePath"].(string)
  327. body = preview.(string)
  328. body = renderFile(filename, body, WithTruncate(6))
  329. }
  330. case "edit":
  331. if filename, ok := toolArgsMap["filePath"].(string); ok {
  332. title = fmt.Sprintf("EDIT %s", relative(filename))
  333. if d, ok := metadata.Get("diff"); ok {
  334. patch := d.(string)
  335. var formattedDiff string
  336. if layout.Current.Viewport.Width < 80 {
  337. formattedDiff, _ = diff.FormatUnifiedDiff(
  338. filename,
  339. patch,
  340. diff.WithWidth(layout.Current.Container.Width-2),
  341. )
  342. } else {
  343. diffWidth := min(layout.Current.Viewport.Width-2, 120)
  344. formattedDiff, _ = diff.FormatDiff(filename, patch, diff.WithTotalWidth(diffWidth))
  345. }
  346. formattedDiff = strings.TrimSpace(formattedDiff)
  347. formattedDiff = styles.NewStyle().
  348. BorderStyle(lipgloss.ThickBorder()).
  349. BorderBackground(t.Background()).
  350. BorderForeground(t.BackgroundPanel()).
  351. BorderLeft(true).
  352. BorderRight(true).
  353. Render(formattedDiff)
  354. if showDetails {
  355. style = style.Width(lipgloss.Width(formattedDiff))
  356. title += "\n"
  357. }
  358. body = strings.TrimSpace(formattedDiff)
  359. body = lipgloss.Place(
  360. layout.Current.Viewport.Width,
  361. lipgloss.Height(body)+1,
  362. lipgloss.Center,
  363. lipgloss.Top,
  364. body,
  365. styles.WhitespaceStyle(t.Background()),
  366. )
  367. // Add diagnostics at the bottom if they exist
  368. if diagnostics := renderDiagnostics(metadata, filename); diagnostics != "" {
  369. body += "\n" + renderContentBlock(diagnostics, WithFullWidth(), WithBorderColor(t.Error()))
  370. }
  371. }
  372. }
  373. case "write":
  374. if filename, ok := toolArgsMap["filePath"].(string); ok {
  375. title = fmt.Sprintf("WRITE %s", relative(filename))
  376. if content, ok := toolArgsMap["content"].(string); ok {
  377. body = renderFile(filename, content)
  378. // Add diagnostics at the bottom if they exist
  379. if diagnostics := renderDiagnostics(metadata, filename); diagnostics != "" {
  380. body += "\n" + renderContentBlock(diagnostics, WithFullWidth(), WithBorderColor(t.Error()))
  381. }
  382. }
  383. }
  384. case "bash":
  385. if description, ok := toolArgsMap["description"].(string); ok {
  386. title = fmt.Sprintf("SHELL %s", description)
  387. }
  388. if stdout, ok := metadata.Get("stdout"); ok {
  389. command := toolArgsMap["command"].(string)
  390. stdout := stdout.(string)
  391. body = fmt.Sprintf("```console\n> %s\n%s```", command, stdout)
  392. body = toMarkdown(body, innerWidth, t.BackgroundPanel())
  393. body = renderContentBlock(body, WithFullWidth(), WithMarginBottom(1))
  394. }
  395. case "webfetch":
  396. toolArgs = renderArgs(&toolArgsMap, "url")
  397. title = fmt.Sprintf("FETCH %s", toolArgs)
  398. if format, ok := toolArgsMap["format"].(string); ok {
  399. if result != nil {
  400. body = *result
  401. body = truncateHeight(body, 10)
  402. if format == "html" || format == "markdown" {
  403. body = toMarkdown(body, innerWidth, t.BackgroundPanel())
  404. }
  405. body = renderContentBlock(body, WithFullWidth(), WithMarginBottom(1))
  406. }
  407. }
  408. case "todowrite":
  409. title = fmt.Sprintf("PLAN")
  410. if to, ok := metadata.Get("todos"); ok && finished {
  411. todos := to.([]any)
  412. for _, todo := range todos {
  413. t := todo.(map[string]any)
  414. content := t["content"].(string)
  415. switch t["status"].(string) {
  416. case "completed":
  417. body += fmt.Sprintf("- [x] %s\n", content)
  418. // case "in-progress":
  419. // body += fmt.Sprintf("- [ ] %s\n", content)
  420. default:
  421. body += fmt.Sprintf("- [ ] %s\n", content)
  422. }
  423. }
  424. body = toMarkdown(body, innerWidth, t.BackgroundPanel())
  425. body = renderContentBlock(body, WithFullWidth(), WithMarginBottom(1))
  426. }
  427. case "task":
  428. if description, ok := toolArgsMap["description"].(string); ok {
  429. title = fmt.Sprintf("TASK %s", description)
  430. if summary, ok := metadata.Get("summary"); ok {
  431. toolcalls := summary.([]any)
  432. // toolcalls :=
  433. steps := []string{}
  434. for _, toolcall := range toolcalls {
  435. call := toolcall.(map[string]any)
  436. if toolInvocation, ok := call["toolInvocation"].(map[string]any); ok {
  437. data, _ := json.Marshal(toolInvocation)
  438. var toolCall client.MessageToolInvocationToolCall
  439. _ = json.Unmarshal(data, &toolCall)
  440. if metadata, ok := call["metadata"].(map[string]any); ok {
  441. data, _ = json.Marshal(metadata)
  442. var toolMetadata client.MessageMetadata_Tool_AdditionalProperties
  443. _ = json.Unmarshal(data, &toolMetadata)
  444. step := renderToolInvocation(
  445. toolCall,
  446. nil,
  447. toolMetadata,
  448. false,
  449. false,
  450. true,
  451. )
  452. steps = append(steps, step)
  453. }
  454. }
  455. }
  456. body = strings.Join(steps, "\n")
  457. body = renderContentBlock(body, WithFullWidth(), WithMarginBottom(1))
  458. }
  459. }
  460. default:
  461. toolName := renderToolName(toolCall.ToolName)
  462. title = fmt.Sprintf("%s %s", toolName, toolArgs)
  463. if result == nil {
  464. empty := ""
  465. result = &empty
  466. }
  467. body = *result
  468. body = truncateHeight(body, 10)
  469. body = renderContentBlock(body, WithFullWidth(), WithMarginBottom(1))
  470. }
  471. if contentOnly {
  472. title = "∟ " + title
  473. return title
  474. }
  475. if !showDetails {
  476. title = "∟ " + title
  477. padding := calculatePadding()
  478. style := styles.NewStyle().Background(t.BackgroundPanel()).Width(outerWidth - padding - 4 - 3)
  479. paddingBottom := 0
  480. if isLast {
  481. paddingBottom = 1
  482. }
  483. return renderContentBlock(style.Render(title),
  484. WithAlign(lipgloss.Left),
  485. WithBorderColor(t.Accent()),
  486. WithPaddingTop(0),
  487. WithPaddingBottom(paddingBottom),
  488. )
  489. }
  490. if body == "" && error == "" {
  491. body = *result
  492. body = truncateHeight(body, 10)
  493. body = renderContentBlock(body, WithFullWidth(), WithMarginBottom(1))
  494. }
  495. content := style.Render(title)
  496. content = lipgloss.PlaceHorizontal(
  497. layout.Current.Viewport.Width,
  498. lipgloss.Center,
  499. content,
  500. styles.WhitespaceStyle(t.Background()),
  501. )
  502. if showDetails && body != "" && error == "" {
  503. content += "\n" + body
  504. }
  505. if showDetails && error != "" {
  506. content += "\n" + error
  507. }
  508. return content
  509. }
  510. func renderToolName(name string) string {
  511. switch name {
  512. case "list":
  513. return "LIST"
  514. case "webfetch":
  515. return "FETCH"
  516. case "todowrite":
  517. return "PLAN"
  518. default:
  519. normalizedName := name
  520. if strings.HasPrefix(name, "opencode_") {
  521. normalizedName = strings.TrimPrefix(name, "opencode_")
  522. }
  523. return cases.Upper(language.Und).String(normalizedName)
  524. }
  525. }
  526. type fileRenderer struct {
  527. filename string
  528. content string
  529. height int
  530. }
  531. type fileRenderingOption func(*fileRenderer)
  532. func WithTruncate(height int) fileRenderingOption {
  533. return func(c *fileRenderer) {
  534. c.height = height
  535. }
  536. }
  537. func renderFile(filename string, content string, options ...fileRenderingOption) string {
  538. t := theme.CurrentTheme()
  539. renderer := &fileRenderer{
  540. filename: filename,
  541. content: content,
  542. }
  543. for _, option := range options {
  544. option(renderer)
  545. }
  546. lines := []string{}
  547. for line := range strings.SplitSeq(content, "\n") {
  548. line = strings.TrimRightFunc(line, unicode.IsSpace)
  549. line = strings.ReplaceAll(line, "\t", " ")
  550. lines = append(lines, line)
  551. }
  552. content = strings.Join(lines, "\n")
  553. width := layout.Current.Container.Width - 8
  554. if renderer.height > 0 {
  555. content = truncateHeight(content, renderer.height)
  556. }
  557. content = fmt.Sprintf("```%s\n%s\n```", extension(renderer.filename), content)
  558. content = toMarkdown(content, width, t.BackgroundPanel())
  559. return renderContentBlock(content, WithFullWidth(), WithMarginBottom(1))
  560. }
  561. func renderToolAction(name string) string {
  562. switch name {
  563. case "task":
  564. return "Searching..."
  565. case "bash":
  566. return "Building command..."
  567. case "edit":
  568. return "Preparing edit..."
  569. case "webfetch":
  570. return "Fetching from the web..."
  571. case "glob":
  572. return "Finding files..."
  573. case "grep":
  574. return "Searching content..."
  575. case "list":
  576. return "Listing directory..."
  577. case "read":
  578. return "Reading file..."
  579. case "write":
  580. return "Preparing write..."
  581. case "todowrite", "todoread":
  582. return "Planning..."
  583. case "patch":
  584. return "Preparing patch..."
  585. case "batch":
  586. return "Running batch operations..."
  587. }
  588. return "Working..."
  589. }
  590. func renderArgs(args *map[string]any, titleKey string) string {
  591. if args == nil || len(*args) == 0 {
  592. return ""
  593. }
  594. keys := make([]string, 0, len(*args))
  595. for key := range *args {
  596. keys = append(keys, key)
  597. }
  598. slices.Sort(keys)
  599. title := ""
  600. parts := []string{}
  601. for _, key := range keys {
  602. value := (*args)[key]
  603. if value == nil {
  604. continue
  605. }
  606. if key == "filePath" || key == "path" {
  607. value = relative(value.(string))
  608. }
  609. if key == titleKey {
  610. title = fmt.Sprintf("%s", value)
  611. continue
  612. }
  613. parts = append(parts, fmt.Sprintf("%s=%v", key, value))
  614. }
  615. if len(parts) == 0 {
  616. return title
  617. }
  618. return fmt.Sprintf("%s (%s)", title, strings.Join(parts, ", "))
  619. }
  620. func truncateHeight(content string, height int) string {
  621. lines := strings.Split(content, "\n")
  622. if len(lines) > height {
  623. return strings.Join(lines[:height], "\n")
  624. }
  625. return content
  626. }
  627. func relative(path string) string {
  628. return strings.TrimPrefix(path, app.RootPath+"/")
  629. }
  630. func extension(path string) string {
  631. ext := filepath.Ext(path)
  632. if ext == "" {
  633. ext = ""
  634. } else {
  635. ext = strings.ToLower(ext[1:])
  636. }
  637. return ext
  638. }
  639. // Diagnostic represents an LSP diagnostic
  640. type Diagnostic struct {
  641. Range struct {
  642. Start struct {
  643. Line int `json:"line"`
  644. Character int `json:"character"`
  645. } `json:"start"`
  646. } `json:"range"`
  647. Severity int `json:"severity"`
  648. Message string `json:"message"`
  649. }
  650. // renderDiagnostics formats LSP diagnostics for display in the TUI
  651. func renderDiagnostics(metadata client.MessageMetadata_Tool_AdditionalProperties, filePath string) string {
  652. diagnosticsData, ok := metadata.Get("diagnostics")
  653. if !ok {
  654. return ""
  655. }
  656. // diagnosticsData should be a map[string][]Diagnostic
  657. diagnosticsMap, ok := diagnosticsData.(map[string]interface{})
  658. if !ok {
  659. return ""
  660. }
  661. fileDiagnostics, ok := diagnosticsMap[filePath]
  662. if !ok {
  663. return ""
  664. }
  665. diagnosticsList, ok := fileDiagnostics.([]interface{})
  666. if !ok {
  667. return ""
  668. }
  669. var errorDiagnostics []string
  670. for _, diagInterface := range diagnosticsList {
  671. diagMap, ok := diagInterface.(map[string]interface{})
  672. if !ok {
  673. continue
  674. }
  675. // Parse the diagnostic
  676. var diag Diagnostic
  677. diagBytes, err := json.Marshal(diagMap)
  678. if err != nil {
  679. continue
  680. }
  681. if err := json.Unmarshal(diagBytes, &diag); err != nil {
  682. continue
  683. }
  684. // Only show error diagnostics (severity === 1)
  685. if diag.Severity != 1 {
  686. continue
  687. }
  688. line := diag.Range.Start.Line + 1 // 1-based
  689. column := diag.Range.Start.Character + 1 // 1-based
  690. errorDiagnostics = append(errorDiagnostics, fmt.Sprintf("Error [%d:%d] %s", line, column, diag.Message))
  691. }
  692. if len(errorDiagnostics) == 0 {
  693. return ""
  694. }
  695. t := theme.CurrentTheme()
  696. var result strings.Builder
  697. for _, diagnostic := range errorDiagnostics {
  698. if result.Len() > 0 {
  699. result.WriteString("\n")
  700. }
  701. result.WriteString(styles.NewStyle().Foreground(t.Error()).Render(diagnostic))
  702. }
  703. return result.String()
  704. }