1package messages
2
3import (
4 "fmt"
5 "path/filepath"
6 "strings"
7 "time"
8
9 "github.com/charmbracelet/bubbles/v2/key"
10 "github.com/charmbracelet/bubbles/v2/viewport"
11 tea "github.com/charmbracelet/bubbletea/v2"
12 "github.com/charmbracelet/catwalk/pkg/catwalk"
13 "github.com/charmbracelet/lipgloss/v2"
14 "github.com/charmbracelet/x/ansi"
15 "github.com/google/uuid"
16
17 "github.com/atotto/clipboard"
18 "github.com/charmbracelet/crush/internal/config"
19 "github.com/charmbracelet/crush/internal/message"
20 "github.com/charmbracelet/crush/internal/tui/components/anim"
21 "github.com/charmbracelet/crush/internal/tui/components/core"
22 "github.com/charmbracelet/crush/internal/tui/components/core/layout"
23 "github.com/charmbracelet/crush/internal/tui/exp/list"
24 "github.com/charmbracelet/crush/internal/tui/styles"
25 "github.com/charmbracelet/crush/internal/tui/util"
26)
27
28var copyKey = key.NewBinding(key.WithKeys("c", "y", "C", "Y"), key.WithHelp("c/y", "copy"))
29
30// MessageCmp defines the interface for message components in the chat interface.
31// It combines standard UI model interfaces with message-specific functionality.
32type MessageCmp interface {
33 util.Model // Basic Bubble Tea model interface
34 layout.Sizeable // Width/height management
35 layout.Focusable // Focus state management
36 GetMessage() message.Message // Access to underlying message data
37 SetMessage(msg message.Message) // Update the message content
38 Spinning() bool // Animation state for loading messages
39 ID() string
40}
41
42// messageCmp implements the MessageCmp interface for displaying chat messages.
43// It handles rendering of user and assistant messages with proper styling,
44// animations, and state management.
45type messageCmp struct {
46 width int // Component width for text wrapping
47 focused bool // Focus state for border styling
48
49 // Core message data and state
50 message message.Message // The underlying message content
51 spinning bool // Whether to show loading animation
52 anim *anim.Anim // Animation component for loading states
53
54 // Thinking viewport for displaying reasoning content
55 thinkingViewport viewport.Model
56}
57
58var focusedMessageBorder = lipgloss.Border{
59 Left: "▌",
60}
61
62// NewMessageCmp creates a new message component with the given message and options
63func NewMessageCmp(msg message.Message) MessageCmp {
64 t := styles.CurrentTheme()
65
66 thinkingViewport := viewport.New()
67 thinkingViewport.SetHeight(1)
68 thinkingViewport.KeyMap = viewport.KeyMap{}
69
70 m := &messageCmp{
71 message: msg,
72 anim: anim.New(anim.Settings{
73 Size: 15,
74 GradColorA: t.Primary,
75 GradColorB: t.Secondary,
76 CycleColors: true,
77 }),
78 thinkingViewport: thinkingViewport,
79 }
80 return m
81}
82
83// Init initializes the message component and starts animations if needed.
84// Returns a command to start the animation for spinning messages.
85func (m *messageCmp) Init() tea.Cmd {
86 m.spinning = m.shouldSpin()
87 return m.anim.Init()
88}
89
90// Update handles incoming messages and updates the component state.
91// Manages animation updates for spinning messages and stops animation when appropriate.
92func (m *messageCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
93 switch msg := msg.(type) {
94 case anim.StepMsg:
95 m.spinning = m.shouldSpin()
96 if m.spinning {
97 u, cmd := m.anim.Update(msg)
98 m.anim = u.(*anim.Anim)
99 return m, cmd
100 }
101 case tea.KeyPressMsg:
102 if key.Matches(msg, copyKey) {
103 err := clipboard.WriteAll(m.message.Content().Text)
104 if err != nil {
105 return m, util.ReportError(fmt.Errorf("failed to copy message content to clipboard: %w", err))
106 }
107 return m, util.ReportInfo("Message copied to clipboard")
108 }
109 }
110 return m, nil
111}
112
113// View renders the message component based on its current state.
114// Returns different views for spinning, user, and assistant messages.
115func (m *messageCmp) View() string {
116 if m.spinning && m.message.ReasoningContent().Thinking == "" {
117 return m.style().PaddingLeft(1).Render(m.anim.View())
118 }
119 if m.message.ID != "" {
120 // this is a user or assistant message
121 switch m.message.Role {
122 case message.User:
123 return m.renderUserMessage()
124 default:
125 return m.renderAssistantMessage()
126 }
127 }
128 return m.style().Render("No message content")
129}
130
131// GetMessage returns the underlying message data
132func (m *messageCmp) GetMessage() message.Message {
133 return m.message
134}
135
136func (m *messageCmp) SetMessage(msg message.Message) {
137 m.message = msg
138}
139
140// textWidth calculates the available width for text content,
141// accounting for borders and padding
142func (m *messageCmp) textWidth() int {
143 return m.width - 2 // take into account the border and/or padding
144}
145
146// style returns the lipgloss style for the message component.
147// Applies different border colors and styles based on message role and focus state.
148func (msg *messageCmp) style() lipgloss.Style {
149 t := styles.CurrentTheme()
150 borderStyle := lipgloss.NormalBorder()
151 if msg.focused {
152 borderStyle = focusedMessageBorder
153 }
154
155 style := t.S().Text
156 if msg.message.Role == message.User {
157 style = style.PaddingLeft(1).BorderLeft(true).BorderStyle(borderStyle).BorderForeground(t.Primary)
158 } else {
159 if msg.focused {
160 style = style.PaddingLeft(1).BorderLeft(true).BorderStyle(borderStyle).BorderForeground(t.GreenDark)
161 } else {
162 style = style.PaddingLeft(2)
163 }
164 }
165 return style
166}
167
168// renderAssistantMessage renders assistant messages with optional footer information.
169// Shows model name, response time, and finish reason when the message is complete.
170func (m *messageCmp) renderAssistantMessage() string {
171 t := styles.CurrentTheme()
172 parts := []string{}
173 content := m.message.Content().String()
174 thinking := m.message.IsThinking()
175 finished := m.message.IsFinished()
176 finishedData := m.message.FinishPart()
177 thinkingContent := ""
178
179 if thinking || m.message.ReasoningContent().Thinking != "" {
180 m.anim.SetLabel("Thinking")
181 thinkingContent = m.renderThinkingContent()
182 } else if finished && content == "" && finishedData.Reason == message.FinishReasonEndTurn {
183 content = ""
184 } else if finished && content == "" && finishedData.Reason == message.FinishReasonCanceled {
185 content = "*Canceled*"
186 } else if finished && content == "" && finishedData.Reason == message.FinishReasonError {
187 errTag := t.S().Base.Padding(0, 1).Background(t.Red).Foreground(t.White).Render("ERROR")
188 truncated := ansi.Truncate(finishedData.Message, m.textWidth()-2-lipgloss.Width(errTag), "...")
189 title := fmt.Sprintf("%s %s", errTag, t.S().Base.Foreground(t.FgHalfMuted).Render(truncated))
190 details := t.S().Base.Foreground(t.FgSubtle).Width(m.textWidth() - 2).Render(finishedData.Details)
191 errorContent := fmt.Sprintf("%s\n\n%s", title, details)
192 return m.style().Render(errorContent)
193 }
194
195 if thinkingContent != "" {
196 parts = append(parts, thinkingContent)
197 }
198
199 if content != "" {
200 if thinkingContent != "" {
201 parts = append(parts, "")
202 }
203 parts = append(parts, m.toMarkdown(content))
204 }
205
206 joined := lipgloss.JoinVertical(lipgloss.Left, parts...)
207 return m.style().Render(joined)
208}
209
210// renderUserMessage renders user messages with file attachments. It displays
211// message content and any attached files with appropriate icons.
212func (m *messageCmp) renderUserMessage() string {
213 t := styles.CurrentTheme()
214 parts := []string{
215 m.toMarkdown(m.message.Content().String()),
216 }
217
218 attachmentStyles := t.S().Text.
219 MarginLeft(1).
220 Background(t.BgSubtle)
221
222 attachments := make([]string, len(m.message.BinaryContent()))
223 for i, attachment := range m.message.BinaryContent() {
224 const maxFilenameWidth = 10
225 filename := filepath.Base(attachment.Path)
226 attachments[i] = attachmentStyles.Render(fmt.Sprintf(
227 " %s %s ",
228 styles.DocumentIcon,
229 ansi.Truncate(filename, maxFilenameWidth, "..."),
230 ))
231 }
232
233 if len(attachments) > 0 {
234 parts = append(parts, "", strings.Join(attachments, ""))
235 }
236
237 joined := lipgloss.JoinVertical(lipgloss.Left, parts...)
238 return m.style().Render(joined)
239}
240
241// toMarkdown converts text content to rendered markdown using the configured renderer
242func (m *messageCmp) toMarkdown(content string) string {
243 r := styles.GetMarkdownRenderer(m.textWidth())
244 rendered, _ := r.Render(content)
245 return strings.TrimSuffix(rendered, "\n")
246}
247
248func (m *messageCmp) renderThinkingContent() string {
249 t := styles.CurrentTheme()
250 reasoningContent := m.message.ReasoningContent()
251 if reasoningContent.Thinking == "" {
252 return ""
253 }
254 lines := strings.Split(reasoningContent.Thinking, "\n")
255 var content strings.Builder
256 lineStyle := t.S().Subtle.Background(t.BgBaseLighter)
257 for i, line := range lines {
258 if line == "" {
259 continue
260 }
261 content.WriteString(lineStyle.Width(m.textWidth() - 2).Render(line))
262 if i < len(lines)-1 {
263 content.WriteString("\n")
264 }
265 }
266 fullContent := content.String()
267 height := util.Clamp(lipgloss.Height(fullContent), 1, 10)
268 m.thinkingViewport.SetHeight(height)
269 m.thinkingViewport.SetWidth(m.textWidth())
270 m.thinkingViewport.SetContent(fullContent)
271 m.thinkingViewport.GotoBottom()
272 finishReason := m.message.FinishPart()
273 var footer string
274 if reasoningContent.StartedAt > 0 {
275 duration := m.message.ThinkingDuration()
276 if reasoningContent.FinishedAt > 0 {
277 if duration.String() == "0s" {
278 return ""
279 }
280 m.anim.SetLabel("")
281 opts := core.StatusOpts{
282 Title: "Thought for",
283 Description: duration.String(),
284 NoIcon: true,
285 }
286 return t.S().Base.PaddingLeft(1).Render(core.Status(opts, m.textWidth()-1))
287 } else if finishReason != nil && finishReason.Reason == message.FinishReasonCanceled {
288 footer = t.S().Base.PaddingLeft(1).Render(m.toMarkdown("*Canceled*"))
289 } else {
290 footer = m.anim.View()
291 }
292 }
293 return lineStyle.Width(m.textWidth()).Padding(0, 1).Render(m.thinkingViewport.View()) + "\n\n" + footer
294}
295
296// shouldSpin determines whether the message should show a loading animation.
297// Only assistant messages without content that aren't finished should spin.
298func (m *messageCmp) shouldSpin() bool {
299 if m.message.Role != message.Assistant {
300 return false
301 }
302
303 if m.message.IsFinished() {
304 return false
305 }
306
307 if m.message.Content().Text != "" {
308 return false
309 }
310 if len(m.message.ToolCalls()) > 0 {
311 return false
312 }
313 return true
314}
315
316// Blur removes focus from the message component
317func (m *messageCmp) Blur() tea.Cmd {
318 m.focused = false
319 return nil
320}
321
322// Focus sets focus on the message component
323func (m *messageCmp) Focus() tea.Cmd {
324 m.focused = true
325 return nil
326}
327
328// IsFocused returns whether the message component is currently focused
329func (m *messageCmp) IsFocused() bool {
330 return m.focused
331}
332
333// Size management methods
334
335// GetSize returns the current dimensions of the message component
336func (m *messageCmp) GetSize() (int, int) {
337 return m.width, 0
338}
339
340// SetSize updates the width of the message component for text wrapping
341func (m *messageCmp) SetSize(width int, height int) tea.Cmd {
342 m.width = util.Clamp(width, 1, 120)
343 m.thinkingViewport.SetWidth(m.width - 4)
344 return nil
345}
346
347// Spinning returns whether the message is currently showing a loading animation
348func (m *messageCmp) Spinning() bool {
349 return m.spinning
350}
351
352type AssistantSection interface {
353 list.Item
354 layout.Sizeable
355}
356type assistantSectionModel struct {
357 width int
358 id string
359 message message.Message
360 lastUserMessageTime time.Time
361}
362
363// ID implements AssistantSection.
364func (m *assistantSectionModel) ID() string {
365 return m.id
366}
367
368func NewAssistantSection(message message.Message, lastUserMessageTime time.Time) AssistantSection {
369 return &assistantSectionModel{
370 width: 0,
371 id: uuid.NewString(),
372 message: message,
373 lastUserMessageTime: lastUserMessageTime,
374 }
375}
376
377func (m *assistantSectionModel) Init() tea.Cmd {
378 return nil
379}
380
381func (m *assistantSectionModel) Update(tea.Msg) (tea.Model, tea.Cmd) {
382 return m, nil
383}
384
385func (m *assistantSectionModel) View() string {
386 t := styles.CurrentTheme()
387 finishData := m.message.FinishPart()
388 finishTime := time.Unix(finishData.Time, 0)
389 duration := finishTime.Sub(m.lastUserMessageTime)
390 infoMsg := t.S().Subtle.Render(duration.String())
391 icon := t.S().Subtle.Render(styles.ModelIcon)
392 model := config.Get().GetModel(m.message.Provider, m.message.Model)
393 if model == nil {
394 // This means the model is not configured anymore
395 model = &catwalk.Model{
396 Name: "Unknown Model",
397 }
398 }
399 modelFormatted := t.S().Muted.Render(model.Name)
400 assistant := fmt.Sprintf("%s %s %s", icon, modelFormatted, infoMsg)
401 return t.S().Base.PaddingLeft(2).Render(
402 core.Section(assistant, m.width-2),
403 )
404}
405
406func (m *assistantSectionModel) GetSize() (int, int) {
407 return m.width, 1
408}
409
410func (m *assistantSectionModel) SetSize(width int, height int) tea.Cmd {
411 m.width = width
412 return nil
413}
414
415func (m *assistantSectionModel) IsSectionHeader() bool {
416 return true
417}
418
419func (m *messageCmp) ID() string {
420 return m.message.ID
421}