1package chat
2
3import (
4 "fmt"
5 "image"
6 "strings"
7 "time"
8
9 tea "charm.land/bubbletea/v2"
10 "charm.land/catwalk/pkg/catwalk"
11 "charm.land/lipgloss/v2"
12 "github.com/charmbracelet/crush/internal/config"
13 "github.com/charmbracelet/crush/internal/message"
14 "github.com/charmbracelet/crush/internal/ui/anim"
15 "github.com/charmbracelet/crush/internal/ui/attachments"
16 "github.com/charmbracelet/crush/internal/ui/common"
17 "github.com/charmbracelet/crush/internal/ui/list"
18 "github.com/charmbracelet/crush/internal/ui/styles"
19)
20
21// MessageLeftPaddingTotal is the total width that is taken up by the border +
22// padding. We also cap the width so text is readable to the maxTextWidth(120).
23const MessageLeftPaddingTotal = 2
24
25// maxTextWidth is the maximum width text messages can be
26const maxTextWidth = 120
27
28// Identifiable is an interface for items that can provide a unique identifier.
29type Identifiable interface {
30 ID() string
31}
32
33// Animatable is an interface for items that support animation.
34type Animatable interface {
35 StartAnimation() tea.Cmd
36 Animate(msg anim.StepMsg) tea.Cmd
37}
38
39// Expandable is an interface for items that can be expanded or collapsed.
40type Expandable interface {
41 // ToggleExpanded toggles the expanded state of the item. It returns
42 // whether the item is now expanded.
43 ToggleExpanded() bool
44}
45
46// KeyEventHandler is an interface for items that can handle key events.
47type KeyEventHandler interface {
48 HandleKeyEvent(key tea.KeyMsg) (bool, tea.Cmd)
49}
50
51// MessageItem represents a [message.Message] item that can be displayed in the
52// UI and be part of a [list.List] identifiable by a unique ID.
53type MessageItem interface {
54 list.Item
55 list.RawRenderable
56 Identifiable
57}
58
59// HighlightableMessageItem is a message item that supports highlighting.
60type HighlightableMessageItem interface {
61 MessageItem
62 list.Highlightable
63}
64
65// FocusableMessageItem is a message item that supports focus.
66type FocusableMessageItem interface {
67 MessageItem
68 list.Focusable
69}
70
71// SendMsg represents a message to send a chat message.
72type SendMsg struct {
73 Text string
74 Attachments []message.Attachment
75}
76
77type highlightableMessageItem struct {
78 startLine int
79 startCol int
80 endLine int
81 endCol int
82 highlighter list.Highlighter
83}
84
85var _ list.Highlightable = (*highlightableMessageItem)(nil)
86
87// isHighlighted returns true if the item has a highlight range set.
88func (h *highlightableMessageItem) isHighlighted() bool {
89 return h.startLine != -1 || h.endLine != -1
90}
91
92// renderHighlighted highlights the content if necessary.
93func (h *highlightableMessageItem) renderHighlighted(content string, width, height int) string {
94 if !h.isHighlighted() {
95 return content
96 }
97 area := image.Rect(0, 0, width, height)
98 return list.Highlight(content, area, h.startLine, h.startCol, h.endLine, h.endCol, h.highlighter)
99}
100
101// SetHighlight implements list.Highlightable.
102func (h *highlightableMessageItem) SetHighlight(startLine int, startCol int, endLine int, endCol int) {
103 // Adjust columns for the style's left inset (border + padding) since we
104 // highlight the content only.
105 offset := MessageLeftPaddingTotal
106 h.startLine = startLine
107 h.startCol = max(0, startCol-offset)
108 h.endLine = endLine
109 if endCol >= 0 {
110 h.endCol = max(0, endCol-offset)
111 } else {
112 h.endCol = endCol
113 }
114}
115
116// Highlight implements list.Highlightable.
117func (h *highlightableMessageItem) Highlight() (startLine int, startCol int, endLine int, endCol int) {
118 return h.startLine, h.startCol, h.endLine, h.endCol
119}
120
121func defaultHighlighter(sty *styles.Styles) *highlightableMessageItem {
122 return &highlightableMessageItem{
123 startLine: -1,
124 startCol: -1,
125 endLine: -1,
126 endCol: -1,
127 highlighter: list.ToHighlighter(sty.TextSelection),
128 }
129}
130
131// cachedMessageItem caches rendered message content to avoid re-rendering.
132//
133// This should be used by any message that can store a cached version of its render. e.x user,assistant... and so on
134//
135// THOUGHT(kujtim): we should consider if its efficient to store the render for different widths
136// the issue with that could be memory usage
137type cachedMessageItem struct {
138 // rendered is the cached rendered string
139 rendered string
140 // width and height are the dimensions of the cached render
141 width int
142 height int
143}
144
145// getCachedRender returns the cached render if it exists for the given width.
146func (c *cachedMessageItem) getCachedRender(width int) (string, int, bool) {
147 if c.width == width && c.rendered != "" {
148 return c.rendered, c.height, true
149 }
150 return "", 0, false
151}
152
153// setCachedRender sets the cached render.
154func (c *cachedMessageItem) setCachedRender(rendered string, width, height int) {
155 c.rendered = rendered
156 c.width = width
157 c.height = height
158}
159
160// clearCache clears the cached render.
161func (c *cachedMessageItem) clearCache() {
162 c.rendered = ""
163 c.width = 0
164 c.height = 0
165}
166
167// focusableMessageItem is a base struct for message items that can be focused.
168type focusableMessageItem struct {
169 focused bool
170}
171
172// SetFocused implements MessageItem.
173func (f *focusableMessageItem) SetFocused(focused bool) {
174 f.focused = focused
175}
176
177// AssistantInfoID returns a stable ID for assistant info items.
178func AssistantInfoID(messageID string) string {
179 return fmt.Sprintf("%s:assistant-info", messageID)
180}
181
182// AssistantInfoItem renders model info and response time after assistant completes.
183type AssistantInfoItem struct {
184 *cachedMessageItem
185
186 id string
187 message *message.Message
188 sty *styles.Styles
189 cfg *config.Config
190 lastUserMessageTime time.Time
191}
192
193// NewAssistantInfoItem creates a new AssistantInfoItem.
194func NewAssistantInfoItem(sty *styles.Styles, message *message.Message, cfg *config.Config, lastUserMessageTime time.Time) MessageItem {
195 return &AssistantInfoItem{
196 cachedMessageItem: &cachedMessageItem{},
197 id: AssistantInfoID(message.ID),
198 message: message,
199 sty: sty,
200 cfg: cfg,
201 lastUserMessageTime: lastUserMessageTime,
202 }
203}
204
205// ID implements MessageItem.
206func (a *AssistantInfoItem) ID() string {
207 return a.id
208}
209
210// RawRender implements MessageItem.
211func (a *AssistantInfoItem) RawRender(width int) string {
212 innerWidth := max(0, width-MessageLeftPaddingTotal)
213 content, _, ok := a.getCachedRender(innerWidth)
214 if !ok {
215 content = a.renderContent(innerWidth)
216 height := lipgloss.Height(content)
217 a.setCachedRender(content, innerWidth, height)
218 }
219 return content
220}
221
222// Render implements MessageItem.
223func (a *AssistantInfoItem) Render(width int) string {
224 return a.sty.Chat.Message.SectionHeader.Render(a.RawRender(width))
225}
226
227func (a *AssistantInfoItem) renderContent(width int) string {
228 finishData := a.message.FinishPart()
229 if finishData == nil {
230 return ""
231 }
232 finishTime := time.Unix(finishData.Time, 0)
233 duration := finishTime.Sub(a.lastUserMessageTime)
234 infoMsg := a.sty.Chat.Message.AssistantInfoDuration.Render(duration.String())
235 icon := a.sty.Chat.Message.AssistantInfoIcon.Render(styles.ModelIcon)
236 model := a.cfg.GetModel(a.message.Provider, a.message.Model)
237 if model == nil {
238 model = &catwalk.Model{Name: "Unknown Model"}
239 }
240 modelFormatted := a.sty.Chat.Message.AssistantInfoModel.Render(model.Name)
241 providerName := a.message.Provider
242 if providerConfig, ok := a.cfg.Providers.Get(a.message.Provider); ok {
243 providerName = providerConfig.Name
244 }
245 provider := a.sty.Chat.Message.AssistantInfoProvider.Render(fmt.Sprintf("via %s", providerName))
246 assistant := fmt.Sprintf("%s %s %s %s", icon, modelFormatted, provider, infoMsg)
247 return common.Section(a.sty, assistant, width)
248}
249
250// cappedMessageWidth returns the maximum width for message content for readability.
251func cappedMessageWidth(availableWidth int) int {
252 return min(availableWidth-MessageLeftPaddingTotal, maxTextWidth)
253}
254
255// ExtractMessageItems extracts [MessageItem]s from a [message.Message]. It
256// returns all parts of the message as [MessageItem]s.
257//
258// For assistant messages with tool calls, pass a toolResults map to link results.
259// Use BuildToolResultMap to create this map from all messages in a session.
260func ExtractMessageItems(sty *styles.Styles, msg *message.Message, toolResults map[string]message.ToolResult) []MessageItem {
261 switch msg.Role {
262 case message.User:
263 r := attachments.NewRenderer(
264 sty.Attachments.Normal,
265 sty.Attachments.Deleting,
266 sty.Attachments.Image,
267 sty.Attachments.Text,
268 )
269 return []MessageItem{NewUserMessageItem(sty, msg, r)}
270 case message.Assistant:
271 var items []MessageItem
272 if ShouldRenderAssistantMessage(msg) {
273 items = append(items, NewAssistantMessageItem(sty, msg))
274 }
275 for _, tc := range msg.ToolCalls() {
276 var result *message.ToolResult
277 if tr, ok := toolResults[tc.ID]; ok {
278 result = &tr
279 }
280 items = append(items, NewToolMessageItem(
281 sty,
282 msg.ID,
283 tc,
284 result,
285 msg.FinishReason() == message.FinishReasonCanceled,
286 ))
287 }
288 return items
289 }
290 return []MessageItem{}
291}
292
293// ShouldRenderAssistantMessage determines if an assistant message should be rendered
294//
295// In some cases the assistant message only has tools so we do not want to render an
296// empty message.
297func ShouldRenderAssistantMessage(msg *message.Message) bool {
298 content := strings.TrimSpace(msg.Content().Text)
299 thinking := strings.TrimSpace(msg.ReasoningContent().Thinking)
300 isError := msg.FinishReason() == message.FinishReasonError
301 isCancelled := msg.FinishReason() == message.FinishReasonCanceled
302 hasToolCalls := len(msg.ToolCalls()) > 0
303 return !hasToolCalls || content != "" || thinking != "" || msg.IsThinking() || isError || isCancelled
304}
305
306// BuildToolResultMap creates a map of tool call IDs to their results from a list of messages.
307// Tool result messages (role == message.Tool) contain the results that should be linked
308// to tool calls in assistant messages.
309func BuildToolResultMap(messages []*message.Message) map[string]message.ToolResult {
310 resultMap := make(map[string]message.ToolResult)
311 for _, msg := range messages {
312 if msg.Role == message.Tool {
313 for _, result := range msg.ToolResults() {
314 if result.ToolCallID != "" {
315 resultMap[result.ToolCallID] = result
316 }
317 }
318 }
319 }
320 return resultMap
321}