ratkit 0.2.14

A comprehensive collection of reusable TUI components for ratatui including resizable splits, tree views, markdown rendering, toast notifications, dialogs, and terminal embedding
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
//! ToolPart component for rendering tool calls in AI Chat.
//!
//! This module provides the [`ToolPart`] widget that dispatches to the correct
//! tool-specific component based on the tool type. It uses a PART_MAPPING pattern
//! to map tool types to their corresponding renderable components.

use ratatui::{
    buffer::Buffer,
    layout::Rect,
    style::{Color, Modifier, Style},
    text::Span,
    widgets::Widget,
};

use crate::widgets::ai_chat::components::theme::ChatColors;

/// Enum representing different tool types that can be called.
///
/// Each variant corresponds to a specific tool with its own rendering requirements:
/// - Simple tools render inline
/// - Complex tools render as blocks with detailed information
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ToolType {
    /// Bash/shell command execution
    Bash,
    /// File writing operation
    Write,
    /// File editing operation
    Edit,
    /// File reading operation
    Read,
    /// File glob pattern matching
    Glob,
    /// Content search
    Grep,
    /// Directory listing
    List,
    /// Web URL fetching
    WebFetch,
    /// Web search
    WebSearch,
    /// Code search
    CodeSearch,
    /// Task/subagent delegation
    Task,
    /// Patch application
    ApplyPatch,
    /// Todo/note writing
    TodoWrite,
    /// Question to user
    Question,
    /// Skill invocation
    Skill,
    /// Generic/unknown tool
    Generic,
}

impl ToolType {
    /// Convert a tool name string to ToolType.
    pub fn from_name(name: &str) -> Self {
        match name.to_lowercase().as_str() {
            "bash" | "shell" | "sh" | "zsh" => ToolType::Bash,
            "write" | "filesystem_write" | "write_file" => ToolType::Write,
            "edit" | "filesystem_edit" | "edit_file" => ToolType::Edit,
            "read" | "filesystem_read" | "read_file" => ToolType::Read,
            "glob" | "filesystem_glob" => ToolType::Glob,
            "grep" | "search" | "content_search" => ToolType::Grep,
            "list" | "ls" | "directory_list" => ToolType::List,
            "webfetch" | "fetch" | "http_get" => ToolType::WebFetch,
            "websearch" | "search_web" => ToolType::WebSearch,
            "codesearch" | "search_code" => ToolType::CodeSearch,
            "task" | "subagent" | "delegate" => ToolType::Task,
            "applypatch" | "patch" | "apply_patch" => ToolType::ApplyPatch,
            "todowrite" | "todo" | "note" => ToolType::TodoWrite,
            "question" | "ask" | "clarify" => ToolType::Question,
            "skill" | "invoke" | "call" => ToolType::Skill,
            _ => ToolType::Generic,
        }
    }

    /// Check if this tool type should render as inline (simple) or block (complex).
    pub fn is_inline(&self) -> bool {
        matches!(
            self,
            ToolType::Read
                | ToolType::Glob
                | ToolType::List
                | ToolType::TodoWrite
                | ToolType::Question
        )
    }

    /// Get the display name for this tool type.
    pub fn display_name(&self) -> &'static str {
        match self {
            ToolType::Bash => "Bash",
            ToolType::Write => "Write",
            ToolType::Edit => "Edit",
            ToolType::Read => "Read",
            ToolType::Glob => "Glob",
            ToolType::Grep => "Grep",
            ToolType::List => "List",
            ToolType::WebFetch => "WebFetch",
            ToolType::WebSearch => "WebSearch",
            ToolType::CodeSearch => "CodeSearch",
            ToolType::Task => "Task",
            ToolType::ApplyPatch => "ApplyPatch",
            ToolType::TodoWrite => "TodoWrite",
            ToolType::Question => "Question",
            ToolType::Skill => "Skill",
            ToolType::Generic => "Tool",
        }
    }

    /// Get the icon for this tool type.
    pub fn icon(&self) -> &'static str {
        match self {
            ToolType::Bash => "",
            ToolType::Write => "✏️",
            ToolType::Edit => "🔧",
            ToolType::Read => "📖",
            ToolType::Glob => "🔍",
            ToolType::Grep => "🔎",
            ToolType::List => "📁",
            ToolType::WebFetch => "🌐",
            ToolType::WebSearch => "🔎",
            ToolType::CodeSearch => "💻",
            ToolType::Task => "🎯",
            ToolType::ApplyPatch => "🩹",
            ToolType::TodoWrite => "📝",
            ToolType::Question => "",
            ToolType::Skill => "⚙️",
            ToolType::Generic => "🔧",
        }
    }
}

