tool.go

  1package messages
  2
  3import (
  4	"fmt"
  5
  6	tea "github.com/charmbracelet/bubbletea/v2"
  7	"github.com/charmbracelet/crush/internal/message"
  8	"github.com/charmbracelet/crush/internal/tui/components/anim"
  9	"github.com/charmbracelet/crush/internal/tui/components/core/layout"
 10	"github.com/charmbracelet/crush/internal/tui/styles"
 11	"github.com/charmbracelet/crush/internal/tui/util"
 12	"github.com/charmbracelet/lipgloss/v2"
 13	"github.com/charmbracelet/x/ansi"
 14)
 15
 16// ToolCallCmp defines the interface for tool call components in the chat interface.
 17// It manages the display of tool execution including pending states, results, and errors.
 18type ToolCallCmp interface {
 19	util.Model                         // Basic Bubble Tea model interface
 20	layout.Sizeable                    // Width/height management
 21	layout.Focusable                   // Focus state management
 22	GetToolCall() message.ToolCall     // Access to tool call data
 23	GetToolResult() message.ToolResult // Access to tool result data
 24	SetToolResult(message.ToolResult)  // Update tool result
 25	SetToolCall(message.ToolCall)      // Update tool call
 26	SetCancelled()                     // Mark as cancelled
 27	ParentMessageID() string           // Get parent message ID
 28	Spinning() bool                    // Animation state for pending tools
 29	GetNestedToolCalls() []ToolCallCmp // Get nested tool calls
 30	SetNestedToolCalls([]ToolCallCmp)  // Set nested tool calls
 31	SetIsNested(bool)                  // Set whether this tool call is nested
 32}
 33
 34// toolCallCmp implements the ToolCallCmp interface for displaying tool calls.
 35// It handles rendering of tool execution states including pending, completed, and error states.
 36type toolCallCmp struct {
 37	width    int  // Component width for text wrapping
 38	focused  bool // Focus state for border styling
 39	isNested bool // Whether this tool call is nested within another
 40
 41	// Tool call data and state
 42	parentMessageID string             // ID of the message that initiated this tool call
 43	call            message.ToolCall   // The tool call being executed
 44	result          message.ToolResult // The result of the tool execution
 45	cancelled       bool               // Whether the tool call was cancelled
 46
 47	// Animation state for pending tool calls
 48	spinning bool       // Whether to show loading animation
 49	anim     util.Model // Animation component for pending states
 50
 51	nestedToolCalls []ToolCallCmp // Nested tool calls for hierarchical display
 52}
 53
 54// ToolCallOption provides functional options for configuring tool call components
 55type ToolCallOption func(*toolCallCmp)
 56
 57// WithToolCallCancelled marks the tool call as cancelled
 58func WithToolCallCancelled() ToolCallOption {
 59	return func(m *toolCallCmp) {
 60		m.cancelled = true
 61	}
 62}
 63
 64// WithToolCallResult sets the initial tool result
 65func WithToolCallResult(result message.ToolResult) ToolCallOption {
 66	return func(m *toolCallCmp) {
 67		m.result = result
 68	}
 69}
 70
 71func WithToolCallNested(isNested bool) ToolCallOption {
 72	return func(m *toolCallCmp) {
 73		m.isNested = isNested
 74	}
 75}
 76
 77func WithToolCallNestedCalls(calls []ToolCallCmp) ToolCallOption {
 78	return func(m *toolCallCmp) {
 79		m.nestedToolCalls = calls
 80	}
 81}
 82
 83// NewToolCallCmp creates a new tool call component with the given parent message ID,
 84// tool call, and optional configuration
 85func NewToolCallCmp(parentMessageID string, tc message.ToolCall, opts ...ToolCallOption) ToolCallCmp {
 86	m := &toolCallCmp{
 87		call:            tc,
 88		parentMessageID: parentMessageID,
 89	}
 90	for _, opt := range opts {
 91		opt(m)
 92	}
 93	t := styles.CurrentTheme()
 94	m.anim = anim.New(15, "Working", t)
 95	if m.isNested {
 96		m.anim = anim.New(10, "", t)
 97	}
 98	return m
 99}
