messages.go

  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			}
285			return t.S().Base.PaddingLeft(1).Render(core.Status(opts, m.textWidth()-1))
286		} else if finishReason != nil && finishReason.Reason == message.FinishReasonCanceled {
287			footer = t.S().Base.PaddingLeft(1).Render(m.toMarkdown("*Canceled*"))
288		} else {
289			footer = m.anim.View()
290		}
291	}
292	return lineStyle.Width(m.textWidth()).Padding(0, 1).Render(m.thinkingViewport.View()) + "\n\n" + footer
293}
294
295// shouldSpin determines whether the message should show a loading animation.
296// Only assistant messages without content that aren't finished should spin.
297func (m *messageCmp) shouldSpin() bool {
298	if m.message.Role != message.Assistant {
299		return false
300	}
301
302	if m.message.IsFinished() {
303		return false
304	}
305
306	if m.message.Content().Text != "" {
307		return false
308	}
309	if len(m.message.ToolCalls()) > 0 {
310		return false
311	}
312	return true
313}
314
315// Blur removes focus from the message component
316func (m *messageCmp) Blur() tea.Cmd {
317	m.focused = false
318	return nil
319}
320
321// Focus sets focus on the message component
322func (m *messageCmp) Focus() tea.Cmd {
323	m.focused = true
324	return nil
325}
326
327// IsFocused returns whether the message component is currently focused
328func (m *messageCmp) IsFocused() bool {
329	return m.focused
330}
331
332// Size management methods
333
334// GetSize returns the current dimensions of the message component
335func (m *messageCmp) GetSize() (int, int) {
336	return m.width, 0
337}
338
339// SetSize updates the width of the message component for text wrapping
340func (m *messageCmp) SetSize(width int, height int) tea.Cmd {
341	m.width = util.Clamp(width, 1, 120)
342	m.thinkingViewport.SetWidth(m.width - 4)
343	return nil
344}
345
346// Spinning returns whether the message is currently showing a loading animation
347func (m *messageCmp) Spinning() bool {
348	return m.spinning
349}
350
351type AssistantSection interface {
352	list.Item
353	layout.Sizeable
354}
355type assistantSectionModel struct {
356	width               int
357	id                  string
358	message             message.Message
359	lastUserMessageTime time.Time
360}
361
362// ID implements AssistantSection.
363func (m *assistantSectionModel) ID() string {
364	return m.id
365}
366
367func NewAssistantSection(message message.Message, lastUserMessageTime time.Time) AssistantSection {
368	return &assistantSectionModel{
369		width:               0,
370		id:                  uuid.NewString(),
371		message:             message,
372		lastUserMessageTime: lastUserMessageTime,
373	}
374}
375
376func (m *assistantSectionModel) Init() tea.Cmd {
377	return nil
378}
379
380func (m *assistantSectionModel) Update(tea.Msg) (tea.Model, tea.Cmd) {
381	return m, nil
382}
383
384func (m *assistantSectionModel) View() string {
385	t := styles.CurrentTheme()
386	finishData := m.message.FinishPart()
387	finishTime := time.Unix(finishData.Time, 0)
388	duration := finishTime.Sub(m.lastUserMessageTime)
389	infoMsg := t.S().Subtle.Render(duration.String())
390	icon := t.S().Subtle.Render(styles.ModelIcon)
391	model := config.Get().GetModel(m.message.Provider, m.message.Model)
392	if model == nil {
393		// This means the model is not configured anymore
394		model = &catwalk.Model{
395			Name: "Unknown Model",
396		}
397	}
398	modelFormatted := t.S().Muted.Render(model.Name)
399	assistant := fmt.Sprintf("%s %s %s", icon, modelFormatted, infoMsg)
400	return t.S().Base.PaddingLeft(2).Render(
401		core.Section(assistant, m.width-2),
402	)
403}
404
405func (m *assistantSectionModel) GetSize() (int, int) {
406	return m.width, 1
407}
408
409func (m *assistantSectionModel) SetSize(width int, height int) tea.Cmd {
410	m.width = width
411	return nil
412}
413
414func (m *assistantSectionModel) IsSectionHeader() bool {
415	return true
416}
417
418func (m *messageCmp) ID() string {
419	return m.message.ID
420}