/// Tool call data containing the tool name and arguments.
#[derive(Debug, Clone, PartialEq)]
pub struct ToolCall {
    /// The tool name
    pub name: String,
    /// The tool arguments (JSON string)
    pub arguments: String,
    /// Optional result from tool execution
    pub result: Option<String>,
    /// Whether the tool is currently executing
    pub executing: bool,
}

impl ToolCall {
    /// Create a new tool call.
    pub fn new(name: String, arguments: String) -> Self {
        Self {
            name,
            arguments,
            result: None,
            executing: false,
        }
    }

    /// Set the result.
    pub fn with_result(mut self, result: String) -> Self {
        self.result = Some(result);
        self
    }

    /// Set executing state.
    pub fn executing(mut self, executing: bool) -> Self {
        self.executing = executing;
        self
    }

    /// Get the tool type.
    pub fn tool_type(&self) -> ToolType {
        ToolType::from_name(&self.name)
    }
}

/// ToolPart component that dispatches to the correct tool renderer.
///
/// Uses PART_MAPPING to map ToolType to the appropriate render function.
pub struct ToolPart<'a> {
    /// The tool call data
    tool_call: &'a ToolCall,
    /// Whether to show detailed information
    show_details: bool,
    /// Custom colors (optional)
    colors: Option<ChatColors>,
}

impl<'a> ToolPart<'a> {
    /// Create a new ToolPart with the given tool call.
    pub fn new(tool_call: &'a ToolCall) -> Self {
        Self {
            tool_call,
            show_details: true,
            colors: None,
        }
    }

    /// Set show_details flag.
    pub fn show_details(mut self, show_details: bool) -> Self {
        self.show_details = show_details;
        self
    }

    /// Set custom colors.
    pub fn colors(mut self, colors: ChatColors) -> Self {
        self.colors = Some(colors);
        self
    }

    /// Get the colors to use.
    fn get_colors(&self) -> ChatColors {
        self.colors.clone().unwrap_or_default()
    }

    /// Render inline tool (simple display).
    fn render_inline(&self, area: Rect, buf: &mut Buffer) {
        let colors = self.get_colors();
        let tool_type = self.tool_call.tool_type();

        // Status icon and tool info
        let status_icon = if self.tool_call.executing {
            ""
        } else if self.tool_call.result.is_some() {
            ""
        } else {
            tool_type.icon()
        };

        let status_style = if self.tool_call.executing {
            Style::default()
                .fg(colors.warning)
                .add_modifier(Modifier::BOLD)
        } else if self.tool_call.result.is_some() {
            Style::default()
                .fg(colors.success)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default()
                .fg(colors.primary)
                .add_modifier(Modifier::BOLD)
        };

        let content = format!("{} {}", status_icon, tool_type.display_name());
        let span = Span::styled(content, status_style);
        buf.set_span(area.x, area.y, &span, area.width);
    }

