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