62159
Sy
symb / files
symb / internal / tui / conv.go
7.6 KB
1package tui 2 3import ( 4 "fmt" 5 "strings" 6 7 "charm.land/lipgloss/v2" 8 "github.com/xonecas/symb/internal/highlight" 9 "github.com/xonecas/symb/internal/provider" 10) 11 12// --------------------------------------------------------------------------- 13// Conversation entry helpers 14// --------------------------------------------------------------------------- 15 16// convWidth returns the usable width of the conversation pane. 17func (m Model) convWidth() int { return m.layout.conv.Dx() } 18 19// highlightMarkdown highlights a full markdown text block via Chroma. 20// The entire text is tokenised as one unit so multi-line constructs 21// (fenced code blocks, block quotes, etc.) maintain correct state. 22// Rendering cost is bounded by the frame-loop tick (~16ms). 23func highlightMarkdown(text string, fallback lipgloss.Style) []string { 24 hl := highlight.Highlight(text, "markdown", syntaxThemeName, palette.Bg) 25 if hl == text { 26 // Chroma produced no highlighting; apply fallback per line. 27 raw := strings.Split(text, "\n") 28 out := make([]string, len(raw)) 29 for i, line := range raw { 30 out[i] = fallback.Render(line) 31 } 32 return out 33 } 34 return highlight.SplitLines(hl) 35} 36 37// styledLines applies a lipgloss style to each line in a multi-line text. 38// No wrapping — lines are stored raw for later wrapping at render time. 39func styledLines(text string, style lipgloss.Style) []string { 40 raw := strings.Split(text, "\n") 41 out := make([]string, len(raw)) 42 for i, l := range raw { 43 out[i] = style.Render(l) 44 } 45 return out 46} 47 48// textEntries converts styled display strings into plain convEntry values. 49func textEntries(lines ...string) []convEntry { 50 out := make([]convEntry, len(lines)) 51 for i, l := range lines { 52 out[i] = convEntry{display: l, kind: entryText} 53 } 54 return out 55} 56 57// appendConv appends entries and returns whether we were at bottom 58// (for sticky scroll). 59func (m *Model) appendConv(entries ...convEntry) bool { 60 atBottom := m.scrollOffset == 0 61 if !atBottom { 62 addedLines := 0 63 w := m.convWidth() 64 for _, entry := range entries { 65 if entry.display == "" { 66 addedLines++ 67 continue 68 } 69 if w <= 0 { 70 addedLines++ 71 continue 72 } 73 addedLines += len(wrapANSI(entry.display, w)) 74 } 75 m.scrollOffset += addedLines 76 } 77 m.convEntries = append(m.convEntries, entries...) 78 return atBottom 79} 80 81// appendText is a convenience to append plain text entries. 82func (m *Model) appendText(lines ...string) bool { 83 return m.appendConv(textEntries(lines...)...) 84} 85 86// rebuildStreamEntries replaces any existing streaming entries with fresh 87// styled entries from the current streamingReasoning and streamingContent. 88// Wrapping is deferred to View() — this only updates convEntries. 89func (m *Model) rebuildStreamEntries() { 90 // Remove old streaming entries. 91 if m.streamEntryStart >= 0 && m.streamEntryStart <= len(m.convEntries) { 92 m.convEntries = m.convEntries[:m.streamEntryStart] 93 } 94 95 if m.streamingReasoning != "" { 96 m.convEntries = append(m.convEntries, textEntries(styledLines(m.streamingReasoning, m.styles.Muted)...)...) 97 } 98 if m.streamingContent != "" { 99 m.convEntries = append(m.convEntries, textEntries(highlightMarkdown(m.streamingContent, m.styles.Text)...)...) 100 } 101} 102 103// wrappedConvLines wraps all conversation entries to the current convWidth. 104// Cached for the current frame — cleared at the start of each Update cycle. 105func (m *Model) wrappedConvLines() []string { 106 if m.frameLines != nil { 107 return m.frameLines 108 } 109 w := m.convWidth() 110 lines := make([]string, 0, len(m.convEntries)) 111 source := make([]int, 0, len(m.convEntries)) 112 for i, entry := range m.convEntries { 113 if entry.display == "" { 114 lines = append(lines, "") 115 source = append(source, i) 116 } else { 117 wrapped := wrapANSI(entry.display, w) 118 for range wrapped { 119 source = append(source, i) 120 } 121 lines = append(lines, wrapped...) 122 } 123 } 124 m.convLineSource = source 125 m.frameLines = lines 126 return lines 127} 128 129// formatTokens formats a token count for display (e.g. 1234 -> "1.2k"). 130func formatTokens(n int) string { 131 if n < 1000 { 132 return fmt.Sprintf("%d", n) 133 } 134 return fmt.Sprintf("%.1fk", float64(n)/1000) 135} 136 137// makeSeparator builds a timestamp/token separator label. 138// Centering is applied at render time so it adapts to resizes. 139func makeSeparator(sty Styles, dur, ts string, tokIn, tokOut, totalTok, ctxTok int) string { 140 var label string 141 if tokIn > 0 || tokOut > 0 { 142 label = fmt.Sprintf("%s %s ↓ %s ↑ %s Σ %s ◔ %s", ts, dur, formatTokens(tokIn), formatTokens(tokOut), formatTokens(totalTok), formatTokens(ctxTok)) 143 } else { 144 label = ts + " " + dur 145 } 146 return sty.Dim.Render(label) 147} 148 149// makeUndoEntry creates convEntries for the undo control: the separator line 150// plus a centered [undo] button below it. Centering is applied at render time. 151// sepDisplay is the styled separator text to restore if the undo entry is demoted. 152func (m Model) makeUndoEntry(sepDisplay string) []convEntry { 153 return []convEntry{ 154 {display: sepDisplay, kind: entrySeparator, full: sepDisplay}, 155 {display: m.styles.Clickable.Render("undo"), kind: entryUndo, full: sepDisplay}, 156 } 157} 158 159// isCentered returns true if the wrapped line at lineIdx belongs to a 160// separator or undo entry that should be centered in the conversation pane. 161// Caller must ensure convLineSource is fresh (call wrappedConvLines first). 162func (m Model) isCentered(lineIdx int) bool { 163 src := m.convLineSource 164 if lineIdx < 0 || lineIdx >= len(src) { 165 return false 166 } 167 entryIdx := src[lineIdx] 168 if entryIdx < 0 || entryIdx >= len(m.convEntries) { 169 return false 170 } 171 k := m.convEntries[entryIdx].kind 172 return k == entrySeparator || k == entryUndo 173} 174 175// visibleStartLine returns the index of the first visible wrapped conversation line. 176func (m *Model) visibleStartLine() int { 177 lines := m.wrappedConvLines() 178 total := len(lines) 179 visible := m.layout.conv.Dy() 180 if total <= visible { 181 return 0 182 } 183 start := total - visible - m.scrollOffset 184 if start < 0 { 185 return 0 186 } 187 return start 188} 189 190// historyConvEntries rebuilds conversation display entries from loaded history. 191func historyConvEntries(msgs []provider.Message, sty Styles) []convEntry { 192 var entries []convEntry 193 for _, msg := range msgs { 194 switch msg.Role { 195 case "system": 196 // not displayed 197 case "user": 198 if msg.Content == "" { 199 continue 200 } 201 entries = append(entries, convEntry{display: "", kind: entryText}) 202 entries = append(entries, textEntries(highlightMarkdown(msg.Content, sty.Text)...)...) 203 entries = append(entries, convEntry{display: "", kind: entryText}) 204 case roleAssistant: 205 if msg.Reasoning != "" { 206 entries = append(entries, textEntries(styledLines(msg.Reasoning, sty.Muted)...)...) 207 entries = append(entries, convEntry{display: "", kind: entryText}) 208 } 209 if msg.Content != "" { 210 entries = append(entries, textEntries(highlightMarkdown(msg.Content, sty.Text)...)...) 211 entries = append(entries, convEntry{display: "", kind: entryText}) 212 } 213 for _, tc := range msg.ToolCalls { 214 display := sty.ToolArrow.Render("→ ") + sty.BgFill.Render(" ") + sty.ToolCall.Render(formatToolCall(tc)) 215 entries = append(entries, convEntry{display: display, kind: entryToolCall}) 216 } 217 case "tool": 218 if msg.Content != "" { 219 lines := strings.SplitN(msg.Content, "\n", 2) 220 body := lines[0] 221 if len(body) > 200 { 222 body = body[:200] + "…" 223 } 224 arrow := sty.ToolArrow.Render("← ") + sty.BgFill.Render(" ") 225 display := arrow + sty.Dim.Render(body) + sty.BgFill.Render(" ") + sty.Clickable.Render("view") 226 227 var filePath string 228 if sm := toolResultFileRe.FindStringSubmatch(msg.Content); sm != nil { 229 filePath = sm[1] 230 } 231 entries = append(entries, convEntry{ 232 display: display, 233 kind: entryToolResult, 234 filePath: filePath, 235 full: msg.Content, 236 }) 237 } 238 } 239 } 240 return entries 241}