    /// Render block tool (detailed display).
    fn render_block(&self, area: Rect, buf: &mut Buffer) {
        let colors = self.get_colors();
        let tool_type = self.tool_call.tool_type();
        let max_y = area.y + area.height;
        let mut y = area.y;

        // Draw left border
        let border_color = if self.tool_call.executing {
            colors.warning
        } else if self.tool_call.result.is_some() {
            colors.success
        } else {
            colors.primary
        };

        for y_pos in area.y..max_y {
            buf.get_mut(area.x, y_pos)
                .set_style(Style::default().fg(border_color));
        }

        // Header with tool info
        let status_icon = if self.tool_call.executing {
            "⚙️  Executing"
        } else if self.tool_call.result.is_some() {
            "✓  Done"
        } else {
            "🔧  Tool"
        };

        let header_style = Style::default()
            .fg(border_color)
            .add_modifier(Modifier::BOLD);

        let header = format!("{} {}", status_icon, tool_type.display_name());
        buf.set_span(
            area.x + 2,
            y,
            &Span::styled(header, header_style),
            area.width - 2,
        );
        y += 1;

        // Tool name in arguments
        if y < max_y {
            let args_label = Span::styled("  name: ", Style::default().fg(colors.text_muted));
            buf.set_span(area.x + 2, y, &args_label, area.width - 2);

            let name_value = Span::styled(
                self.tool_call.name.clone(),
                Style::default()
                    .fg(colors.text)
                    .add_modifier(Modifier::BOLD),
            );
            buf.set_span(area.x + 2 + 7, y, &name_value, area.width.saturating_sub(9));
            y += 1;
        }

        // Arguments (truncated for block display)
        if y < max_y && !self.tool_call.arguments.is_empty() {
            let args_preview = if self.tool_call.arguments.len() > 50 {
                format!("{}...", &self.tool_call.arguments[..50])
            } else {
                self.tool_call.arguments.clone()
            };

            let args_span = Span::styled(
                format!("  args: {}", args_preview),
                Style::default().fg(colors.text_muted),
            );
            buf.set_span(area.x + 2, y, &args_span, area.width - 2);
            y += 1;
        }

        // Result if present
        if let Some(result) = &self.tool_call.result {
            if y < max_y {
                let result_preview = if result.len() > 80 {
                    format!("{}...", &result[..80])
                } else {
                    result.clone()
                };

                let result_span = Span::styled(
                    format!("{}", result_preview),
                    Style::default().fg(colors.success),
                );
                buf.set_span(area.x + 2, y, &result_span, area.width - 2);
            }
        }
    }
}

impl<'a> Widget for ToolPart<'a> {
    fn render(self, area: Rect, buf: &mut Buffer) {
        // If show_details is false, don't render anything (hidden)
        if !self.show_details {
            return;
        }

        if self.tool_call.tool_type().is_inline() {
            self.render_inline(area, buf);
        } else {
            self.render_block(area, buf);
        }
    }
}

/// Builder for ToolPart with custom rendering options.
pub struct ToolPartRenderer<'a> {
    tool_call: &'a ToolCall,
    show_details: bool,
    colors: ChatColors,
}

impl<'a> ToolPartRenderer<'a> {
    /// Create a new renderer.
    pub fn new(tool_call: &'a ToolCall) -> Self {
        Self {
            tool_call,
            show_details: true,
            colors: ChatColors::default(),
        }
    }

    /// Set show_details flag.
    pub fn show_details(mut self, show_details: bool) -> Self {
        self.show_details = show_details;
        self
    }

    /// Set custom colors.
    pub fn colors(mut self, colors: ChatColors) -> Self {
        self.colors = colors;
        self
    }

    /// Render the tool part.
    pub fn render(self, area: Rect, buf: &mut Buffer) {
        let part = ToolPart {
            tool_call: self.tool_call,
            show_details: self.show_details,
            colors: Some(self.colors),
        };
        part.render(area, buf);
    }
}

// === PART_MAPPING pattern ===

/// Type alias for tool part render functions.
type ToolPartRendererFn<'a> = fn(&'a ToolCall, Rect, &mut Buffer, &ChatColors);

/// Map of ToolType to its corresponding renderer function.
///
/// This PART_MAPPING pattern allows easy extension for new tool types.
pub const PART_MAPPING: &[(ToolType, ToolPartRendererFn)] = &[
    (ToolType::Bash, render_bash_tool),
    (ToolType::Write, render_write_tool),
    (ToolType::Edit, render_edit_tool),
    (ToolType::Read, render_read_tool),
    (ToolType::Glob, render_glob_tool),
    (ToolType::Grep, render_grep_tool),
    (ToolType::List, render_list_tool),
    (ToolType::WebFetch, render_webfetch_tool),
    (ToolType::WebSearch, render_websearch_tool),
    (ToolType::CodeSearch, render_codesearch_tool),
    (ToolType::Task, render_task_tool),
    (ToolType::ApplyPatch, render_applypatch_tool),
    (ToolType::TodoWrite, render_todowrite_tool),
    (ToolType::Question, render_question_tool),
    (ToolType::Skill, render_skill_tool),
    (ToolType::Generic, render_generic_tool),
];

