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