tool.go

  1package messages
  2
  3import (
  4	"encoding/json"
  5	"fmt"
  6	"path/filepath"
  7	"strings"
  8	"time"
  9
 10	"github.com/atotto/clipboard"
 11	"github.com/charmbracelet/bubbles/v2/key"
 12	tea "github.com/charmbracelet/bubbletea/v2"
 13	"github.com/charmbracelet/crush/internal/agent"
 14	"github.com/charmbracelet/crush/internal/agent/tools"
 15	"github.com/charmbracelet/crush/internal/diff"
 16	"github.com/charmbracelet/crush/internal/fsext"
 17	"github.com/charmbracelet/crush/internal/message"
 18	"github.com/charmbracelet/crush/internal/permission"
 19	"github.com/charmbracelet/crush/internal/tui/components/anim"
 20	"github.com/charmbracelet/crush/internal/tui/components/core/layout"
 21	"github.com/charmbracelet/crush/internal/tui/styles"
 22	"github.com/charmbracelet/crush/internal/tui/util"
 23	"github.com/charmbracelet/lipgloss/v2"
 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			parts = append(parts, fmt.Sprintf("**URL:** %s", params.URL))
305			if params.Prompt != "" {
306				parts = append(parts, fmt.Sprintf("**Prompt:** %s", params.Prompt))
307			}
308			return strings.Join(parts, "\n")
309		}
310	case tools.WebFetchToolName:
311		var params tools.WebFetchParams
312		if json.Unmarshal([]byte(m.call.Input), &params) == nil {
313			return fmt.Sprintf("**URL:** %s", params.URL)
314		}
315	case tools.GrepToolName:
316		var params tools.GrepParams
317		if json.Unmarshal([]byte(m.call.Input), &params) == nil {
318			var parts []string
319			parts = append(parts, fmt.Sprintf("**Pattern:** %s", params.Pattern))
320			if params.Path != "" {
321				parts = append(parts, fmt.Sprintf("**Path:** %s", params.Path))
322			}
323			if params.Include != "" {
324				parts = append(parts, fmt.Sprintf("**Include:** %s", params.Include))
325			}
326			if params.LiteralText {
327				parts = append(parts, "**Literal:** true")
328			}
329			return strings.Join(parts, "\n")
330		}
331	case tools.GlobToolName:
332		var params tools.GlobParams
333		if json.Unmarshal([]byte(m.call.Input), &params) == nil {
334			var parts []string
335			parts = append(parts, fmt.Sprintf("**Pattern:** %s", params.Pattern))
336			if params.Path != "" {
337				parts = append(parts, fmt.Sprintf("**Path:** %s", params.Path))
338			}
339			return strings.Join(parts, "\n")
340		}
341	case tools.LSToolName:
342		var params tools.LSParams
343		if json.Unmarshal([]byte(m.call.Input), &params) == nil {
344			path := params.Path
345			if path == "" {
346				path = "."
347			}
348			return fmt.Sprintf("**Path:** %s", fsext.PrettyPath(path))
349		}
350	case tools.DownloadToolName:
351		var params tools.DownloadParams
352		if json.Unmarshal([]byte(m.call.Input), &params) == nil {
353			var parts []string
354			parts = append(parts, fmt.Sprintf("**URL:** %s", params.URL))
355			parts = append(parts, fmt.Sprintf("**File Path:** %s", fsext.PrettyPath(params.FilePath)))
356			if params.Timeout > 0 {
357				parts = append(parts, fmt.Sprintf("**Timeout:** %s", (time.Duration(params.Timeout)*time.Second).String()))
358			}
359			return strings.Join(parts, "\n")
360		}
361	case tools.SourcegraphToolName:
362		var params tools.SourcegraphParams
363		if json.Unmarshal([]byte(m.call.Input), &params) == nil {
364			var parts []string
365			parts = append(parts, fmt.Sprintf("**Query:** %s", params.Query))
366			if params.Count > 0 {
367				parts = append(parts, fmt.Sprintf("**Count:** %d", params.Count))
368			}
369			if params.ContextWindow > 0 {
370				parts = append(parts, fmt.Sprintf("**Context:** %d", params.ContextWindow))
371			}
372			return strings.Join(parts, "\n")
373		}
374	case tools.DiagnosticsToolName:
375		return "**Project:** diagnostics"
376	case agent.AgentToolName:
377		var params agent.AgentParams
378		if json.Unmarshal([]byte(m.call.Input), &params) == nil {
379			return fmt.Sprintf("**Task:**\n%s", params.Prompt)
380		}
381	}
382
383	var params map[string]any
384	if json.Unmarshal([]byte(m.call.Input), &params) == nil {
385		var parts []string
386		for key, value := range params {
387			displayKey := strings.ReplaceAll(key, "_", " ")
388			if len(displayKey) > 0 {
389				displayKey = strings.ToUpper(displayKey[:1]) + displayKey[1:]
390			}
391			parts = append(parts, fmt.Sprintf("**%s:** %v", displayKey, value))
392		}
393		return strings.Join(parts, "\n")
394	}
395
396	return ""
397}
398
399func (m *toolCallCmp) formatResultForCopy() string {
400	switch m.call.Name {
401	case tools.BashToolName:
402		return m.formatBashResultForCopy()
403	case tools.ViewToolName:
404		return m.formatViewResultForCopy()
405	case tools.EditToolName:
406		return m.formatEditResultForCopy()
407	case tools.MultiEditToolName:
408		return m.formatMultiEditResultForCopy()
409	case tools.WriteToolName:
410		return m.formatWriteResultForCopy()
411	case tools.FetchToolName:
412		return m.formatFetchResultForCopy()
413	case tools.AgenticFetchToolName:
414		return m.formatAgenticFetchResultForCopy()
415	case tools.WebFetchToolName:
416		return m.formatWebFetchResultForCopy()
417	case agent.AgentToolName:
418		return m.formatAgentResultForCopy()
419	case tools.DownloadToolName, tools.GrepToolName, tools.GlobToolName, tools.LSToolName, tools.SourcegraphToolName, tools.DiagnosticsToolName:
420		return fmt.Sprintf("```\n%s\n```", m.result.Content)
421	default:
422		return m.result.Content
423	}
424}
425
426func (m *toolCallCmp) formatBashResultForCopy() string {
427	var meta tools.BashResponseMetadata
428	if m.result.Metadata != "" {
429		json.Unmarshal([]byte(m.result.Metadata), &meta)
430	}
431
432	output := meta.Output
433	if output == "" && m.result.Content != tools.BashNoOutput {
434		output = m.result.Content
435	}
436
437	if output == "" {
438		return ""
439	}
440
441	return fmt.Sprintf("```bash\n%s\n```", output)
442}
443
444func (m *toolCallCmp) formatViewResultForCopy() string {
445	var meta tools.ViewResponseMetadata
446	if m.result.Metadata != "" {
447		json.Unmarshal([]byte(m.result.Metadata), &meta)
448	}
449
450	if meta.Content == "" {
451		return m.result.Content
452	}
453
454	lang := ""
455	if meta.FilePath != "" {
456		ext := strings.ToLower(filepath.Ext(meta.FilePath))
457		switch ext {
458		case ".go":
459			lang = "go"
460		case ".js", ".mjs":
461			lang = "javascript"
462		case ".ts":
463			lang = "typescript"
464		case ".py":
465			lang = "python"
466		case ".rs":
467			lang = "rust"
468		case ".java":
469			lang = "java"
470		case ".c":
471			lang = "c"
472		case ".cpp", ".cc", ".cxx":
473			lang = "cpp"
474		case ".sh", ".bash":
475			lang = "bash"
476		case ".json":
477			lang = "json"
478		case ".yaml", ".yml":
479			lang = "yaml"
480		case ".xml":
481			lang = "xml"
482		case ".html":
483			lang = "html"
484		case ".css":
485			lang = "css"
486		case ".md":
487			lang = "markdown"
488		}
489	}
490
491	var result strings.Builder
492	if lang != "" {
493		result.WriteString(fmt.Sprintf("```%s\n", lang))
494	} else {
495		result.WriteString("```\n")
496	}
497	result.WriteString(meta.Content)
498	result.WriteString("\n```")
499
500	return result.String()
501}
502
503func (m *toolCallCmp) formatEditResultForCopy() string {
504	var meta tools.EditResponseMetadata
505	if m.result.Metadata == "" {
506		return m.result.Content
507	}
508
509	if json.Unmarshal([]byte(m.result.Metadata), &meta) != nil {
510		return m.result.Content
511	}
512
513	var params tools.EditParams
514	json.Unmarshal([]byte(m.call.Input), &params)
515
516	var result strings.Builder
517
518	if meta.OldContent != "" || meta.NewContent != "" {
519		fileName := params.FilePath
520		if fileName != "" {
521			fileName = fsext.PrettyPath(fileName)
522		}
523		diffContent, additions, removals := diff.GenerateDiff(meta.OldContent, meta.NewContent, fileName)
524
525		result.WriteString(fmt.Sprintf("Changes: +%d -%d\n", additions, removals))
526		result.WriteString("```diff\n")
527		result.WriteString(diffContent)
528		result.WriteString("\n```")
529	}
530
531	return result.String()
532}
533
534func (m *toolCallCmp) formatMultiEditResultForCopy() string {
535	var meta tools.MultiEditResponseMetadata
536	if m.result.Metadata == "" {
537		return m.result.Content
538	}
539
540	if json.Unmarshal([]byte(m.result.Metadata), &meta) != nil {
541		return m.result.Content
542	}
543
544	var params tools.MultiEditParams
545	json.Unmarshal([]byte(m.call.Input), &params)
546
547	var result strings.Builder
548	if meta.OldContent != "" || meta.NewContent != "" {
549		fileName := params.FilePath
550		if fileName != "" {
551			fileName = fsext.PrettyPath(fileName)
552		}
553		diffContent, additions, removals := diff.GenerateDiff(meta.OldContent, meta.NewContent, fileName)
554
555		result.WriteString(fmt.Sprintf("Changes: +%d -%d\n", additions, removals))
556		result.WriteString("```diff\n")
557		result.WriteString(diffContent)
558		result.WriteString("\n```")
559	}
560
561	return result.String()
562}
563
564func (m *toolCallCmp) formatWriteResultForCopy() string {
565	var params tools.WriteParams
566	if json.Unmarshal([]byte(m.call.Input), &params) != nil {
567		return m.result.Content
568	}
569
570	lang := ""
571	if params.FilePath != "" {
572		ext := strings.ToLower(filepath.Ext(params.FilePath))
573		switch ext {
574		case ".go":
575			lang = "go"
576		case ".js", ".mjs":
577			lang = "javascript"
578		case ".ts":
579			lang = "typescript"
580		case ".py":
581			lang = "python"
582		case ".rs":
583			lang = "rust"
584		case ".java":
585			lang = "java"
586		case ".c":
587			lang = "c"
588		case ".cpp", ".cc", ".cxx":
589			lang = "cpp"
590		case ".sh", ".bash":
591			lang = "bash"
592		case ".json":
593			lang = "json"
594		case ".yaml", ".yml":
595			lang = "yaml"
596		case ".xml":
597			lang = "xml"
598		case ".html":
599			lang = "html"
600		case ".css":
601			lang = "css"
602		case ".md":
603			lang = "markdown"
604		}
605	}
606
607	var result strings.Builder
608	result.WriteString(fmt.Sprintf("File: %s\n", fsext.PrettyPath(params.FilePath)))
609	if lang != "" {
610		result.WriteString(fmt.Sprintf("```%s\n", lang))
611	} else {
612		result.WriteString("```\n")
613	}
614	result.WriteString(params.Content)
615	result.WriteString("\n```")
616
617	return result.String()
618}
619
620func (m *toolCallCmp) formatFetchResultForCopy() string {
621	var params tools.FetchParams
622	if json.Unmarshal([]byte(m.call.Input), &params) != nil {
623		return m.result.Content
624	}
625
626	var result strings.Builder
627	if params.URL != "" {
628		result.WriteString(fmt.Sprintf("URL: %s\n", params.URL))
629	}
630	if params.Format != "" {
631		result.WriteString(fmt.Sprintf("Format: %s\n", params.Format))
632	}
633	if params.Timeout > 0 {
634		result.WriteString(fmt.Sprintf("Timeout: %ds\n", params.Timeout))
635	}
636	result.WriteString("\n")
637
638	result.WriteString(m.result.Content)
639
640	return result.String()
641}
642
643func (m *toolCallCmp) formatAgenticFetchResultForCopy() string {
644	var params tools.AgenticFetchParams
645	if json.Unmarshal([]byte(m.call.Input), &params) != nil {
646		return m.result.Content
647	}
648
649	var result strings.Builder
650	if params.URL != "" {
651		result.WriteString(fmt.Sprintf("URL: %s\n", params.URL))
652	}
653	if params.Prompt != "" {
654		result.WriteString(fmt.Sprintf("Prompt: %s\n\n", params.Prompt))
655	}
656
657	result.WriteString("```markdown\n")
658	result.WriteString(m.result.Content)
659	result.WriteString("\n```")
660
661	return result.String()
662}
663
664func (m *toolCallCmp) formatWebFetchResultForCopy() string {
665	var params tools.WebFetchParams
666	if json.Unmarshal([]byte(m.call.Input), &params) != nil {
667		return m.result.Content
668	}
669
670	var result strings.Builder
671	result.WriteString(fmt.Sprintf("URL: %s\n\n", params.URL))
672	result.WriteString("```markdown\n")
673	result.WriteString(m.result.Content)
674	result.WriteString("\n```")
675
676	return result.String()
677}
678
679func (m *toolCallCmp) formatAgentResultForCopy() string {
680	var result strings.Builder
681
682	if len(m.nestedToolCalls) > 0 {
683		result.WriteString("### Nested Tool Calls:\n")
684		for i, nestedCall := range m.nestedToolCalls {
685			nestedContent := nestedCall.(*toolCallCmp).formatToolForCopy()
686			indentedContent := strings.ReplaceAll(nestedContent, "\n", "\n  ")
687			result.WriteString(fmt.Sprintf("%d. %s\n", i+1, indentedContent))
688			if i < len(m.nestedToolCalls)-1 {
689				result.WriteString("\n")
690			}
691		}
692
693		if m.result.Content != "" {
694			result.WriteString("\n### Final Result:\n")
695		}
696	}
697
698	if m.result.Content != "" {
699		result.WriteString(fmt.Sprintf("```markdown\n%s\n```", m.result.Content))
700	}
701
702	return result.String()
703}
704
705// SetToolCall updates the tool call data and stops spinning if finished
706func (m *toolCallCmp) SetToolCall(call message.ToolCall) {
707	m.call = call
708	if m.call.Finished {
709		m.spinning = false
710	}
711}
712
713// ParentMessageID returns the ID of the message that initiated this tool call
714func (m *toolCallCmp) ParentMessageID() string {
715	return m.parentMessageID
716}
717
718// SetToolResult updates the tool result and stops the spinning animation
719func (m *toolCallCmp) SetToolResult(result message.ToolResult) {
720	m.result = result
721	m.spinning = false
722}
723
724// GetToolCall returns the current tool call data
725func (m *toolCallCmp) GetToolCall() message.ToolCall {
726	return m.call
727}
728
729// GetToolResult returns the current tool result data
730func (m *toolCallCmp) GetToolResult() message.ToolResult {
731	return m.result
732}
733
734// GetNestedToolCalls returns the nested tool calls
735func (m *toolCallCmp) GetNestedToolCalls() []ToolCallCmp {
736	return m.nestedToolCalls
737}
738
739// SetNestedToolCalls sets the nested tool calls
740func (m *toolCallCmp) SetNestedToolCalls(calls []ToolCallCmp) {
741	m.nestedToolCalls = calls
742	for _, nested := range m.nestedToolCalls {
743		nested.SetSize(m.width, 0)
744	}
745}
746
747// SetIsNested sets whether this tool call is nested within another
748func (m *toolCallCmp) SetIsNested(isNested bool) {
749	m.isNested = isNested
750}
751
752// Rendering methods
753
754// renderPending displays the tool name with a loading animation for pending tool calls
755func (m *toolCallCmp) renderPending() string {
756	t := styles.CurrentTheme()
757	icon := t.S().Base.Foreground(t.GreenDark).Render(styles.ToolPending)
758	if m.isNested {
759		tool := t.S().Base.Foreground(t.FgHalfMuted).Render(prettifyToolName(m.call.Name))
760		return fmt.Sprintf("%s %s %s", icon, tool, m.anim.View())
761	}
762	tool := t.S().Base.Foreground(t.Blue).Render(prettifyToolName(m.call.Name))
763	return fmt.Sprintf("%s %s %s", icon, tool, m.anim.View())
764}
765
766// style returns the lipgloss style for the tool call component.
767// Applies muted colors and focus-dependent border styles.
768func (m *toolCallCmp) style() lipgloss.Style {
769	t := styles.CurrentTheme()
770
771	if m.isNested {
772		return t.S().Muted
773	}
774	style := t.S().Muted.PaddingLeft(4)
775
776	if m.focused {
777		style = style.PaddingLeft(3).BorderStyle(focusedMessageBorder).BorderLeft(true).BorderForeground(t.GreenDark)
778	}
779	return style
780}
781
782// textWidth calculates the available width for text content,
783// accounting for borders and padding
784func (m *toolCallCmp) textWidth() int {
785	if m.isNested {
786		return m.width - 6
787	}
788	return m.width - 5 // take into account the border and PaddingLeft
789}
790
791// fit truncates content to fit within the specified width with ellipsis
792func (m *toolCallCmp) fit(content string, width int) string {
793	t := styles.CurrentTheme()
794	lineStyle := t.S().Muted
795	dots := lineStyle.Render("…")
796	return ansi.Truncate(content, width, dots)
797}
798
799// Focus management methods
800
801// Blur removes focus from the tool call component
802func (m *toolCallCmp) Blur() tea.Cmd {
803	m.focused = false
804	return nil
805}
806
807// Focus sets focus on the tool call component
808func (m *toolCallCmp) Focus() tea.Cmd {
809	m.focused = true
810	return nil
811}
812
813// IsFocused returns whether the tool call component is currently focused
814func (m *toolCallCmp) IsFocused() bool {
815	return m.focused
816}
817
818// Size management methods
819
820// GetSize returns the current dimensions of the tool call component
821func (m *toolCallCmp) GetSize() (int, int) {
822	return m.width, 0
823}
824
825// SetSize updates the width of the tool call component for text wrapping
826func (m *toolCallCmp) SetSize(width int, height int) tea.Cmd {
827	m.width = width
828	for _, nested := range m.nestedToolCalls {
829		nested.SetSize(width, height)
830	}
831	return nil
832}
833
834// shouldSpin determines whether the tool call should show a loading animation.
835// Returns true if the tool call is not finished or if the result doesn't match the call ID.
836func (m *toolCallCmp) shouldSpin() bool {
837	return !m.call.Finished && !m.cancelled
838}
839
840// Spinning returns whether the tool call is currently showing a loading animation
841func (m *toolCallCmp) Spinning() bool {
842	if m.spinning {
843		return true
844	}
845	for _, nested := range m.nestedToolCalls {
846		if nested.Spinning() {
847			return true
848		}
849	}
850	return m.spinning
851}
852
853func (m *toolCallCmp) ID() string {
854	return m.call.ID
855}
856
857// SetPermissionRequested marks that a permission request was made for this tool call
858func (m *toolCallCmp) SetPermissionRequested() {
859	m.permissionRequested = true
860}
861
862// SetPermissionGranted marks that permission was granted for this tool call
863func (m *toolCallCmp) SetPermissionGranted() {
864	m.permissionGranted = true
865}