/// Get the renderer function for a tool type.
pub fn get_renderer_for_tool(tool_type: &ToolType) -> Option<ToolPartRendererFn> {
    PART_MAPPING
        .iter()
        .find(|(t, _)| t == tool_type)
        .map(|(_, f)| *f)
}

// === Individual tool renderers ===

fn render_bash_tool(call: &ToolCall, area: Rect, buf: &mut Buffer, colors: &ChatColors) {
    let status = if call.executing { "" } else { "" };
    let style = if call.executing {
        colors.warning
    } else {
        colors.primary
    };

    let content = format!("{} Bash: {}", status, call.arguments);
    let span = Span::styled(content, Style::default().fg(style));
    buf.set_span(area.x, area.y, &span, area.width);
}

fn render_write_tool(call: &ToolCall, area: Rect, buf: &mut Buffer, colors: &ChatColors) {
    let content = format!("✏️  Write: {}", call.arguments);
    let span = Span::styled(content, Style::default().fg(colors.primary));
    buf.set_span(area.x, area.y, &span, area.width);
}

fn render_edit_tool(call: &ToolCall, area: Rect, buf: &mut Buffer, colors: &ChatColors) {
    let content = format!("🔧  Edit: {}", call.arguments);
    let span = Span::styled(content, Style::default().fg(colors.secondary));
    buf.set_span(area.x, area.y, &span, area.width);
}

fn render_read_tool(call: &ToolCall, area: Rect, buf: &mut Buffer, colors: &ChatColors) {
    let content = format!("📖  Read: {}", call.arguments);
    let span = Span::styled(content, Style::default().fg(colors.text));
    buf.set_span(area.x, area.y, &span, area.width);
}

fn render_glob_tool(call: &ToolCall, area: Rect, buf: &mut Buffer, colors: &ChatColors) {
    let content = format!("🔍  Glob: {}", call.arguments);
    let span = Span::styled(content, Style::default().fg(colors.text));
    buf.set_span(area.x, area.y, &span, area.width);
}

fn render_grep_tool(call: &ToolCall, area: Rect, buf: &mut Buffer, colors: &ChatColors) {
    let content = format!("🔎  Grep: {}", call.arguments);
    let span = Span::styled(content, Style::default().fg(colors.accent));
    buf.set_span(area.x, area.y, &span, area.width);
}

fn render_list_tool(call: &ToolCall, area: Rect, buf: &mut Buffer, colors: &ChatColors) {
    let content = format!("📁  List: {}", call.arguments);
    let span = Span::styled(content, Style::default().fg(colors.text));
    buf.set_span(area.x, area.y, &span, area.width);
}

fn render_webfetch_tool(call: &ToolCall, area: Rect, buf: &mut Buffer, colors: &ChatColors) {
    let content = format!("🌐  Fetch: {}", call.arguments);
    let span = Span::styled(content, Style::default().fg(colors.primary));
    buf.set_span(area.x, area.y, &span, area.width);
}

fn render_websearch_tool(call: &ToolCall, area: Rect, buf: &mut Buffer, colors: &ChatColors) {
    let content = format!("🔎  Search: {}", call.arguments);
    let span = Span::styled(content, Style::default().fg(colors.primary));
    buf.set_span(area.x, area.y, &span, area.width);
}

fn render_codesearch_tool(call: &ToolCall, area: Rect, buf: &mut Buffer, colors: &ChatColors) {
    let content = format!("💻  CodeSearch: {}", call.arguments);
    let span = Span::styled(content, Style::default().fg(colors.secondary));
    buf.set_span(area.x, area.y, &span, area.width);
}

fn render_task_tool(call: &ToolCall, area: Rect, buf: &mut Buffer, colors: &ChatColors) {
    let content = format!("🎯  Task: {}", call.arguments);
    let span = Span::styled(content, Style::default().fg(colors.accent));
    buf.set_span(area.x, area.y, &span, area.width);
}

