chat.go

  1package chat
  2
  3import (
  4	"context"
  5	"strings"
  6	"time"
  7
  8	"github.com/atotto/clipboard"
  9	"github.com/charmbracelet/bubbles/v2/key"
 10	tea "github.com/charmbracelet/bubbletea/v2"
 11	"github.com/charmbracelet/crush/internal/agent"
 12	"github.com/charmbracelet/crush/internal/app"
 13	"github.com/charmbracelet/crush/internal/message"
 14	"github.com/charmbracelet/crush/internal/permission"
 15	"github.com/charmbracelet/crush/internal/pubsub"
 16	"github.com/charmbracelet/crush/internal/session"
 17	"github.com/charmbracelet/crush/internal/tui/components/chat/messages"
 18	"github.com/charmbracelet/crush/internal/tui/components/core/layout"
 19	"github.com/charmbracelet/crush/internal/tui/exp/list"
 20	"github.com/charmbracelet/crush/internal/tui/styles"
 21	"github.com/charmbracelet/crush/internal/tui/util"
 22)
 23
 24type SendMsg struct {
 25	Text        string
 26	Attachments []message.Attachment
 27}
 28
 29type SessionSelectedMsg = session.Session
 30
 31type SessionClearedMsg struct{}
 32
 33type SelectionCopyMsg struct {
 34	clickCount   int
 35	endSelection bool
 36	x, y         int
 37}
 38
 39const (
 40	NotFound = -1
 41)
 42
 43// MessageListCmp represents a component that displays a list of chat messages
 44// with support for real-time updates and session management.
 45type MessageListCmp interface {
 46	util.Model
 47	layout.Sizeable
 48	layout.Focusable
 49	layout.Help
 50
 51	SetSession(session.Session) tea.Cmd
 52	GoToBottom() tea.Cmd
 53	GetSelectedText() string
 54	CopySelectedText(bool) tea.Cmd
 55}
 56
 57// messageListCmp implements MessageListCmp, providing a virtualized list
 58// of chat messages with support for tool calls, real-time updates, and
 59// session switching.
 60type messageListCmp struct {
 61	app              *app.App
 62	width, height    int
 63	session          session.Session
 64	listCmp          list.List[list.Item]
 65	previousSelected string // Last selected item index for restoring focus
 66
 67	lastUserMessageTime int64
 68	defaultListKeyMap   list.KeyMap
 69
 70	// Click tracking for double/triple click detection
 71	lastClickTime time.Time
 72	lastClickX    int
 73	lastClickY    int
 74	clickCount    int
 75	promptQueue   int
 76}
 77
 78// New creates a new message list component with custom keybindings
 79// and reverse ordering (newest messages at bottom).
 80func New(app *app.App) MessageListCmp {
 81	defaultListKeyMap := list.DefaultKeyMap()
 82	listCmp := list.New(
 83		[]list.Item{},
 84		list.WithGap(1),
 85		list.WithDirectionBackward(),
 86		list.WithFocus(false),
 87		list.WithKeyMap(defaultListKeyMap),
 88		list.WithEnableMouse(),
 89	)
 90	return &messageListCmp{
 91		app:               app,
 92		listCmp:           listCmp,
 93		previousSelected:  "",
 94		defaultListKeyMap: defaultListKeyMap,
 95	}
 96}
 97
 98// Init initializes the component.
 99func (m *messageListCmp) Init() tea.Cmd {
100	return m.listCmp.Init()
101}
102
103// Update handles incoming messages and updates the component state.
104func (m *messageListCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
105	var cmds []tea.Cmd
106	if m.session.ID != "" && m.app.AgentCoordinator != nil {
107		queueSize := m.app.AgentCoordinator.QueuedPrompts(m.session.ID)
108		if queueSize != m.promptQueue {
109			m.promptQueue = queueSize
110			cmds = append(cmds, m.SetSize(m.width, m.height))
111		}
112	}
113	switch msg := msg.(type) {
114	case tea.KeyPressMsg:
115		if m.listCmp.IsFocused() && m.listCmp.HasSelection() {
116			switch {
117			case key.Matches(msg, messages.CopyKey):
118				cmds = append(cmds, m.CopySelectedText(true))
119				return m, tea.Batch(cmds...)
120			case key.Matches(msg, messages.ClearSelectionKey):
121				cmds = append(cmds, m.SelectionClear())
122				return m, tea.Batch(cmds...)
123			}
124		}
125	case tea.MouseClickMsg:
126		x := msg.X - 1 // Adjust for padding
127		y := msg.Y - 1 // Adjust for padding
128		if x < 0 || y < 0 || x >= m.width-2 || y >= m.height-1 {
129			return m, nil // Ignore clicks outside the component
130		}
131		if msg.Button == tea.MouseLeft {
132			cmds = append(cmds, m.handleMouseClick(x, y))
133			return m, tea.Batch(cmds...)
134		}
135		return m, tea.Batch(cmds...)
136	case tea.MouseMotionMsg:
137		x := msg.X - 1 // Adjust for padding
138		y := msg.Y - 1 // Adjust for padding
139		if x < 0 || y < 0 || x >= m.width-2 || y >= m.height-1 {
140			if y < 0 {
141				cmds = append(cmds, m.listCmp.MoveUp(1))
142				return m, tea.Batch(cmds...)
143			}
144			if y >= m.height-1 {
145				cmds = append(cmds, m.listCmp.MoveDown(1))
146				return m, tea.Batch(cmds...)
147			}
148			return m, nil // Ignore clicks outside the component
149		}
150		if msg.Button == tea.MouseLeft {
151			m.listCmp.EndSelection(x, y)
152		}
153		return m, tea.Batch(cmds...)
154	case tea.MouseReleaseMsg:
155		x := msg.X - 1 // Adjust for padding
156		y := msg.Y - 1 // Adjust for padding
157		if msg.Button == tea.MouseLeft {
158			clickCount := m.clickCount
159			if x < 0 || y < 0 || x >= m.width-2 || y >= m.height-1 {
160				tick := tea.Tick(doubleClickThreshold, func(time.Time) tea.Msg {
161					return SelectionCopyMsg{
162						clickCount:   clickCount,
163						endSelection: false,
164					}
165				})
166
167				cmds = append(cmds, tick)
168				return m, tea.Batch(cmds...)
169			}
170			tick := tea.Tick(doubleClickThreshold, func(time.Time) tea.Msg {
171				return SelectionCopyMsg{
172					clickCount:   clickCount,
173					endSelection: true,
174					x:            x,
175					y:            y,
176				}
177			})
178			cmds = append(cmds, tick)
179			return m, tea.Batch(cmds...)
180		}
181		return m, nil
182	case SelectionCopyMsg:
183		if msg.clickCount == m.clickCount && time.Since(m.lastClickTime) >= doubleClickThreshold {
184			// If the click count matches and within threshold, copy selected text
185			if msg.endSelection {
186				m.listCmp.EndSelection(msg.x, msg.y)
187			}
188			m.listCmp.SelectionStop()
189			cmds = append(cmds, m.CopySelectedText(true))
190			return m, tea.Batch(cmds...)
191		}
192	case pubsub.Event[permission.PermissionNotification]:
193		cmds = append(cmds, m.handlePermissionRequest(msg.Payload))
194		return m, tea.Batch(cmds...)
195	case SessionSelectedMsg:
196		if msg.ID != m.session.ID {
197			cmds = append(cmds, m.SetSession(msg))
198		}
199		return m, tea.Batch(cmds...)
200	case SessionClearedMsg:
201		m.session = session.Session{}
202		cmds = append(cmds, m.listCmp.SetItems([]list.Item{}))
203		return m, tea.Batch(cmds...)
204
205	case pubsub.Event[message.Message]:
206		cmds = append(cmds, m.handleMessageEvent(msg))
207		return m, tea.Batch(cmds...)
208
209	case tea.MouseWheelMsg:
210		u, cmd := m.listCmp.Update(msg)
211		m.listCmp = u.(list.List[list.Item])
212		cmds = append(cmds, cmd)
213		return m, tea.Batch(cmds...)
214	}
215
216	u, cmd := m.listCmp.Update(msg)
217	m.listCmp = u.(list.List[list.Item])
218	cmds = append(cmds, cmd)
219	return m, tea.Batch(cmds...)
220}
221
222// View renders the message list or an initial screen if empty.
223func (m *messageListCmp) View() string {
224	t := styles.CurrentTheme()
225	height := m.height
226	if m.promptQueue > 0 {
227		height -= 4 // pill height and padding
228	}
229	view := []string{
230		t.S().Base.
231			Padding(1, 1, 0, 1).
232			Width(m.width).
233			Height(height).
234			Render(
235				m.listCmp.View(),
236			),
237	}
238	if m.app.AgentCoordinator != nil && m.promptQueue > 0 {
239		queuePill := queuePill(m.promptQueue, t)
240		view = append(view, t.S().Base.PaddingLeft(4).PaddingTop(1).Render(queuePill))
241	}
242	return strings.Join(view, "\n")
243}
244
245func (m *messageListCmp) handlePermissionRequest(permission permission.PermissionNotification) tea.Cmd {
246	items := m.listCmp.Items()
247	if toolCallIndex := m.findToolCallByID(items, permission.ToolCallID); toolCallIndex != NotFound {
248		toolCall := items[toolCallIndex].(messages.ToolCallCmp)
249		toolCall.SetPermissionRequested()
250		if permission.Granted {
251			toolCall.SetPermissionGranted()
252		}
253		m.listCmp.UpdateItem(toolCall.ID(), toolCall)
254	}
255	return nil
256}
257
258// handleChildSession handles messages from child sessions (agent tools).
259func (m *messageListCmp) handleChildSession(event pubsub.Event[message.Message]) tea.Cmd {
260	var cmds []tea.Cmd
261	if len(event.Payload.ToolCalls()) == 0 && len(event.Payload.ToolResults()) == 0 {
262		return nil
263	}
264
265	// Check if this is an agent tool session and parse it
266	childSessionID := event.Payload.SessionID
267	parentMessageID, toolCallID, ok := m.app.Sessions.ParseAgentToolSessionID(childSessionID)
268	if !ok {
269		return nil
270	}
271	items := m.listCmp.Items()
272	toolCallInx := NotFound
273	var toolCall messages.ToolCallCmp
274	for i := len(items) - 1; i >= 0; i-- {
275		if msg, ok := items[i].(messages.ToolCallCmp); ok {
276			if msg.ParentMessageID() == parentMessageID && msg.GetToolCall().ID == toolCallID {
277				toolCallInx = i
278				toolCall = msg
279			}
280		}
281	}
282	if toolCallInx == NotFound {
283		return nil
284	}
285	nestedToolCalls := toolCall.GetNestedToolCalls()
286	for _, tc := range event.Payload.ToolCalls() {
287		found := false
288		for existingInx, existingTC := range nestedToolCalls {
289			if existingTC.GetToolCall().ID == tc.ID {
290				nestedToolCalls[existingInx].SetToolCall(tc)
291				found = true
292				break
293			}
294		}
295		if !found {
296			nestedCall := messages.NewToolCallCmp(
297				event.Payload.ID,
298				tc,
299				m.app.Permissions,
300				messages.WithToolCallNested(true),
301			)
302			cmds = append(cmds, nestedCall.Init())
303			nestedToolCalls = append(
304				nestedToolCalls,
305				nestedCall,
306			)
307		}
308	}
309	for _, tr := range event.Payload.ToolResults() {
310		for nestedInx, nestedTC := range nestedToolCalls {
311			if nestedTC.GetToolCall().ID == tr.ToolCallID {
312				nestedToolCalls[nestedInx].SetToolResult(tr)
313				break
314			}
315		}
316	}
317
318	toolCall.SetNestedToolCalls(nestedToolCalls)
319	m.listCmp.UpdateItem(
320		toolCall.ID(),
321		toolCall,
322	)
323	return tea.Batch(cmds...)
324}
325
326// handleMessageEvent processes different types of message events (created/updated).
327func (m *messageListCmp) handleMessageEvent(event pubsub.Event[message.Message]) tea.Cmd {
328	switch event.Type {
329	case pubsub.CreatedEvent:
330		if event.Payload.SessionID != m.session.ID {
331			return m.handleChildSession(event)
332		}
333		if m.messageExists(event.Payload.ID) {
334			return nil
335		}
336		return m.handleNewMessage(event.Payload)
337	case pubsub.UpdatedEvent:
338		if event.Payload.SessionID != m.session.ID {
339			return m.handleChildSession(event)
340		}
341		switch event.Payload.Role {
342		case message.Assistant:
343			return m.handleUpdateAssistantMessage(event.Payload)
344		case message.Tool:
345			return m.handleToolMessage(event.Payload)
346		}
347	}
348	return nil
349}
350
351// messageExists checks if a message with the given ID already exists in the list.
352func (m *messageListCmp) messageExists(messageID string) bool {
353	items := m.listCmp.Items()
354	// Search backwards as new messages are more likely to be at the end
355	for i := len(items) - 1; i >= 0; i-- {
356		if msg, ok := items[i].(messages.MessageCmp); ok && msg.GetMessage().ID == messageID {
357			return true
358		}
359	}
360	return false
361}
362
363// handleNewMessage routes new messages to appropriate handlers based on role.
364func (m *messageListCmp) handleNewMessage(msg message.Message) tea.Cmd {
365	switch msg.Role {
366	case message.User:
367		return m.handleNewUserMessage(msg)
368	case message.Assistant:
369		return m.handleNewAssistantMessage(msg)
370	case message.Tool:
371		return m.handleToolMessage(msg)
372	}
373	return nil
374}
375
376// handleNewUserMessage adds a new user message to the list and updates the timestamp.
377func (m *messageListCmp) handleNewUserMessage(msg message.Message) tea.Cmd {
378	m.lastUserMessageTime = msg.CreatedAt
379	return m.listCmp.AppendItem(messages.NewMessageCmp(msg))
380}
381
382// handleToolMessage updates existing tool calls with their results.
383func (m *messageListCmp) handleToolMessage(msg message.Message) tea.Cmd {
384	items := m.listCmp.Items()
385	for _, tr := range msg.ToolResults() {
386		if toolCallIndex := m.findToolCallByID(items, tr.ToolCallID); toolCallIndex != NotFound {
387			toolCall := items[toolCallIndex].(messages.ToolCallCmp)
388			toolCall.SetToolResult(tr)
389			m.listCmp.UpdateItem(toolCall.ID(), toolCall)
390		}
391	}
392	return nil
393}
394
395// findToolCallByID searches for a tool call with the specified ID.
396// Returns the index if found, NotFound otherwise.
397func (m *messageListCmp) findToolCallByID(items []list.Item, toolCallID string) int {
398	// Search backwards as tool calls are more likely to be recent
399	for i := len(items) - 1; i >= 0; i-- {
400		if toolCall, ok := items[i].(messages.ToolCallCmp); ok && toolCall.GetToolCall().ID == toolCallID {
401			return i
402		}
403	}
404	return NotFound
405}
406
407// handleUpdateAssistantMessage processes updates to assistant messages,
408// managing both message content and associated tool calls.
409func (m *messageListCmp) handleUpdateAssistantMessage(msg message.Message) tea.Cmd {
410	var cmds []tea.Cmd
411	items := m.listCmp.Items()
412
413	// Find existing assistant message and tool calls for this message
414	assistantIndex, existingToolCalls := m.findAssistantMessageAndToolCalls(items, msg.ID)
415
416	// Handle assistant message content
417	if cmd := m.updateAssistantMessageContent(msg, assistantIndex); cmd != nil {
418		cmds = append(cmds, cmd)
419	}
420
421	// Handle tool calls
422	if cmd := m.updateToolCalls(msg, existingToolCalls); cmd != nil {
423		cmds = append(cmds, cmd)
424	}
425
426	return tea.Batch(cmds...)
427}
428
429// findAssistantMessageAndToolCalls locates the assistant message and its tool calls.
430func (m *messageListCmp) findAssistantMessageAndToolCalls(items []list.Item, messageID string) (int, map[int]messages.ToolCallCmp) {
431	assistantIndex := NotFound
432	toolCalls := make(map[int]messages.ToolCallCmp)
433
434	// Search backwards as messages are more likely to be at the end
435	for i := len(items) - 1; i >= 0; i-- {
436		item := items[i]
437		if asMsg, ok := item.(messages.MessageCmp); ok {
438			if asMsg.GetMessage().ID == messageID {
439				assistantIndex = i
440			}
441		} else if tc, ok := item.(messages.ToolCallCmp); ok {
442			if tc.ParentMessageID() == messageID {
443				toolCalls[i] = tc
444			}
445		}
446	}
447
448	return assistantIndex, toolCalls
449}
450
451// updateAssistantMessageContent updates or removes the assistant message based on content.
452func (m *messageListCmp) updateAssistantMessageContent(msg message.Message, assistantIndex int) tea.Cmd {
453	if assistantIndex == NotFound {
454		return nil
455	}
456
457	shouldShowMessage := m.shouldShowAssistantMessage(msg)
458	hasToolCallsOnly := len(msg.ToolCalls()) > 0 && msg.Content().Text == ""
459
460	var cmd tea.Cmd
461	if shouldShowMessage {
462		items := m.listCmp.Items()
463		uiMsg := items[assistantIndex].(messages.MessageCmp)
464		uiMsg.SetMessage(msg)
465		m.listCmp.UpdateItem(
466			items[assistantIndex].ID(),
467			uiMsg,
468		)
469		if msg.FinishPart() != nil && msg.FinishPart().Reason == message.FinishReasonEndTurn {
470			m.listCmp.AppendItem(
471				messages.NewAssistantSection(
472					msg,
473					time.Unix(m.lastUserMessageTime, 0),
474				),
475			)
476		}
477	} else if hasToolCallsOnly {
478		items := m.listCmp.Items()
479		m.listCmp.DeleteItem(items[assistantIndex].ID())
480	}
481
482	return cmd
483}
484
485// shouldShowAssistantMessage determines if an assistant message should be displayed.
486func (m *messageListCmp) shouldShowAssistantMessage(msg message.Message) bool {
487	return len(msg.ToolCalls()) == 0 || msg.Content().Text != "" || msg.ReasoningContent().Thinking != "" || msg.IsThinking()
488}
489
490// updateToolCalls handles updates to tool calls, updating existing ones and adding new ones.
491func (m *messageListCmp) updateToolCalls(msg message.Message, existingToolCalls map[int]messages.ToolCallCmp) tea.Cmd {
492	var cmds []tea.Cmd
493
494	for _, tc := range msg.ToolCalls() {
495		if cmd := m.updateOrAddToolCall(msg, tc, existingToolCalls); cmd != nil {
496			cmds = append(cmds, cmd)
497		}
498	}
499
500	return tea.Batch(cmds...)
501}
502
503// updateOrAddToolCall updates an existing tool call or adds a new one.
504func (m *messageListCmp) updateOrAddToolCall(msg message.Message, tc message.ToolCall, existingToolCalls map[int]messages.ToolCallCmp) tea.Cmd {
505	// Try to find existing tool call
506	for _, existingTC := range existingToolCalls {
507		if tc.ID == existingTC.GetToolCall().ID {
508			existingTC.SetToolCall(tc)
509			if msg.FinishPart() != nil && msg.FinishPart().Reason == message.FinishReasonCanceled {
510				existingTC.SetCancelled()
511			}
512			m.listCmp.UpdateItem(tc.ID, existingTC)
513			return nil
514		}
515	}
516
517	// Add new tool call if not found
518	return m.listCmp.AppendItem(messages.NewToolCallCmp(msg.ID, tc, m.app.Permissions))
519}
520
521// handleNewAssistantMessage processes new assistant messages and their tool calls.
522func (m *messageListCmp) handleNewAssistantMessage(msg message.Message) tea.Cmd {
523	var cmds []tea.Cmd
524
525	// Add assistant message if it should be displayed
526	if m.shouldShowAssistantMessage(msg) {
527		cmd := m.listCmp.AppendItem(
528			messages.NewMessageCmp(
529				msg,
530			),
531		)
532		cmds = append(cmds, cmd)
533	}
534
535	// Add tool calls
536	for _, tc := range msg.ToolCalls() {
537		cmd := m.listCmp.AppendItem(messages.NewToolCallCmp(msg.ID, tc, m.app.Permissions))
538		cmds = append(cmds, cmd)
539	}
540
541	return tea.Batch(cmds...)
542}
543
544// SetSession loads and displays messages for a new session.
545func (m *messageListCmp) SetSession(session session.Session) tea.Cmd {
546	if m.session.ID == session.ID {
547		return nil
548	}
549
550	m.session = session
551	sessionMessages, err := m.app.Messages.List(context.Background(), session.ID)
552	if err != nil {
553		return util.ReportError(err)
554	}
555
556	if len(sessionMessages) == 0 {
557		return m.listCmp.SetItems([]list.Item{})
558	}
559
560	// Initialize with first message timestamp
561	m.lastUserMessageTime = sessionMessages[0].CreatedAt
562
563	// Build tool result map for efficient lookup
564	toolResultMap := m.buildToolResultMap(sessionMessages)
565
566	// Convert messages to UI components
567	uiMessages := m.convertMessagesToUI(sessionMessages, toolResultMap)
568
569	return m.listCmp.SetItems(uiMessages)
570}
571
572// buildToolResultMap creates a map of tool call ID to tool result for efficient lookup.
573func (m *messageListCmp) buildToolResultMap(messages []message.Message) map[string]message.ToolResult {
574	toolResultMap := make(map[string]message.ToolResult)
575	for _, msg := range messages {
576		for _, tr := range msg.ToolResults() {
577			toolResultMap[tr.ToolCallID] = tr
578		}
579	}
580	return toolResultMap
581}
582
583// convertMessagesToUI converts database messages to UI components.
584func (m *messageListCmp) convertMessagesToUI(sessionMessages []message.Message, toolResultMap map[string]message.ToolResult) []list.Item {
585	uiMessages := make([]list.Item, 0)
586
587	for _, msg := range sessionMessages {
588		switch msg.Role {
589		case message.User:
590			m.lastUserMessageTime = msg.CreatedAt
591			uiMessages = append(uiMessages, messages.NewMessageCmp(msg))
592		case message.Assistant:
593			uiMessages = append(uiMessages, m.convertAssistantMessage(msg, toolResultMap)...)
594			if msg.FinishPart() != nil && msg.FinishPart().Reason == message.FinishReasonEndTurn {
595				uiMessages = append(uiMessages, messages.NewAssistantSection(msg, time.Unix(m.lastUserMessageTime, 0)))
596			}
597		}
598	}
599
600	return uiMessages
601}
602
603// convertAssistantMessage converts an assistant message and its tool calls to UI components.
604func (m *messageListCmp) convertAssistantMessage(msg message.Message, toolResultMap map[string]message.ToolResult) []list.Item {
605	var uiMessages []list.Item
606
607	// Add assistant message if it should be displayed
608	if m.shouldShowAssistantMessage(msg) {
609		uiMessages = append(
610			uiMessages,
611			messages.NewMessageCmp(
612				msg,
613			),
614		)
615	}
616
617	// Add tool calls with their results and status
618	for _, tc := range msg.ToolCalls() {
619		options := m.buildToolCallOptions(tc, msg, toolResultMap)
620		uiMessages = append(uiMessages, messages.NewToolCallCmp(msg.ID, tc, m.app.Permissions, options...))
621		// If this tool call is the agent tool, fetch nested tool calls
622		if tc.Name == agent.AgentToolName {
623			agentToolSessionID := m.app.Sessions.CreateAgentToolSessionID(msg.ID, tc.ID)
624			nestedMessages, _ := m.app.Messages.List(context.Background(), agentToolSessionID)
625			nestedToolResultMap := m.buildToolResultMap(nestedMessages)
626			nestedUIMessages := m.convertMessagesToUI(nestedMessages, nestedToolResultMap)
627			nestedToolCalls := make([]messages.ToolCallCmp, 0, len(nestedUIMessages))
628			for _, nestedMsg := range nestedUIMessages {
629				if toolCall, ok := nestedMsg.(messages.ToolCallCmp); ok {
630					toolCall.SetIsNested(true)
631					nestedToolCalls = append(nestedToolCalls, toolCall)
632				}
633			}
634			uiMessages[len(uiMessages)-1].(messages.ToolCallCmp).SetNestedToolCalls(nestedToolCalls)
635		}
636	}
637
638	return uiMessages
639}
640
641// buildToolCallOptions creates options for tool call components based on results and status.
642func (m *messageListCmp) buildToolCallOptions(tc message.ToolCall, msg message.Message, toolResultMap map[string]message.ToolResult) []messages.ToolCallOption {
643	var options []messages.ToolCallOption
644
645	// Add tool result if available
646	if tr, ok := toolResultMap[tc.ID]; ok {
647		options = append(options, messages.WithToolCallResult(tr))
648	}
649
650	// Add cancelled status if applicable
651	if msg.FinishPart() != nil && msg.FinishPart().Reason == message.FinishReasonCanceled {
652		options = append(options, messages.WithToolCallCancelled())
653	}
654
655	return options
656}
657
658// GetSize returns the current width and height of the component.
659func (m *messageListCmp) GetSize() (int, int) {
660	return m.width, m.height
661}
662
663// SetSize updates the component dimensions and propagates to the list component.
664func (m *messageListCmp) SetSize(width int, height int) tea.Cmd {
665	m.width = width
666	m.height = height
667	if m.promptQueue > 0 {
668		queueHeight := 3 + 1 // 1 for padding top
669		lHight := max(0, height-(1+queueHeight))
670		return m.listCmp.SetSize(width-2, lHight)
671	}
672	return m.listCmp.SetSize(width-2, max(0, height-1)) // for padding
673}
674
675// Blur implements MessageListCmp.
676func (m *messageListCmp) Blur() tea.Cmd {
677	return m.listCmp.Blur()
678}
679
680// Focus implements MessageListCmp.
681func (m *messageListCmp) Focus() tea.Cmd {
682	return m.listCmp.Focus()
683}
684
685// IsFocused implements MessageListCmp.
686func (m *messageListCmp) IsFocused() bool {
687	return m.listCmp.IsFocused()
688}
689
690func (m *messageListCmp) Bindings() []key.Binding {
691	return m.defaultListKeyMap.KeyBindings()
692}
693
694func (m *messageListCmp) GoToBottom() tea.Cmd {
695	return m.listCmp.GoToBottom()
696}
697
698const (
699	doubleClickThreshold = 500 * time.Millisecond
700	clickTolerance       = 2 // pixels
701)
702
703// handleMouseClick handles mouse click events and detects double/triple clicks.
704func (m *messageListCmp) handleMouseClick(x, y int) tea.Cmd {
705	now := time.Now()
706
707	// Check if this is a potential multi-click
708	if now.Sub(m.lastClickTime) <= doubleClickThreshold &&
709		abs(x-m.lastClickX) <= clickTolerance &&
710		abs(y-m.lastClickY) <= clickTolerance {
711		m.clickCount++
712	} else {
713		m.clickCount = 1
714	}
715
716	m.lastClickTime = now
717	m.lastClickX = x
718	m.lastClickY = y
719
720	switch m.clickCount {
721	case 1:
722		// Single click - start selection
723		m.listCmp.StartSelection(x, y)
724	case 2:
725		// Double click - select word
726		m.listCmp.SelectWord(x, y)
727	case 3:
728		// Triple click - select paragraph
729		m.listCmp.SelectParagraph(x, y)
730		m.clickCount = 0 // Reset after triple click
731	}
732
733	return nil
734}
735
736// SelectionClear clears the current selection in the list component.
737func (m *messageListCmp) SelectionClear() tea.Cmd {
738	m.listCmp.SelectionClear()
739	m.previousSelected = ""
740	m.lastClickX, m.lastClickY = 0, 0
741	m.lastClickTime = time.Time{}
742	m.clickCount = 0
743	return nil
744}
745
746// HasSelection checks if there is a selection in the list component.
747func (m *messageListCmp) HasSelection() bool {
748	return m.listCmp.HasSelection()
749}
750
751// GetSelectedText returns the currently selected text from the list component.
752func (m *messageListCmp) GetSelectedText() string {
753	return m.listCmp.GetSelectedText(3) // 3 padding for the left border/padding
754}
755
756// CopySelectedText copies the currently selected text to the clipboard. When
757// clear is true, it clears the selection after copying.
758func (m *messageListCmp) CopySelectedText(clear bool) tea.Cmd {
759	if !m.listCmp.HasSelection() {
760		return nil
761	}
762
763	selectedText := m.GetSelectedText()
764	if selectedText == "" {
765		return util.ReportInfo("No text selected")
766	}
767
768	if clear {
769		defer func() { m.SelectionClear() }()
770	}
771
772	return tea.Sequence(
773		// We use both OSC 52 and native clipboard for compatibility with different
774		// terminal emulators and environments.
775		tea.SetClipboard(selectedText),
776		func() tea.Msg {
777			_ = clipboard.WriteAll(selectedText)
778			return nil
779		},
780		util.ReportInfo("Selected text copied to clipboard"),
781	)
782}
783
784// abs returns the absolute value of an integer.
785func abs(x int) int {
786	if x < 0 {
787		return -x
788	}
789	return x
790}