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	items := m.listCmp.Items()
265	toolCallInx := NotFound
266	var toolCall messages.ToolCallCmp
267	for i := len(items) - 1; i >= 0; i-- {
268		if msg, ok := items[i].(messages.ToolCallCmp); ok {
269			if msg.GetToolCall().ID == event.Payload.SessionID {
270				toolCallInx = i
271				toolCall = msg
272			}
273		}
274	}
275	if toolCallInx == NotFound {
276		return nil
277	}
278	nestedToolCalls := toolCall.GetNestedToolCalls()
279	for _, tc := range event.Payload.ToolCalls() {
280		found := false
281		for existingInx, existingTC := range nestedToolCalls {
282			if existingTC.GetToolCall().ID == tc.ID {
283				nestedToolCalls[existingInx].SetToolCall(tc)
284				found = true
285				break
286			}
287		}
288		if !found {
289			nestedCall := messages.NewToolCallCmp(
290				event.Payload.ID,
291				tc,
292				m.app.Permissions,
293				messages.WithToolCallNested(true),
294			)
295			cmds = append(cmds, nestedCall.Init())
296			nestedToolCalls = append(
297				nestedToolCalls,
298				nestedCall,
299			)
300		}
301	}
302	for _, tr := range event.Payload.ToolResults() {
303		for nestedInx, nestedTC := range nestedToolCalls {
304			if nestedTC.GetToolCall().ID == tr.ToolCallID {
305				nestedToolCalls[nestedInx].SetToolResult(tr)
306				break
307			}
308		}
309	}
310
311	toolCall.SetNestedToolCalls(nestedToolCalls)
312	m.listCmp.UpdateItem(
313		toolCall.ID(),
314		toolCall,
315	)
316	return tea.Batch(cmds...)
317}
318
319// handleMessageEvent processes different types of message events (created/updated).
320func (m *messageListCmp) handleMessageEvent(event pubsub.Event[message.Message]) tea.Cmd {
321	switch event.Type {
322	case pubsub.CreatedEvent:
323		if event.Payload.SessionID != m.session.ID {
324			return m.handleChildSession(event)
325		}
326		if m.messageExists(event.Payload.ID) {
327			return nil
328		}
329		return m.handleNewMessage(event.Payload)
330	case pubsub.UpdatedEvent:
331		if event.Payload.SessionID != m.session.ID {
332			return m.handleChildSession(event)
333		}
334		switch event.Payload.Role {
335		case message.Assistant:
336			return m.handleUpdateAssistantMessage(event.Payload)
337		case message.Tool:
338			return m.handleToolMessage(event.Payload)
339		}
340	}
341	return nil
342}
343
344// messageExists checks if a message with the given ID already exists in the list.
345func (m *messageListCmp) messageExists(messageID string) bool {
346	items := m.listCmp.Items()
347	// Search backwards as new messages are more likely to be at the end
348	for i := len(items) - 1; i >= 0; i-- {
349		if msg, ok := items[i].(messages.MessageCmp); ok && msg.GetMessage().ID == messageID {
350			return true
351		}
352	}
353	return false
354}
355
356// handleNewMessage routes new messages to appropriate handlers based on role.
357func (m *messageListCmp) handleNewMessage(msg message.Message) tea.Cmd {
358	switch msg.Role {
359	case message.User:
360		return m.handleNewUserMessage(msg)
361	case message.Assistant:
362		return m.handleNewAssistantMessage(msg)
363	case message.Tool:
364		return m.handleToolMessage(msg)
365	}
366	return nil
367}
368
369// handleNewUserMessage adds a new user message to the list and updates the timestamp.
370func (m *messageListCmp) handleNewUserMessage(msg message.Message) tea.Cmd {
371	m.lastUserMessageTime = msg.CreatedAt
372	return m.listCmp.AppendItem(messages.NewMessageCmp(msg))
373}
374
375// handleToolMessage updates existing tool calls with their results.
376func (m *messageListCmp) handleToolMessage(msg message.Message) tea.Cmd {
377	items := m.listCmp.Items()
378	for _, tr := range msg.ToolResults() {
379		if toolCallIndex := m.findToolCallByID(items, tr.ToolCallID); toolCallIndex != NotFound {
380			toolCall := items[toolCallIndex].(messages.ToolCallCmp)
381			toolCall.SetToolResult(tr)
382			m.listCmp.UpdateItem(toolCall.ID(), toolCall)
383		}
384	}
385	return nil
386}
387
388// findToolCallByID searches for a tool call with the specified ID.
389// Returns the index if found, NotFound otherwise.
390func (m *messageListCmp) findToolCallByID(items []list.Item, toolCallID string) int {
391	// Search backwards as tool calls are more likely to be recent
392	for i := len(items) - 1; i >= 0; i-- {
393		if toolCall, ok := items[i].(messages.ToolCallCmp); ok && toolCall.GetToolCall().ID == toolCallID {
394			return i
395		}
396	}
397	return NotFound
398}
399
400// handleUpdateAssistantMessage processes updates to assistant messages,
401// managing both message content and associated tool calls.
402func (m *messageListCmp) handleUpdateAssistantMessage(msg message.Message) tea.Cmd {
403	var cmds []tea.Cmd
404	items := m.listCmp.Items()
405
406	// Find existing assistant message and tool calls for this message
407	assistantIndex, existingToolCalls := m.findAssistantMessageAndToolCalls(items, msg.ID)
408
409	// Handle assistant message content
410	if cmd := m.updateAssistantMessageContent(msg, assistantIndex); cmd != nil {
411		cmds = append(cmds, cmd)
412	}
413
414	// Handle tool calls
415	if cmd := m.updateToolCalls(msg, existingToolCalls); cmd != nil {
416		cmds = append(cmds, cmd)
417	}
418
419	return tea.Batch(cmds...)
420}
421
422// findAssistantMessageAndToolCalls locates the assistant message and its tool calls.
423func (m *messageListCmp) findAssistantMessageAndToolCalls(items []list.Item, messageID string) (int, map[int]messages.ToolCallCmp) {
424	assistantIndex := NotFound
425	toolCalls := make(map[int]messages.ToolCallCmp)
426
427	// Search backwards as messages are more likely to be at the end
428	for i := len(items) - 1; i >= 0; i-- {
429		item := items[i]
430		if asMsg, ok := item.(messages.MessageCmp); ok {
431			if asMsg.GetMessage().ID == messageID {
432				assistantIndex = i
433			}
434		} else if tc, ok := item.(messages.ToolCallCmp); ok {
435			if tc.ParentMessageID() == messageID {
436				toolCalls[i] = tc
437			}
438		}
439	}
440
441	return assistantIndex, toolCalls
442}
443
444// updateAssistantMessageContent updates or removes the assistant message based on content.
445func (m *messageListCmp) updateAssistantMessageContent(msg message.Message, assistantIndex int) tea.Cmd {
446	if assistantIndex == NotFound {
447		return nil
448	}
449
450	shouldShowMessage := m.shouldShowAssistantMessage(msg)
451	hasToolCallsOnly := len(msg.ToolCalls()) > 0 && msg.Content().Text == ""
452
453	var cmd tea.Cmd
454	if shouldShowMessage {
455		items := m.listCmp.Items()
456		uiMsg := items[assistantIndex].(messages.MessageCmp)
457		uiMsg.SetMessage(msg)
458		m.listCmp.UpdateItem(
459			items[assistantIndex].ID(),
460			uiMsg,
461		)
462		if msg.FinishPart() != nil && msg.FinishPart().Reason == message.FinishReasonEndTurn {
463			m.listCmp.AppendItem(
464				messages.NewAssistantSection(
465					msg,
466					time.Unix(m.lastUserMessageTime, 0),
467				),
468			)
469		}
470	} else if hasToolCallsOnly {
471		items := m.listCmp.Items()
472		m.listCmp.DeleteItem(items[assistantIndex].ID())
473	}
474
475	return cmd
476}
477
478// shouldShowAssistantMessage determines if an assistant message should be displayed.
479func (m *messageListCmp) shouldShowAssistantMessage(msg message.Message) bool {
480	return len(msg.ToolCalls()) == 0 || msg.Content().Text != "" || msg.ReasoningContent().Thinking != "" || msg.IsThinking()
481}
482
483// updateToolCalls handles updates to tool calls, updating existing ones and adding new ones.
484func (m *messageListCmp) updateToolCalls(msg message.Message, existingToolCalls map[int]messages.ToolCallCmp) tea.Cmd {
485	var cmds []tea.Cmd
486
487	for _, tc := range msg.ToolCalls() {
488		if cmd := m.updateOrAddToolCall(msg, tc, existingToolCalls); cmd != nil {
489			cmds = append(cmds, cmd)
490		}
491	}
492
493	return tea.Batch(cmds...)
494}
495
496// updateOrAddToolCall updates an existing tool call or adds a new one.
497func (m *messageListCmp) updateOrAddToolCall(msg message.Message, tc message.ToolCall, existingToolCalls map[int]messages.ToolCallCmp) tea.Cmd {
498	// Try to find existing tool call
499	for _, existingTC := range existingToolCalls {
500		if tc.ID == existingTC.GetToolCall().ID {
501			existingTC.SetToolCall(tc)
502			if msg.FinishPart() != nil && msg.FinishPart().Reason == message.FinishReasonCanceled {
503				existingTC.SetCancelled()
504			}
505			m.listCmp.UpdateItem(tc.ID, existingTC)
506			return nil
507		}
508	}
509
510	// Add new tool call if not found
511	return m.listCmp.AppendItem(messages.NewToolCallCmp(msg.ID, tc, m.app.Permissions))
512}
513
514// handleNewAssistantMessage processes new assistant messages and their tool calls.
515func (m *messageListCmp) handleNewAssistantMessage(msg message.Message) tea.Cmd {
516	var cmds []tea.Cmd
517
518	// Add assistant message if it should be displayed
519	if m.shouldShowAssistantMessage(msg) {
520		cmd := m.listCmp.AppendItem(
521			messages.NewMessageCmp(
522				msg,
523			),
524		)
525		cmds = append(cmds, cmd)
526	}
527
528	// Add tool calls
529	for _, tc := range msg.ToolCalls() {
530		cmd := m.listCmp.AppendItem(messages.NewToolCallCmp(msg.ID, tc, m.app.Permissions))
531		cmds = append(cmds, cmd)
532	}
533
534	return tea.Batch(cmds...)
535}
536
537// SetSession loads and displays messages for a new session.
538func (m *messageListCmp) SetSession(session session.Session) tea.Cmd {
539	if m.session.ID == session.ID {
540		return nil
541	}
542
543	m.session = session
544	sessionMessages, err := m.app.Messages.List(context.Background(), session.ID)
545	if err != nil {
546		return util.ReportError(err)
547	}
548
549	if len(sessionMessages) == 0 {
550		return m.listCmp.SetItems([]list.Item{})
551	}
552
553	// Initialize with first message timestamp
554	m.lastUserMessageTime = sessionMessages[0].CreatedAt
555
556	// Build tool result map for efficient lookup
557	toolResultMap := m.buildToolResultMap(sessionMessages)
558
559	// Convert messages to UI components
560	uiMessages := m.convertMessagesToUI(sessionMessages, toolResultMap)
561
562	return m.listCmp.SetItems(uiMessages)
563}
564
565// buildToolResultMap creates a map of tool call ID to tool result for efficient lookup.
566func (m *messageListCmp) buildToolResultMap(messages []message.Message) map[string]message.ToolResult {
567	toolResultMap := make(map[string]message.ToolResult)
568	for _, msg := range messages {
569		for _, tr := range msg.ToolResults() {
570			toolResultMap[tr.ToolCallID] = tr
571		}
572	}
573	return toolResultMap
574}
575
576// convertMessagesToUI converts database messages to UI components.
577func (m *messageListCmp) convertMessagesToUI(sessionMessages []message.Message, toolResultMap map[string]message.ToolResult) []list.Item {
578	uiMessages := make([]list.Item, 0)
579
580	for _, msg := range sessionMessages {
581		switch msg.Role {
582		case message.User:
583			m.lastUserMessageTime = msg.CreatedAt
584			uiMessages = append(uiMessages, messages.NewMessageCmp(msg))
585		case message.Assistant:
586			uiMessages = append(uiMessages, m.convertAssistantMessage(msg, toolResultMap)...)
587			if msg.FinishPart() != nil && msg.FinishPart().Reason == message.FinishReasonEndTurn {
588				uiMessages = append(uiMessages, messages.NewAssistantSection(msg, time.Unix(m.lastUserMessageTime, 0)))
589			}
590		}
591	}
592
593	return uiMessages
594}
595
596// convertAssistantMessage converts an assistant message and its tool calls to UI components.
597func (m *messageListCmp) convertAssistantMessage(msg message.Message, toolResultMap map[string]message.ToolResult) []list.Item {
598	var uiMessages []list.Item
599
600	// Add assistant message if it should be displayed
601	if m.shouldShowAssistantMessage(msg) {
602		uiMessages = append(
603			uiMessages,
604			messages.NewMessageCmp(
605				msg,
606			),
607		)
608	}
609
610	// Add tool calls with their results and status
611	for _, tc := range msg.ToolCalls() {
612		options := m.buildToolCallOptions(tc, msg, toolResultMap)
613		uiMessages = append(uiMessages, messages.NewToolCallCmp(msg.ID, tc, m.app.Permissions, options...))
614		// If this tool call is the agent tool, fetch nested tool calls
615		if tc.Name == agent.AgentToolName {
616			nestedMessages, _ := m.app.Messages.List(context.Background(), tc.ID)
617			nestedToolResultMap := m.buildToolResultMap(nestedMessages)
618			nestedUIMessages := m.convertMessagesToUI(nestedMessages, nestedToolResultMap)
619			nestedToolCalls := make([]messages.ToolCallCmp, 0, len(nestedUIMessages))
620			for _, nestedMsg := range nestedUIMessages {
621				if toolCall, ok := nestedMsg.(messages.ToolCallCmp); ok {
622					toolCall.SetIsNested(true)
623					nestedToolCalls = append(nestedToolCalls, toolCall)
624				}
625			}
626			uiMessages[len(uiMessages)-1].(messages.ToolCallCmp).SetNestedToolCalls(nestedToolCalls)
627		}
628	}
629
630	return uiMessages
631}
632
633// buildToolCallOptions creates options for tool call components based on results and status.
634func (m *messageListCmp) buildToolCallOptions(tc message.ToolCall, msg message.Message, toolResultMap map[string]message.ToolResult) []messages.ToolCallOption {
635	var options []messages.ToolCallOption
636
637	// Add tool result if available
638	if tr, ok := toolResultMap[tc.ID]; ok {
639		options = append(options, messages.WithToolCallResult(tr))
640	}
641
642	// Add cancelled status if applicable
643	if msg.FinishPart() != nil && msg.FinishPart().Reason == message.FinishReasonCanceled {
644		options = append(options, messages.WithToolCallCancelled())
645	}
646
647	return options
648}
649
650// GetSize returns the current width and height of the component.
651func (m *messageListCmp) GetSize() (int, int) {
652	return m.width, m.height
653}
654
655// SetSize updates the component dimensions and propagates to the list component.
656func (m *messageListCmp) SetSize(width int, height int) tea.Cmd {
657	m.width = width
658	m.height = height
659	if m.promptQueue > 0 {
660		queueHeight := 3 + 1 // 1 for padding top
661		lHight := max(0, height-(1+queueHeight))
662		return m.listCmp.SetSize(width-2, lHight)
663	}
664	return m.listCmp.SetSize(width-2, max(0, height-1)) // for padding
665}
666
667// Blur implements MessageListCmp.
668func (m *messageListCmp) Blur() tea.Cmd {
669	return m.listCmp.Blur()
670}
671
672// Focus implements MessageListCmp.
673func (m *messageListCmp) Focus() tea.Cmd {
674	return m.listCmp.Focus()
675}
676
677// IsFocused implements MessageListCmp.
678func (m *messageListCmp) IsFocused() bool {
679	return m.listCmp.IsFocused()
680}
681
682func (m *messageListCmp) Bindings() []key.Binding {
683	return m.defaultListKeyMap.KeyBindings()
684}
685
686func (m *messageListCmp) GoToBottom() tea.Cmd {
687	return m.listCmp.GoToBottom()
688}
689
690const (
691	doubleClickThreshold = 500 * time.Millisecond
692	clickTolerance       = 2 // pixels
693)
694
695// handleMouseClick handles mouse click events and detects double/triple clicks.
696func (m *messageListCmp) handleMouseClick(x, y int) tea.Cmd {
697	now := time.Now()
698
699	// Check if this is a potential multi-click
700	if now.Sub(m.lastClickTime) <= doubleClickThreshold &&
701		abs(x-m.lastClickX) <= clickTolerance &&
702		abs(y-m.lastClickY) <= clickTolerance {
703		m.clickCount++
704	} else {
705		m.clickCount = 1
706	}
707
708	m.lastClickTime = now
709	m.lastClickX = x
710	m.lastClickY = y
711
712	switch m.clickCount {
713	case 1:
714		// Single click - start selection
715		m.listCmp.StartSelection(x, y)
716	case 2:
717		// Double click - select word
718		m.listCmp.SelectWord(x, y)
719	case 3:
720		// Triple click - select paragraph
721		m.listCmp.SelectParagraph(x, y)
722		m.clickCount = 0 // Reset after triple click
723	}
724
725	return nil
726}
727
728// SelectionClear clears the current selection in the list component.
729func (m *messageListCmp) SelectionClear() tea.Cmd {
730	m.listCmp.SelectionClear()
731	m.previousSelected = ""
732	m.lastClickX, m.lastClickY = 0, 0
733	m.lastClickTime = time.Time{}
734	m.clickCount = 0
735	return nil
736}
737
738// HasSelection checks if there is a selection in the list component.
739func (m *messageListCmp) HasSelection() bool {
740	return m.listCmp.HasSelection()
741}
742
743// GetSelectedText returns the currently selected text from the list component.
744func (m *messageListCmp) GetSelectedText() string {
745	return m.listCmp.GetSelectedText(3) // 3 padding for the left border/padding
746}
747
748// CopySelectedText copies the currently selected text to the clipboard. When
749// clear is true, it clears the selection after copying.
750func (m *messageListCmp) CopySelectedText(clear bool) tea.Cmd {
751	if !m.listCmp.HasSelection() {
752		return nil
753	}
754
755	selectedText := m.GetSelectedText()
756	if selectedText == "" {
757		return util.ReportInfo("No text selected")
758	}
759
760	if clear {
761		defer func() { m.SelectionClear() }()
762	}
763
764	return tea.Sequence(
765		// We use both OSC 52 and native clipboard for compatibility with different
766		// terminal emulators and environments.
767		tea.SetClipboard(selectedText),
768		func() tea.Msg {
769			_ = clipboard.WriteAll(selectedText)
770			return nil
771		},
772		util.ReportInfo("Selected text copied to clipboard"),
773	)
774}
775
776// abs returns the absolute value of an integer.
777func abs(x int) int {
778	if x < 0 {
779		return -x
780	}
781	return x
782}