fn render_applypatch_tool(call: &ToolCall, area: Rect, buf: &mut Buffer, colors: &ChatColors) {
    let content = format!("🩹  ApplyPatch: {}", call.arguments);
    let span = Span::styled(content, Style::default().fg(colors.warning));
    buf.set_span(area.x, area.y, &span, area.width);
}

fn render_todowrite_tool(call: &ToolCall, area: Rect, buf: &mut Buffer, colors: &ChatColors) {
    let content = format!("📝  Todo: {}", call.arguments);
    let span = Span::styled(content, Style::default().fg(colors.text));
    buf.set_span(area.x, area.y, &span, area.width);
}

fn render_question_tool(call: &ToolCall, area: Rect, buf: &mut Buffer, colors: &ChatColors) {
    let content = format!("❓  Question: {}", call.arguments);
    let span = Span::styled(content, Style::default().fg(colors.warning));
    buf.set_span(area.x, area.y, &span, area.width);
}

fn render_skill_tool(call: &ToolCall, area: Rect, buf: &mut Buffer, colors: &ChatColors) {
    let content = format!("⚙️  Skill: {}", call.arguments);
    let span = Span::styled(content, Style::default().fg(colors.secondary));
    buf.set_span(area.x, area.y, &span, area.width);
}

fn render_generic_tool(call: &ToolCall, area: Rect, buf: &mut Buffer, colors: &ChatColors) {
    let content = format!("🔧  {}: {}", call.name, call.arguments);
    let span = Span::styled(content, Style::default().fg(colors.text));
    buf.set_span(area.x, area.y, &span, area.width);
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_tool_type_from_name() {
        assert_eq!(ToolType::from_name("bash"), ToolType::Bash);
        assert_eq!(ToolType::from_name("Write"), ToolType::Write);
        assert_eq!(ToolType::from_name("filesystem_read"), ToolType::Read);
        assert_eq!(ToolType::from_name("unknown_tool"), ToolType::Generic);
    }

    #[test]
    fn test_tool_type_is_inline() {
        assert!(ToolType::Read.is_inline());
        assert!(ToolType::Glob.is_inline());
        assert!(!ToolType::Bash.is_inline());
        assert!(!ToolType::Write.is_inline());
    }

    #[test]
    fn test_tool_type_display_name() {
        assert_eq!(ToolType::Bash.display_name(), "Bash");
        assert_eq!(ToolType::Write.display_name(), "Write");
    }

    #[test]
    fn test_tool_type_icon() {
        assert_eq!(ToolType::Bash.icon(), "");
        assert_eq!(ToolType::Read.icon(), "📖");
    }

    #[test]
    fn test_tool_call_builder() {
        let call = ToolCall::new("bash".to_string(), "ls -la".to_string());
        assert_eq!(call.name, "bash");
        assert_eq!(call.arguments, "ls -la");
        assert!(call.result.is_none());
        assert!(!call.executing);
    }

    #[test]
    fn test_tool_call_with_options() {
        let call = ToolCall::new("read".to_string(), "/test.txt".to_string())
            .with_result("file content".to_string())
            .executing(true);

        assert!(call.result.is_some());
        assert!(call.executing);
    }

    #[test]
    fn test_tool_part_builder() {
        let call = ToolCall::new("bash".to_string(), "echo hello".to_string());
        let part = ToolPart::new(&call);

        assert!(part.show_details);
    }

    #[test]
    fn test_tool_part_options() {
        let call = ToolCall::new("bash".to_string(), "echo hello".to_string());
        let part = ToolPart::new(&call).show_details(false);

        assert!(!part.show_details);
    }

    #[test]
    fn test_get_renderer_for_tool() {
        let renderer = get_renderer_for_tool(&ToolType::Bash);
        assert!(renderer.is_some());

        let renderer = get_renderer_for_tool(&ToolType::Generic);
        assert!(renderer.is_some());
    }

    #[test]
    fn test_part_mapping_length() {
        // Verify all tool types have renderers
        assert!(PART_MAPPING.len() >= 16);
    }
}