tool.go

  1package messages
  2
  3import (
  4	"encoding/json"
  5	"fmt"
  6	"path/filepath"
  7	"strings"
  8	"time"
  9
 10	"charm.land/bubbles/v2/key"
 11	tea "charm.land/bubbletea/v2"
 12	"charm.land/lipgloss/v2"
 13	"github.com/atotto/clipboard"
 14	"github.com/charmbracelet/crush/internal/agent"
 15	"github.com/charmbracelet/crush/internal/agent/tools"
 16	"github.com/charmbracelet/crush/internal/diff"
 17	"github.com/charmbracelet/crush/internal/fsext"
 18	"github.com/charmbracelet/crush/internal/message"
 19	"github.com/charmbracelet/crush/internal/permission"
 20	"github.com/charmbracelet/crush/internal/tui/components/anim"
 21	"github.com/charmbracelet/crush/internal/tui/components/core/layout"
 22	"github.com/charmbracelet/crush/internal/tui/styles"
 23	"github.com/charmbracelet/crush/internal/tui/util"
 24	"github.com/charmbracelet/x/ansi"
 25)
 26
 27// ToolCallCmp defines the interface for tool call components in the chat interface.
 28// It manages the display of tool execution including pending states, results, and errors.
 29type ToolCallCmp interface {
 30	util.Model                         // Basic Bubble util.Model interface
 31	layout.Sizeable                    // Width/height management
 32	layout.Focusable                   // Focus state management
 33	GetToolCall() message.ToolCall     // Access to tool call data
 34	GetToolResult() message.ToolResult // Access to tool result data
 35	SetToolResult(message.ToolResult)  // Update tool result
 36	SetToolCall(message.ToolCall)      // Update tool call
 37	SetCancelled()                     // Mark as cancelled
 38	ParentMessageID() string           // Get parent message ID
 39	Spinning() bool                    // Animation state for pending tools
 40	GetNestedToolCalls() []ToolCallCmp // Get nested tool calls
 41	SetNestedToolCalls([]ToolCallCmp)  // Set nested tool calls
 42	SetIsNested(bool)                  // Set whether this tool call is nested
 43	ID() string
 44	SetPermissionRequested() // Mark permission request
 45	SetPermissionGranted()   // Mark permission granted
 46}
 47
 48// toolCallCmp implements the ToolCallCmp interface for displaying tool calls.
 49// It handles rendering of tool execution states including pending, completed, and error states.
 50type toolCallCmp struct {
 51	width    int  // Component width for text wrapping
 52	focused  bool // Focus state for border styling
 53	isNested bool // Whether this tool call is nested within another
 54
 55	// Tool call data and state
 56	parentMessageID     string             // ID of the message that initiated this tool call
 57	call                message.ToolCall   // The tool call being executed
 58	result              message.ToolResult // The result of the tool execution
 59	cancelled           bool               // Whether the tool call was cancelled
 60	permissionRequested bool
 61	permissionGranted   bool
 62
 63	// Animation state for pending tool calls
 64	spinning bool       // Whether to show loading animation
 65	anim     util.Model // Animation component for pending states
 66
 67	nestedToolCalls []ToolCallCmp // Nested tool calls for hierarchical display
 68}
 69
 70// ToolCallOption provides functional options for configuring tool call components
 71type ToolCallOption func(*toolCallCmp)
 72
 73// WithToolCallCancelled marks the tool call as cancelled
 74func WithToolCallCancelled() ToolCallOption {
 75	return func(m *toolCallCmp) {
 76		m.cancelled = true
 77	}
 78}
 79
 80// WithToolCallResult sets the initial tool result
 81func WithToolCallResult(result message.ToolResult) ToolCallOption {
 82	return func(m *toolCallCmp) {
 83		m.result = result
 84	}
 85}
 86
 87func WithToolCallNested(isNested bool) ToolCallOption {
 88	return func(m *toolCallCmp) {
 89		m.isNested = isNested
 90	}
 91}
 92
 93func WithToolCallNestedCalls(calls []ToolCallCmp) ToolCallOption {
 94	return func(m *toolCallCmp) {
 95		m.nestedToolCalls = calls
 96	}
 97}
 98
 99func WithToolPermissionRequested() ToolCallOption {
100	return func(m *toolCallCmp) {
101		m.permissionRequested = true
102	}
103}
104
105func WithToolPermissionGranted() ToolCallOption {
106	return func(m *toolCallCmp) {
107		m.permissionGranted = true
108	}
109}
110
111// NewToolCallCmp creates a new tool call component with the given parent message ID,
112// tool call, and optional configuration
113func NewToolCallCmp(parentMessageID string, tc message.ToolCall, permissions permission.Service, opts ...ToolCallOption) ToolCallCmp {
114	m := &toolCallCmp{
115		call:            tc,
116		parentMessageID: parentMessageID,
117	}
118	for _, opt := range opts {
119		opt(m)
120	}
121	t := styles.CurrentTheme()
122	m.anim = anim.New(anim.Settings{
123		Size:        15,
124		Label:       "Working",
125		GradColorA:  t.Primary,
126		GradColorB:  t.Secondary,
127		LabelColor:  t.FgBase,
128		CycleColors: true,
129	})
130	if m.isNested {
131		m.anim = anim.New(anim.Settings{
132			Size:        10,
133			GradColorA:  t.Primary,
134			GradColorB:  t.Secondary,
135			CycleColors: true,
136		})
137	}
138	return m
139}
140
141// Init initializes the tool call component and starts animations if needed.
142// Returns a command to start the animation for pending tool calls.
143func (m *toolCallCmp) Init() tea.Cmd {
144	m.spinning = m.shouldSpin()
145	return m.anim.Init()
146}
147
148// Update handles incoming messages and updates the component state.
149// Manages animation updates for pending tool calls.
150func (m *toolCallCmp) Update(msg tea.Msg) (util.Model, tea.Cmd) {
151	switch msg := msg.(type) {
152	case anim.StepMsg:
153		var cmds []tea.Cmd
154		for i, nested := range m.nestedToolCalls {
155			if nested.Spinning() {
156				u, cmd := nested.Update(msg)
157				m.nestedToolCalls[i] = u.(ToolCallCmp)
158				cmds = append(cmds, cmd)
159			}
160		}
161		if m.spinning {
162			u, cmd := m.anim.Update(msg)
163			m.anim = u
164			cmds = append(cmds, cmd)
165		}
166		return m, tea.Batch(cmds...)
167	case tea.KeyPressMsg:
168		if key.Matches(msg, CopyKey) {
169			return m, m.copyTool()
170		}
171	}
172	return m, nil
173}
174
175// View renders the tool call component based on its current state.
176// Shows either a pending animation or the tool-specific rendered result.
177func (m *toolCallCmp) View() string {
178	box := m.style()
179
180	if !m.call.Finished && !m.cancelled {
181		return box.Render(m.renderPending())
182	}
183
184	r := registry.lookup(m.call.Name)
185
186	if m.isNested {
187		return box.Render(r.Render(m))
188	}
189	return box.Render(r.Render(m))
190}
191
192// State management methods
193
194// SetCancelled marks the tool call as cancelled
195func (m *toolCallCmp) SetCancelled() {
196	m.cancelled = true
197}
198
199func (m *toolCallCmp) copyTool() tea.Cmd {
200	content := m.formatToolForCopy()
201	return tea.Sequence(
202		tea.SetClipboard(content),
203		func() tea.Msg {
204			_ = clipboard.WriteAll(content)
205			return nil
206		},
207		util.ReportInfo("Tool content copied to clipboard"),
208	)
209}
210
211func (m *toolCallCmp) formatToolForCopy() string {
212	var parts []string
213
214	toolName := prettifyToolName(m.call.Name)
215	parts = append(parts, fmt.Sprintf("## %s Tool Call", toolName))
216
217	if m.call.Input != "" {
218		params := m.formatParametersForCopy()
219		if params != "" {
220			parts = append(parts, "### Parameters:")
221			parts = append(parts, params)
222		}
223	}
224
225	if m.result.ToolCallID != "" {
226		if m.result.IsError {
227			parts = append(parts, "### Error:")
228			parts = append(parts, m.result.Content)
229		} else {
230			parts = append(parts, "### Result:")
231			content := m.formatResultForCopy()
232			if content != "" {
233				parts = append(parts, content)
234			}
235		}
236	} else if m.cancelled {
237		parts = append(parts, "### Status:")
238		parts = append(parts, "Cancelled")
239	} else {
240		parts = append(parts, "### Status:")
241		parts = append(parts, "Pending...")
242	}
243
244	return strings.Join(parts, "\n\n")
245}
246
247func (m *toolCallCmp) formatParametersForCopy() string {
248	switch m.call.Name {
249	case tools.BashToolName:
250		var params tools.BashParams
251		if json.Unmarshal([]byte(m.call.Input), &params) == nil {
252			cmd := strings.ReplaceAll(params.Command, "\n", " ")
253			cmd = strings.ReplaceAll(cmd, "\t", "    ")
254			return fmt.Sprintf("**Command:** %s", cmd)
255		}
256	case tools.ViewToolName:
257		var params tools.ViewParams
258		if json.Unmarshal([]byte(m.call.Input), &params) == nil {
259			var parts []string
260			parts = append(parts, fmt.Sprintf("**File:** %s", fsext.PrettyPath(params.FilePath)))
261			if params.Limit > 0 {
262				parts = append(parts, fmt.Sprintf("**Limit:** %d", params.Limit))
263			}
264			if params.Offset > 0 {
265				parts = append(parts, fmt.Sprintf("**Offset:** %d", params.Offset))
266			}
267			return strings.Join(parts, "\n")
268		}
269	case tools.EditToolName:
270		var params tools.EditParams
271		if json.Unmarshal([]byte(m.call.Input), &params) == nil {
272			return fmt.Sprintf("**File:** %s", fsext.PrettyPath(params.FilePath))
273		}
274	case tools.MultiEditToolName:
275		var params tools.MultiEditParams
276		if json.Unmarshal([]byte(m.call.Input), &params) == nil {
277			var parts []string
278			parts = append(parts, fmt.Sprintf("**File:** %s", fsext.PrettyPath(params.FilePath)))
279			parts = append(parts, fmt.Sprintf("**Edits:** %d", len(params.Edits)))
280			return strings.Join(parts, "\n")
281		}
282	case tools.WriteToolName:
283		var params tools.WriteParams
284		if json.Unmarshal([]byte(m.call.Input), &params) == nil {
285			return fmt.Sprintf("**File:** %s", fsext.PrettyPath(params.FilePath))
286		}
287	case tools.FetchToolName:
288		var params tools.FetchParams
289		if json.Unmarshal([]byte(m.call.Input), &params) == nil {
290			var parts []string
291			parts = append(parts, fmt.Sprintf("**URL:** %s", params.URL))
292			if params.Format != "" {
293				parts = append(parts, fmt.Sprintf("**Format:** %s", params.Format))
294			}
295			if params.Timeout > 0 {
296				parts = append(parts, fmt.Sprintf("**Timeout:** %ds", params.Timeout))
297			}
298			return strings.Join(parts, "\n")
299		}
300	case tools.AgenticFetchToolName:
301		var params tools.AgenticFetchParams
302		if json.Unmarshal([]byte(m.call.Input), &params) == nil {
303			var parts []string
304			if params.URL != "" {
305				parts = append(parts, fmt.Sprintf("**URL:** %s", params.URL))
306			}
307			if params.Prompt != "" {
308				parts = append(parts, fmt.Sprintf("**Prompt:** %s", params.Prompt))
309			}
310			return strings.Join(parts, "\n")
311		}
312	case tools.WebFetchToolName:
313		var params tools.WebFetchParams
314		if json.Unmarshal([]byte(m.call.Input), &params) == nil {
315			return fmt.Sprintf("**URL:** %s", params.URL)
316		}
317	case tools.GrepToolName:
318		var params tools.GrepParams
319		if json.Unmarshal([]byte(m.call.Input), &params) == nil {
320			var parts []string
321			parts = append(parts, fmt.Sprintf("**Pattern:** %s", params.Pattern))
322			if params.Path != "" {
323				parts = append(parts, fmt.Sprintf("**Path:** %s", params.Path))
324			}
325			if params.Include != "" {
326				parts = append(parts, fmt.Sprintf("**Include:** %s", params.Include))
327			}
328			if params.LiteralText {
329				parts = append(parts, "**Literal:** true")
330			}
331			return strings.Join(parts, "\n")
332		}
333	case tools.GlobToolName:
334		var params tools.GlobParams
335		if json.Unmarshal([]byte(m.call.Input), &params) == nil {
336			var parts []string
337			parts = append(parts, fmt.Sprintf("**Pattern:** %s", params.Pattern))
338			if params.Path != "" {
339				parts = append(parts, fmt.Sprintf("**Path:** %s", params.Path))
340			}
341			return strings.Join(parts, "\n")
342		}
343	case tools.LSToolName:
344		var params tools.LSParams
345		if json.Unmarshal([]byte(m.call.Input), &params) == nil {
346			path := params.Path
347			if path == "" {
348				path = "."
349			}
350			return fmt.Sprintf("**Path:** %s", fsext.PrettyPath(path))
351		}
352	case tools.DownloadToolName:
353		var params tools.DownloadParams
354		if json.Unmarshal([]byte(m.call.Input), &params) == nil {
355			var parts []string
356			parts = append(parts, fmt.Sprintf("**URL:** %s", params.URL))
357			parts = append(parts, fmt.Sprintf("**File Path:** %s", fsext.PrettyPath(params.FilePath)))
358			if params.Timeout > 0 {
359				parts = append(parts, fmt.Sprintf("**Timeout:** %s", (time.Duration(params.Timeout)*time.Second).String()))
360			}
361			return strings.Join(parts, "\n")
362		}
363	case tools.SourcegraphToolName:
364		var params tools.SourcegraphParams
365		if json.Unmarshal([]byte(m.call.Input), &params) == nil {
366			var parts []string
367			parts = append(parts, fmt.Sprintf("**Query:** %s", params.Query))
368			if params.Count > 0 {
369				parts = append(parts, fmt.Sprintf("**Count:** %d", params.Count))
370			}
371			if params.ContextWindow > 0 {
372				parts = append(parts, fmt.Sprintf("**Context:** %d", params.ContextWindow))
373			}
374			return strings.Join(parts, "\n")
375		}
376	case tools.DiagnosticsToolName:
377		return "**Project:** diagnostics"
378	case agent.AgentToolName:
379		var params agent.AgentParams
380		if json.Unmarshal([]byte(m.call.Input), &params) == nil {
381			return fmt.Sprintf("**Task:**\n%s", params.Prompt)
382		}
383	}
384
385	var params map[string]any
386	if json.Unmarshal([]byte(m.call.Input), &params) == nil {
387		var parts []string
388		for key, value := range params {
389			displayKey := strings.ReplaceAll(key, "_", " ")
390			if len(displayKey) > 0 {
391				displayKey = strings.ToUpper(displayKey[:1]) + displayKey[1:]
392			}
393			parts = append(parts, fmt.Sprintf("**%s:** %v", displayKey, value))
394		}
395		return strings.Join(parts, "\n")
396	}
397
398	return ""
399}
400
401func (m *toolCallCmp) formatResultForCopy() string {
402	if m.result.Data != "" {
403		if strings.HasPrefix(m.result.MIMEType, "image/") {
404			return fmt.Sprintf("[Image: %s]", m.result.MIMEType)
405		}
406		return fmt.Sprintf("[Media: %s]", m.result.MIMEType)
407	}
408
409	switch m.call.Name {
410	case tools.BashToolName:
411		return m.formatBashResultForCopy()
412	case tools.ViewToolName:
413		return m.formatViewResultForCopy()
414	case tools.EditToolName:
415		return m.formatEditResultForCopy()
416	case tools.MultiEditToolName:
417		return m.formatMultiEditResultForCopy()
418	case tools.WriteToolName:
419		return m.formatWriteResultForCopy()
420	case tools.FetchToolName:
421		return m.formatFetchResultForCopy()
422	case tools.AgenticFetchToolName:
423		return m.formatAgenticFetchResultForCopy()
424	case tools.WebFetchToolName:
425		return m.formatWebFetchResultForCopy()
426	case agent.AgentToolName:
427		return m.formatAgentResultForCopy()
428	case tools.DownloadToolName, tools.GrepToolName, tools.GlobToolName, tools.LSToolName, tools.SourcegraphToolName, tools.DiagnosticsToolName:
429		return fmt.Sprintf("```\n%s\n```", m.result.Content)
430	default:
431		return m.result.Content
432	}
433}
434
435func (m *toolCallCmp) formatBashResultForCopy() string {
436	var meta tools.BashResponseMetadata
437	if m.result.Metadata != "" {
438		json.Unmarshal([]byte(m.result.Metadata), &meta)
439	}
440
441	output := meta.Output
442	if output == "" && m.result.Content != tools.BashNoOutput {
443		output = m.result.Content
444	}
445
446	if output == "" {
447		return ""
448	}
449
450	return fmt.Sprintf("```bash\n%s\n```", output)
451}
452
453func (m *toolCallCmp) formatViewResultForCopy() string {
454	var meta tools.ViewResponseMetadata
455	if m.result.Metadata != "" {
456		json.Unmarshal([]byte(m.result.Metadata), &meta)
457	}
458
459	if meta.Content == "" {
460		return m.result.Content
461	}
462
463	lang := ""
464	if meta.FilePath != "" {
465		ext := strings.ToLower(filepath.Ext(meta.FilePath))
466		switch ext {
467		case ".go":
468			lang = "go"
469		case ".js", ".mjs":
470			lang = "javascript"
471		case ".ts":
472			lang = "typescript"
473		case ".py":
474			lang = "python"
475		case ".rs":
476			lang = "rust"
477		case ".java":
478			lang = "java"
479		case ".c":
480			lang = "c"
481		case ".cpp", ".cc", ".cxx":
482			lang = "cpp"
483		case ".sh", ".bash":
484			lang = "bash"
485		case ".json":
486			lang = "json"
487		case ".yaml", ".yml":
488			lang = "yaml"
489		case ".xml":
490			lang = "xml"
491		case ".html":
492			lang = "html"
493		case ".css":
494			lang = "css"
495		case ".md":
496			lang = "markdown"
497		}
498	}
499
500	var result strings.Builder
501	if lang != "" {
502		result.WriteString(fmt.Sprintf("```%s\n", lang))
503	} else {
504		result.WriteString("```\n")
505	}
506	result.WriteString(meta.Content)
507	result.WriteString("\n```")
508
509	return result.String()
510}
511
512func (m *toolCallCmp) formatEditResultForCopy() string {
513	var meta tools.EditResponseMetadata
514	if m.result.Metadata == "" {
515		return m.result.Content
516	}
517
518	if json.Unmarshal([]byte(m.result.Metadata), &meta) != nil {
519		return m.result.Content
520	}
521
522	var params tools.EditParams
523	json.Unmarshal([]byte(m.call.Input), &params)
524
525	var result strings.Builder
526
527	if meta.OldContent != "" || meta.NewContent != "" {
528		fileName := params.FilePath
529		if fileName != "" {
530			fileName = fsext.PrettyPath(fileName)
531		}
532		diffContent, additions, removals := diff.GenerateDiff(meta.OldContent, meta.NewContent, fileName)
533
534		result.WriteString(fmt.Sprintf("Changes: +%d -%d\n", additions, removals))
535		result.WriteString("```diff\n")
536		result.WriteString(diffContent)
537		result.WriteString("\n```")
538	}
539
540	return result.String()
541}
542
543func (m *toolCallCmp) formatMultiEditResultForCopy() string {
544	var meta tools.MultiEditResponseMetadata
545	if m.result.Metadata == "" {
546		return m.result.Content
547	}
548
549	if json.Unmarshal([]byte(m.result.Metadata), &meta) != nil {
550		return m.result.Content
551	}
552
553	var params tools.MultiEditParams
554	json.Unmarshal([]byte(m.call.Input), &params)
555
556	var result strings.Builder
557	if meta.OldContent != "" || meta.NewContent != "" {
558		fileName := params.FilePath
559		if fileName != "" {
560			fileName = fsext.PrettyPath(fileName)
561		}
562		diffContent, additions, removals := diff.GenerateDiff(meta.OldContent, meta.NewContent, fileName)
563
564		result.WriteString(fmt.Sprintf("Changes: +%d -%d\n", additions, removals))
565		result.WriteString("```diff\n")
566		result.WriteString(diffContent)
567		result.WriteString("\n```")
568	}
569
570	return result.String()
571}
572
573func (m *toolCallCmp) formatWriteResultForCopy() string {
574	var params tools.WriteParams
575	if json.Unmarshal([]byte(m.call.Input), &params) != nil {
576		return m.result.Content
577	}
578
579	lang := ""
580	if params.FilePath != "" {
581		ext := strings.ToLower(filepath.Ext(params.FilePath))
582		switch ext {
583		case ".go":
584			lang = "go"
585		case ".js", ".mjs":
586			lang = "javascript"
587		case ".ts":
588			lang = "typescript"
589		case ".py":
590			lang = "python"
591		case ".rs":
592			lang = "rust"
593		case ".java":
594			lang = "java"
595		case ".c":
596			lang = "c"
597		case ".cpp", ".cc", ".cxx":
598			lang = "cpp"
599		case ".sh", ".bash":
600			lang = "bash"
601		case ".json":
602			lang = "json"
603		case ".yaml", ".yml":
604			lang = "yaml"
605		case ".xml":
606			lang = "xml"
607		case ".html":
608			lang = "html"
609		case ".css":
610			lang = "css"
611		case ".md":
612			lang = "markdown"
613		}
614	}
615
616	var result strings.Builder
617	result.WriteString(fmt.Sprintf("File: %s\n", fsext.PrettyPath(params.FilePath)))
618	if lang != "" {
619		result.WriteString(fmt.Sprintf("```%s\n", lang))
620	} else {
621		result.WriteString("```\n")
622	}
623	result.WriteString(params.Content)
624	result.WriteString("\n```")
625
626	return result.String()
627}
628
629func (m *toolCallCmp) formatFetchResultForCopy() string {
630	var params tools.FetchParams
631	if json.Unmarshal([]byte(m.call.Input), &params) != nil {
632		return m.result.Content
633	}
634
635	var result strings.Builder
636	if params.URL != "" {
637		result.WriteString(fmt.Sprintf("URL: %s\n", params.URL))
638	}
639	if params.Format != "" {
640		result.WriteString(fmt.Sprintf("Format: %s\n", params.Format))
641	}
642	if params.Timeout > 0 {
643		result.WriteString(fmt.Sprintf("Timeout: %ds\n", params.Timeout))
644	}
645	result.WriteString("\n")
646
647	result.WriteString(m.result.Content)
648
649	return result.String()
650}
651
652func (m *toolCallCmp) formatAgenticFetchResultForCopy() string {
653	var params tools.AgenticFetchParams
654	if json.Unmarshal([]byte(m.call.Input), &params) != nil {
655		return m.result.Content
656	}
657
658	var result strings.Builder
659	if params.URL != "" {
660		result.WriteString(fmt.Sprintf("URL: %s\n", params.URL))
661	}
662	if params.Prompt != "" {
663		result.WriteString(fmt.Sprintf("Prompt: %s\n\n", params.Prompt))
664	}
665
666	result.WriteString("```markdown\n")
667	result.WriteString(m.result.Content)
668	result.WriteString("\n```")
669
670	return result.String()
671}
672
673func (m *toolCallCmp) formatWebFetchResultForCopy() string {
674	var params tools.WebFetchParams
675	if json.Unmarshal([]byte(m.call.Input), &params) != nil {
676		return m.result.Content
677	}
678
679	var result strings.Builder
680	result.WriteString(fmt.Sprintf("URL: %s\n\n", params.URL))
681	result.WriteString("```markdown\n")
682	result.WriteString(m.result.Content)
683	result.WriteString("\n```")
684
685	return result.String()
686}
687
688func (m *toolCallCmp) formatAgentResultForCopy() string {
689	var result strings.Builder
690
691	if len(m.nestedToolCalls) > 0 {
692		result.WriteString("### Nested Tool Calls:\n")
693		for i, nestedCall := range m.nestedToolCalls {
694			nestedContent := nestedCall.(*toolCallCmp).formatToolForCopy()
695			indentedContent := strings.ReplaceAll(nestedContent, "\n", "\n  ")
696			result.WriteString(fmt.Sprintf("%d. %s\n", i+1, indentedContent))
697			if i < len(m.nestedToolCalls)-1 {
698				result.WriteString("\n")
699			}
700		}
701
702		if m.result.Content != "" {
703			result.WriteString("\n### Final Result:\n")
704		}
705	}
706
707	if m.result.Content != "" {
708		result.WriteString(fmt.Sprintf("```markdown\n%s\n```", m.result.Content))
709	}
710
711	return result.String()
712}
713
714// SetToolCall updates the tool call data and stops spinning if finished
715func (m *toolCallCmp) SetToolCall(call message.ToolCall) {
716	m.call = call
717	if m.call.Finished {
718		m.spinning = false
719	}
720}
721
722// ParentMessageID returns the ID of the message that initiated this tool call
723func (m *toolCallCmp) ParentMessageID() string {
724	return m.parentMessageID
725}
726
727// SetToolResult updates the tool result and stops the spinning animation
728func (m *toolCallCmp) SetToolResult(result message.ToolResult) {
729	m.result = result
730	m.spinning = false
731}
732
733// GetToolCall returns the current tool call data
734func (m *toolCallCmp) GetToolCall() message.ToolCall {
735	return m.call
736}
737
738// GetToolResult returns the current tool result data
739func (m *toolCallCmp) GetToolResult() message.ToolResult {
740	return m.result
741}
742
743// GetNestedToolCalls returns the nested tool calls
744func (m *toolCallCmp) GetNestedToolCalls() []ToolCallCmp {
745	return m.nestedToolCalls
746}
747
748// SetNestedToolCalls sets the nested tool calls
749func (m *toolCallCmp) SetNestedToolCalls(calls []ToolCallCmp) {
750	m.nestedToolCalls = calls
751	for _, nested := range m.nestedToolCalls {
752		nested.SetSize(m.width, 0)
753	}
754}
755
756// SetIsNested sets whether this tool call is nested within another
757func (m *toolCallCmp) SetIsNested(isNested bool) {
758	m.isNested = isNested
759}
760
761// Rendering methods
762
763// renderPending displays the tool name with a loading animation for pending tool calls
764func (m *toolCallCmp) renderPending() string {
765	t := styles.CurrentTheme()
766	icon := t.S().Base.Foreground(t.GreenDark).Render(styles.ToolPending)
767	if m.isNested {
768		tool := t.S().Base.Foreground(t.FgHalfMuted).Render(prettifyToolName(m.call.Name))
769		return fmt.Sprintf("%s %s %s", icon, tool, m.anim.View())
770	}
771	tool := t.S().Base.Foreground(t.Blue).Render(prettifyToolName(m.call.Name))
772	return fmt.Sprintf("%s %s %s", icon, tool, m.anim.View())
773}
774
775// style returns the lipgloss style for the tool call component.
776// Applies muted colors and focus-dependent border styles.
777func (m *toolCallCmp) style() lipgloss.Style {
778	t := styles.CurrentTheme()
779
780	if m.isNested {
781		return t.S().Muted
782	}
783	style := t.S().Muted.PaddingLeft(2)
784
785	if m.focused {
786		style = style.PaddingLeft(1).BorderStyle(focusedMessageBorder).BorderLeft(true).BorderForeground(t.GreenDark)
787	}
788	return style
789}
790
791// textWidth calculates the available width for text content,
792// accounting for borders and padding
793func (m *toolCallCmp) textWidth() int {
794	if m.isNested {
795		return m.width - 6
796	}
797	return m.width - 5 // take into account the border and PaddingLeft
798}
799
800// fit truncates content to fit within the specified width with ellipsis
801func (m *toolCallCmp) fit(content string, width int) string {
802	if lipgloss.Width(content) <= width {
803		return content
804	}
805	t := styles.CurrentTheme()
806	lineStyle := t.S().Muted
807	dots := lineStyle.Render("…")
808	return ansi.Truncate(content, width, dots)
809}
810
811// Focus management methods
812
813// Blur removes focus from the tool call component
814func (m *toolCallCmp) Blur() tea.Cmd {
815	m.focused = false
816	return nil
817}
818
819// Focus sets focus on the tool call component
820func (m *toolCallCmp) Focus() tea.Cmd {
821	m.focused = true
822	return nil
823}
824
825// IsFocused returns whether the tool call component is currently focused
826func (m *toolCallCmp) IsFocused() bool {
827	return m.focused
828}
829
830// Size management methods
831
832// GetSize returns the current dimensions of the tool call component
833func (m *toolCallCmp) GetSize() (int, int) {
834	return m.width, 0
835}
836
837// SetSize updates the width of the tool call component for text wrapping
838func (m *toolCallCmp) SetSize(width int, height int) tea.Cmd {
839	m.width = width
840	for _, nested := range m.nestedToolCalls {
841		nested.SetSize(width, height)
842	}
843	return nil
844}
845
846// shouldSpin determines whether the tool call should show a loading animation.
847// Returns true if the tool call is not finished or if the result doesn't match the call ID.
848func (m *toolCallCmp) shouldSpin() bool {
849	return !m.call.Finished && !m.cancelled
850}
851
852// Spinning returns whether the tool call is currently showing a loading animation
853func (m *toolCallCmp) Spinning() bool {
854	if m.spinning {
855		return true
856	}
857	for _, nested := range m.nestedToolCalls {
858		if nested.Spinning() {
859			return true
860		}
861	}
862	return m.spinning
863}
864
865func (m *toolCallCmp) ID() string {
866	return m.call.ID
867}
868
869// SetPermissionRequested marks that a permission request was made for this tool call
870func (m *toolCallCmp) SetPermissionRequested() {
871	m.permissionRequested = true
872}
873
874// SetPermissionGranted marks that permission was granted for this tool call
875func (m *toolCallCmp) SetPermissionGranted() {
876	m.permissionGranted = true
877}