100
101// Init initializes the tool call component and starts animations if needed.
102// Returns a command to start the animation for pending tool calls.
103func (m *toolCallCmp) Init() tea.Cmd {
104	m.spinning = m.shouldSpin()
105	if m.spinning {
106		return m.anim.Init()
107	}
108	return nil
109}
110
111// Update handles incoming messages and updates the component state.
112// Manages animation updates for pending tool calls.
113func (m *toolCallCmp) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
114	switch msg := msg.(type) {
115	case anim.StepMsg:
116		var cmds []tea.Cmd
117		for i, nested := range m.nestedToolCalls {
118			if nested.Spinning() {
119				u, cmd := nested.Update(msg)
120				m.nestedToolCalls[i] = u.(ToolCallCmp)
121				cmds = append(cmds, cmd)
122			}
123		}
124		if m.spinning {
125			u, cmd := m.anim.Update(msg)
126			m.anim = u.(util.Model)
127			cmds = append(cmds, cmd)
128		}
129		return m, tea.Batch(cmds...)
130	}
131	return m, nil
132}
133
134// View renders the tool call component based on its current state.
135// Shows either a pending animation or the tool-specific rendered result.
136func (m *toolCallCmp) View() tea.View {
137	box := m.style()
138
139	if !m.call.Finished && !m.cancelled {
140		return tea.NewView(box.Render(m.renderPending()))
141	}
142
143	r := registry.lookup(m.call.Name)
144
145	if m.isNested {
146		return tea.NewView(box.Render(r.Render(m)))
147	}
148	return tea.NewView(box.Render(r.Render(m)))
149}
150
151// State management methods
152
153// SetCancelled marks the tool call as cancelled
154func (m *toolCallCmp) SetCancelled() {
155	m.cancelled = true
156}
157
158// SetToolCall updates the tool call data and stops spinning if finished
159func (m *toolCallCmp) SetToolCall(call message.ToolCall) {
160	m.call = call
161	if m.call.Finished {
162		m.spinning = false
163	}
164}
165
166// ParentMessageID returns the ID of the message that initiated this tool call
167func (m *toolCallCmp) ParentMessageID() string {
168	return m.parentMessageID
169}
170
171// SetToolResult updates the tool result and stops the spinning animation
172func (m *toolCallCmp) SetToolResult(result message.ToolResult) {
173	m.result = result
174	m.spinning = false
175}
176
177// GetToolCall returns the current tool call data
178func (m *toolCallCmp) GetToolCall() message.ToolCall {
179	return m.call
180}
181
182// GetToolResult returns the current tool result data
183func (m *toolCallCmp) GetToolResult() message.ToolResult {
184	return m.result
185}
186
187// GetNestedToolCalls returns the nested tool calls
188func (m *toolCallCmp) GetNestedToolCalls() []ToolCallCmp {
189	return m.nestedToolCalls
190}
191
192// SetNestedToolCalls sets the nested tool calls
193func (m *toolCallCmp) SetNestedToolCalls(calls []ToolCallCmp) {
194	m.nestedToolCalls = calls
195	for _, nested := range m.nestedToolCalls {
196		nested.SetSize(m.width, 0)
197	}
198}
199
200// SetIsNested sets whether this tool call is nested within another
201func (m *toolCallCmp) SetIsNested(isNested bool) {
202	m.isNested = isNested
203}
204
205// Rendering methods
206
207// renderPending displays the tool name with a loading animation for pending tool calls
208func (m *toolCallCmp) renderPending() string {
209	t := styles.CurrentTheme()
210	if m.isNested {
211		tool := t.S().Base.Foreground(t.FgHalfMuted).Render(prettifyToolName(m.call.Name))
212		return fmt.Sprintf("%s %s", tool, m.anim.View())
213	}
214	icon := t.S().Base.Foreground(t.GreenDark).Render(styles.ToolPending)
215	tool := t.S().Base.Foreground(t.Blue).Render(prettifyToolName(m.call.Name))
216	return fmt.Sprintf("%s %s %s", icon, tool, m.anim.View())
217}
218
219// style returns the lipgloss style for the tool call component.
220// Applies muted colors and focus-dependent border styles.
221func (m *toolCallCmp) style() lipgloss.Style {
222	t := styles.CurrentTheme()
223
224	if m.isNested {
225		return t.S().Muted
226	}
227	style := t.S().Muted.PaddingLeft(4)
228
229	if m.focused {
230		style = style.PaddingLeft(3).BorderStyle(focusedMessageBorder).BorderLeft(true).BorderForeground(t.GreenDark)
231	}
232	return style
233}
234
235// textWidth calculates the available width for text content,
236// accounting for borders and padding
237func (m *toolCallCmp) textWidth() int {
238	if m.isNested {
239		return m.width - 6
240	}
241	return m.width - 5 // take into account the border and PaddingLeft
242}
243
244// fit truncates content to fit within the specified width with ellipsis
245func (m *toolCallCmp) fit(content string, width int) string {
246	t := styles.CurrentTheme()
247	lineStyle := t.S().Muted
248	dots := lineStyle.Render("…")
249	return ansi.Truncate(content, width, dots)
250}
251
252// Focus management methods
253
254// Blur removes focus from the tool call component
255func (m *toolCallCmp) Blur() tea.Cmd {
256	m.focused = false
257	return nil
258}
259
260// Focus sets focus on the tool call component
261func (m *toolCallCmp) Focus() tea.Cmd {
262	m.focused = true
263	return nil
264}
265
266// IsFocused returns whether the tool call component is currently focused
267func (m *toolCallCmp) IsFocused() bool {
268	return m.focused
269}
270
271// Size management methods
272
273// GetSize returns the current dimensions of the tool call component
274func (m *toolCallCmp) GetSize() (int, int) {
275	return m.width, 0
276}
277
278// SetSize updates the width of the tool call component for text wrapping
279func (m *toolCallCmp) SetSize(width int, height int) tea.Cmd {
280	m.width = width
281	for _, nested := range m.nestedToolCalls {
282		nested.SetSize(width, height)
283	}
284	return nil
285}
286
287// shouldSpin determines whether the tool call should show a loading animation.
288// Returns true if the tool call is not finished or if the result doesn't match the call ID.
289func (m *toolCallCmp) shouldSpin() bool {
290	return !m.call.Finished
291}
292
293// Spinning returns whether the tool call is currently showing a loading animation
294func (m *toolCallCmp) Spinning() bool {
295	if m.spinning {
296		return true
297	}
298	for _, nested := range m.nestedToolCalls {
299		if nested.Spinning() {
300			return true
301		}
302	}
303	return m.spinning
304}