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