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