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 lastUserMessageTime time.Time
190}
191
192// NewAssistantInfoItem creates a new AssistantInfoItem.
193func NewAssistantInfoItem(sty *styles.Styles, message *message.Message, lastUserMessageTime time.Time) MessageItem {
194 return &AssistantInfoItem{
195 cachedMessageItem: &cachedMessageItem{},
196 id: AssistantInfoID(message.ID),
197 message: message,
198 sty: sty,
199 lastUserMessageTime: lastUserMessageTime,
200 }
201}
202
203// ID implements MessageItem.
204func (a *AssistantInfoItem) ID() string {
205 return a.id
206}
207
208// RawRender implements MessageItem.
209func (a *AssistantInfoItem) RawRender(width int) string {
210 innerWidth := max(0, width-MessageLeftPaddingTotal)
211 content, _, ok := a.getCachedRender(innerWidth)
212 if !ok {
213 content = a.renderContent(innerWidth)
214 height := lipgloss.Height(content)
215 a.setCachedRender(content, innerWidth, height)
216 }
217 return content
218}
219
220// Render implements MessageItem.
221func (a *AssistantInfoItem) Render(width int) string {
222 return a.sty.Chat.Message.SectionHeader.Render(a.RawRender(width))
223}
224
225func (a *AssistantInfoItem) renderContent(width int) string {
226 finishData := a.message.FinishPart()
227 if finishData == nil {
228 return ""
229 }
230 finishTime := time.Unix(finishData.Time, 0)
231 duration := finishTime.Sub(a.lastUserMessageTime)
232 infoMsg := a.sty.Chat.Message.AssistantInfoDuration.Render(duration.String())
233 icon := a.sty.Chat.Message.AssistantInfoIcon.Render(styles.ModelIcon)
234 model := config.Get().GetModel(a.message.Provider, a.message.Model)
235 if model == nil {
236 model = &catwalk.Model{Name: "Unknown Model"}
237 }
238 modelFormatted := a.sty.Chat.Message.AssistantInfoModel.Render(model.Name)
239 providerName := a.message.Provider
240 if providerConfig, ok := config.Get().Providers.Get(a.message.Provider); ok {
241 providerName = providerConfig.Name
242 }
243 provider := a.sty.Chat.Message.AssistantInfoProvider.Render(fmt.Sprintf("via %s", providerName))
244 assistant := fmt.Sprintf("%s %s %s %s", icon, modelFormatted, provider, infoMsg)
245 return common.Section(a.sty, assistant, width)
246}
247
248// cappedMessageWidth returns the maximum width for message content for readability.
249func cappedMessageWidth(availableWidth int) int {
250 return min(availableWidth-MessageLeftPaddingTotal, maxTextWidth)
251}
252
253// ExtractMessageItems extracts [MessageItem]s from a [message.Message]. It
254// returns all parts of the message as [MessageItem]s.
255//
256// For assistant messages with tool calls, pass a toolResults map to link results.
257// Use BuildToolResultMap to create this map from all messages in a session.
258func ExtractMessageItems(sty *styles.Styles, msg *message.Message, toolResults map[string]message.ToolResult) []MessageItem {
259 switch msg.Role {
260 case message.User:
261 r := attachments.NewRenderer(
262 sty.Attachments.Normal,
263 sty.Attachments.Deleting,
264 sty.Attachments.Image,
265 sty.Attachments.Text,
266 )
267 return []MessageItem{NewUserMessageItem(sty, msg, r)}
268 case message.Assistant:
269 var items []MessageItem
270 if ShouldRenderAssistantMessage(msg) {
271 items = append(items, NewAssistantMessageItem(sty, msg))
272 }
273 for _, tc := range msg.ToolCalls() {
274 var result *message.ToolResult
275 if tr, ok := toolResults[tc.ID]; ok {
276 result = &tr
277 }
278 items = append(items, NewToolMessageItem(
279 sty,
280 msg.ID,
281 tc,
282 result,
283 msg.FinishReason() == message.FinishReasonCanceled,
284 ))
285 }
286 return items
287 }
288 return []MessageItem{}
289}
290
291// ShouldRenderAssistantMessage determines if an assistant message should be rendered
292//
293// In some cases the assistant message only has tools so we do not want to render an
294// empty message.
295func ShouldRenderAssistantMessage(msg *message.Message) bool {
296 content := strings.TrimSpace(msg.Content().Text)
297 thinking := strings.TrimSpace(msg.ReasoningContent().Thinking)
298 isError := msg.FinishReason() == message.FinishReasonError
299 isCancelled := msg.FinishReason() == message.FinishReasonCanceled
300 hasToolCalls := len(msg.ToolCalls()) > 0
301 return !hasToolCalls || content != "" || thinking != "" || msg.IsThinking() || isError || isCancelled
302}
303
304// BuildToolResultMap creates a map of tool call IDs to their results from a list of messages.
305// Tool result messages (role == message.Tool) contain the results that should be linked
306// to tool calls in assistant messages.
307func BuildToolResultMap(messages []*message.Message) map[string]message.ToolResult {
308 resultMap := make(map[string]message.ToolResult)
309 for _, msg := range messages {
310 if msg.Role == message.Tool {
311 for _, result := range msg.ToolResults() {
312 if result.ToolCallID != "" {
313 resultMap[result.ToolCallID] = result
314 }
315 }
316 }
317 }
318 return resultMap
319}