1package chat
2
3import (
4 "fmt"
5 "strings"
6
7 tea "charm.land/bubbletea/v2"
8 "charm.land/lipgloss/v2"
9 "github.com/charmbracelet/crush/internal/message"
10 "github.com/charmbracelet/crush/internal/ui/anim"
11 "github.com/charmbracelet/crush/internal/ui/common"
12 "github.com/charmbracelet/crush/internal/ui/styles"
13 "github.com/charmbracelet/x/ansi"
14)
15
16// assistantMessageTruncateFormat is the text shown when an assistant message is
17// truncated.
18const assistantMessageTruncateFormat = "… (%d lines hidden) [click or space to expand]"
19
20// maxCollapsedThinkingHeight defines the maximum height of the thinking
21const maxCollapsedThinkingHeight = 10
22
23// AssistantMessageItem represents an assistant message in the chat UI.
24//
25// This item includes thinking, and the content but does not include the tool calls.
26type AssistantMessageItem struct {
27 *highlightableMessageItem
28 *cachedMessageItem
29 *focusableMessageItem
30
31 message *message.Message
32 sty *styles.Styles
33 anim *anim.Anim
34 thinkingExpanded bool
35 thinkingBoxHeight int // Tracks the rendered thinking box height for click detection.
36}
37
38// NewAssistantMessageItem creates a new AssistantMessageItem.
39func NewAssistantMessageItem(sty *styles.Styles, message *message.Message) MessageItem {
40 a := &AssistantMessageItem{
41 highlightableMessageItem: defaultHighlighter(sty),
42 cachedMessageItem: &cachedMessageItem{},
43 focusableMessageItem: &focusableMessageItem{},
44 message: message,
45 sty: sty,
46 }
47
48 a.anim = anim.New(anim.Settings{
49 ID: a.ID(),
50 Size: 15,
51 GradColorA: sty.Primary,
52 GradColorB: sty.Secondary,
53 LabelColor: sty.FgBase,
54 CycleColors: true,
55 })
56 return a
57}
58
59// StartAnimation starts the assistant message animation if it should be spinning.
60func (a *AssistantMessageItem) StartAnimation() tea.Cmd {
61 if !a.isSpinning() {
62 return nil
63 }
64 return a.anim.Start()
65}
66
67// Animate progresses the assistant message animation if it should be spinning.
68func (a *AssistantMessageItem) Animate(msg anim.StepMsg) tea.Cmd {
69 if !a.isSpinning() {
70 return nil
71 }
72 return a.anim.Animate(msg)
73}
74
75// ID implements MessageItem.
76func (a *AssistantMessageItem) ID() string {
77 return a.message.ID
78}
79
80// RawRender implements [MessageItem].
81func (a *AssistantMessageItem) RawRender(width int) string {
82 var spinner string
83 if a.isSpinning() {
84 spinner = a.renderSpinning()
85 }
86
87 content, height, ok := a.getCachedRender(width)
88 if !ok {
89 content = a.renderMessageContent(width)
90 height = lipgloss.Height(content)
91 // cache the rendered content
92 a.setCachedRender(content, width, height)
93 }
94
95 highlightedContent := a.renderHighlighted(content, width, height)
96 if spinner != "" {
97 if highlightedContent != "" {
98 highlightedContent += "\n\n"
99 }
100 return highlightedContent + spinner
101 }
102
103 return highlightedContent
104}
105
106// Render implements MessageItem.
107func (a *AssistantMessageItem) Render(width int) string {
108 style := a.sty.Chat.Message.AssistantBlurred
109 if a.focused {
110 style = a.sty.Chat.Message.AssistantFocused
111 }
112 return style.Render(a.RawRender(width))
113}
114
115// renderMessageContent renders the message content including thinking, main content, and finish reason.
116func (a *AssistantMessageItem) renderMessageContent(width int) string {
117 var messageParts []string
118 thinking := strings.TrimSpace(a.message.ReasoningContent().Thinking)
119 content := strings.TrimSpace(a.message.Content().Text)
120 // if the massage has reasoning content add that first
121 if thinking != "" {
122 messageParts = append(messageParts, a.renderThinking(a.message.ReasoningContent().Thinking, width))
123 }
124
125 // then add the main content
126 if content != "" {
127 // add a spacer between thinking and content
128 if thinking != "" {
129 messageParts = append(messageParts, "")
130 }
131 messageParts = append(messageParts, a.renderMarkdown(content, width))
132 }
133
134 // finally add any finish reason info
135 if a.message.IsFinished() {
136 switch a.message.FinishReason() {
137 case message.FinishReasonCanceled:
138 messageParts = append(messageParts, a.sty.Base.Italic(true).Render("Canceled"))
139 case message.FinishReasonError:
140 messageParts = append(messageParts, a.renderError(width))
141 }
142 }
143
144 return strings.Join(messageParts, "\n")
145}
146
147// renderThinking renders the thinking/reasoning content with footer.
148func (a *AssistantMessageItem) renderThinking(thinking string, width int) string {
149 renderer := common.PlainMarkdownRenderer(a.sty, width)
150 rendered, err := renderer.Render(thinking)
151 if err != nil {
152 rendered = thinking
153 }
154 rendered = strings.TrimSpace(rendered)
155
156 lines := strings.Split(rendered, "\n")
157 totalLines := len(lines)
158
159 isTruncated := totalLines > maxCollapsedThinkingHeight
160 if !a.thinkingExpanded && isTruncated {
161 lines = lines[totalLines-maxCollapsedThinkingHeight:]
162 hint := a.sty.Chat.Message.ThinkingTruncationHint.Render(
163 fmt.Sprintf(assistantMessageTruncateFormat, totalLines-maxCollapsedThinkingHeight),
164 )
165 lines = append([]string{hint, ""}, lines...)
166 }
167
168 thinkingStyle := a.sty.Chat.Message.ThinkingBox.Width(width)
169 result := thinkingStyle.Render(strings.Join(lines, "\n"))
170 a.thinkingBoxHeight = lipgloss.Height(result)
171
172 var footer string
173 // if thinking is done add the thought for footer
174 if !a.message.IsThinking() || len(a.message.ToolCalls()) > 0 {
175 duration := a.message.ThinkingDuration()
176 if duration.String() != "0s" {
177 footer = a.sty.Chat.Message.ThinkingFooterTitle.Render("Thought for ") +
178 a.sty.Chat.Message.ThinkingFooterDuration.Render(duration.String())
179 }
180 }
181
182 if footer != "" {
183 result += "\n\n" + footer
184 }
185
186 return result
187}
188
189// renderMarkdown renders content as markdown.
190func (a *AssistantMessageItem) renderMarkdown(content string, width int) string {
191 renderer := common.MarkdownRenderer(a.sty, width)
192 result, err := renderer.Render(content)
193 if err != nil {
194 return content
195 }
196 return strings.TrimSuffix(result, "\n")
197}
198
199func (a *AssistantMessageItem) renderSpinning() string {
200 if a.message.IsThinking() {
201 a.anim.SetLabel("Thinking")
202 } else if a.message.IsSummaryMessage {
203 a.anim.SetLabel("Summarizing")
204 }
205 return a.anim.Render()
206}
207
208// renderError renders an error message.
209func (a *AssistantMessageItem) renderError(width int) string {
210 finishPart := a.message.FinishPart()
211 errTag := a.sty.Chat.Message.ErrorTag.Render("ERROR")
212 truncated := ansi.Truncate(finishPart.Message, width-2-lipgloss.Width(errTag), "...")
213 title := fmt.Sprintf("%s %s", errTag, a.sty.Chat.Message.ErrorTitle.Render(truncated))
214 details := a.sty.Chat.Message.ErrorDetails.Width(width - 2).Render(finishPart.Details)
215 return fmt.Sprintf("%s\n\n%s", title, details)
216}
217
218// isSpinning returns true if the assistant message is still generating.
219func (a *AssistantMessageItem) isSpinning() bool {
220 isThinking := a.message.IsThinking()
221 isFinished := a.message.IsFinished()
222 hasContent := strings.TrimSpace(a.message.Content().Text) != ""
223 hasToolCalls := len(a.message.ToolCalls()) > 0
224 return (isThinking || !isFinished) && !hasContent && !hasToolCalls
225}
226
227// SetMessage is used to update the underlying message.
228func (a *AssistantMessageItem) SetMessage(message *message.Message) tea.Cmd {
229 wasSpinning := a.isSpinning()
230 a.message = message
231 a.clearCache()
232 if !wasSpinning && a.isSpinning() {
233 return a.StartAnimation()
234 }
235 return nil
236}
237
238// ToggleExpanded toggles the expanded state of the thinking box.
239func (a *AssistantMessageItem) ToggleExpanded() {
240 a.thinkingExpanded = !a.thinkingExpanded
241 a.clearCache()
242}
243
244// HandleMouseClick implements MouseClickable.
245func (a *AssistantMessageItem) HandleMouseClick(btn ansi.MouseButton, x, y int) bool {
246 if btn != ansi.MouseLeft {
247 return false
248 }
249 // check if the click is within the thinking box
250 if a.thinkingBoxHeight > 0 && y < a.thinkingBoxHeight {
251 a.ToggleExpanded()
252 return true
253 }
254 return false
255}
256
257// HandleKeyEvent implements KeyEventHandler.
258func (a *AssistantMessageItem) HandleKeyEvent(key tea.KeyMsg) (bool, tea.Cmd) {
259 if k := key.String(); k == "c" || k == "y" {
260 text := a.message.Content().Text
261 return true, common.CopyToClipboard(text, "Message copied to clipboard")
262 }
263 return false, nil
264}