rpi-tui 0.3.5

Terminal User Interface for pi-rust
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
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
//! Tool execution component for displaying tool calls.
//!
//! Based on TypeScript implementation:
//! packages/coding-agent/src/modes/interactive/components/tool-execution.ts

use std::any::Any;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Mutex;
use std::time::Instant;

use super::component::Component;
use crate::ansi::{bold, strip_ansi};
use crate::theme::{theme, theme_revision, ThemeColors};
use crate::utils::{apply_background_to_line, truncate_to_width, wrap_text_with_ansi};

/// Maximum diff lines rendered inline when expanded before collapsing the rest.
const DIFF_LINE_CAP: usize = 40;
/// Diff lines shown when collapsed — a preview density that keeps a big edit
/// from dumping 40 lines into the transcript while still showing what changed.
/// Ctrl+T expands to [`DIFF_LINE_CAP`].
const DIFF_PREVIEW_LINES: usize = 6;
/// Maximum visual rows shown for a regular tool result while collapsed.
/// Read/grep/find output can be hundreds of physical lines; keeping a compact
/// preview prevents one tool from taking over the conversation transcript.
const OUTPUT_PREVIEW_LINES: usize = 12;

/// Tool execution status.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToolStatus {
    /// Tool is pending execution
    Pending,
    /// Tool is running
    Running,
    /// Tool completed successfully
    Completed,
    /// Tool failed
    Failed,
}

/// Component that displays a tool execution.
///
/// Mirrors TypeScript ToolExecutionComponent class (simplified).
pub struct ToolExecutionComponent {
    /// Tool name
    name: Mutex<String>,
    /// Optional display title. The raw name is retained for argument parsing
    /// while extensions such as skill loading can provide a clearer label.
    display_title: Mutex<Option<String>>,
    /// When set, the component renders in the native-Pi skill-invocation
    /// style: a `[skill] <name>` box on the custom-message background that
    /// collapses to a single line and expands to the full skill markdown
    /// content (the `read` result). Mirrors pi's `SkillInvocationMessageComponent`.
    skill_name: Mutex<Option<String>>,
    /// Tool arguments (displayed)
    args: Mutex<String>,
    /// Tool result (displayed after execution)
    result: Mutex<Option<String>>,
    /// Execution status
    status: Mutex<ToolStatus>,
    /// When the tool started running (for elapsed time display)
    started_at: Mutex<Option<Instant>>,
    /// When the tool finished (for total elapsed time display)
    finished_at: Mutex<Option<Instant>>,
    /// Whether expanded
    expanded: Mutex<bool>,
    /// Optional pre-rendered colored diff lines (from `render_diff`). When
    /// present the diff is always shown regardless of `expanded` — the diff
    /// IS the useful content for an `edit` tool.
    diff_lines: Mutex<Option<Vec<String>>>,
    /// Render the result body as markdown (tables, bold, lists) instead of
    /// plain text. Tools opt in by setting `details.markdown = true` on their
    /// result; the interactive host calls [`Self::set_result_markdown`] when
    /// it sees that flag. See [`Self::set_result_markdown`].
    result_markdown: Mutex<bool>,
    /// Bumped by every mutator. A finished tool panel is immutable (no live
    /// elapsed timer), so its rendered lines are memoized by width; the
    /// revision drops the cache when args/result/expand change.
    revision: AtomicU64,
    /// Memoized render of a `Completed`/`Failed` panel. Mirrors native pi's
    /// per-component render cache (`tool-execution.ts` + `layout.ts
    /// renderCached`), which is what keeps a transcript repaint from
    /// re-rendering every finished tool panel.
    cache: Mutex<Option<ToolRenderCache>>,
}

#[derive(Clone)]
struct ToolRenderCache {
    width: usize,
    revision: u64,
    theme_revision: u64,
    lines: Vec<String>,
}

impl ToolExecutionComponent {
    /// Create a new tool execution component.
    pub fn new(name: &str, args: &str) -> Self {
        Self {
            name: Mutex::new(name.to_string()),
            display_title: Mutex::new(None),
            skill_name: Mutex::new(None),
            args: Mutex::new(args.to_string()),
            result: Mutex::new(None),
            status: Mutex::new(ToolStatus::Pending),
            started_at: Mutex::new(None),
            finished_at: Mutex::new(None),
            expanded: Mutex::new(false),
            diff_lines: Mutex::new(None),
            result_markdown: Mutex::new(false),
            revision: AtomicU64::new(0),
            cache: Mutex::new(None),
        }
    }

    /// Invalidate the memoized render (state changed).
    fn bump(&self) {
        self.revision.fetch_add(1, Ordering::AcqRel);
    }

    /// Set the tool arguments.
    pub fn set_args(&self, args: &str) {
        if let Ok(mut a) = self.args.lock() {
            *a = args.to_string();
        }
        self.bump();
    }

    /// Set the tool result.
    pub fn set_result(&self, result: &str, is_error: bool) {
        if let Ok(mut r) = self.result.lock() {
            // The header glyph + bg tint already convey status (✗/red for
            // failure, ✓/green for success), so the result text is stored
            // raw — no redundant emoji prefix (pi doesn't double these up).
            *r = Some(result.to_string());
        }
        if let Ok(mut s) = self.status.lock() {
            *s = if is_error {
                ToolStatus::Failed
            } else {
                ToolStatus::Completed
            };
        }
        if let Ok(mut f) = self.finished_at.lock() {
            *f = Some(Instant::now());
        }
        self.bump();
    }

    /// Mark as running.
    pub fn set_running(&self) {
        if let Ok(mut s) = self.status.lock() {
            *s = ToolStatus::Running;
        }
        if let Ok(mut t) = self.started_at.lock() {
            *t = Some(Instant::now());
        }
        self.bump();
    }

    /// Set expanded state.
    pub fn set_expanded(&self, expanded: bool) {
        if let Ok(mut e) = self.expanded.lock() {
            *e = expanded;
        }
        self.bump();
    }

    /// Whether the component is currently expanded (for toggle helpers).
    pub fn is_expanded(&self) -> bool {
        *self.expanded.lock().unwrap()
    }

    /// Get the status.
    pub fn status(&self) -> ToolStatus {
        *self.status.lock().unwrap()
    }

    /// Get the tool name.
    pub fn name(&self) -> String {
        self.name.lock().unwrap().clone()
    }

    /// Override the title shown in the header without changing the underlying
    /// tool name used to summarize arguments and route updates.
    pub fn set_display_title(&self, title: impl Into<String>) {
        if let Ok(mut display_title) = self.display_title.lock() {
            *display_title = Some(title.into());
        }
        self.bump();
    }

    /// Mark this component as a skill-invocation read: it renders in the
    /// native-Pi `[skill] <name>` box style (custom-message background,
    /// collapsible to the full skill markdown). Pass the skill name.
    pub fn set_skill_name(&self, name: impl Into<String>) {
        if let Ok(mut skill_name) = self.skill_name.lock() {
            *skill_name = Some(name.into());
        }
        self.bump();
    }

    /// Whether this component displays a skill invocation (see
    /// [`Self::set_skill_name`]).
    pub fn is_skill(&self) -> bool {
        self.skill_name.lock().map(|s| s.is_some()).unwrap_or(false)
    }

    /// The skill name when this component is a skill invocation.
    pub fn skill_name(&self) -> Option<String> {
        self.skill_name.lock().unwrap().clone()
    }

    /// Attach a pre-rendered colored diff (from [`crate::diff::render_diff`]).
    /// When set, the diff lines are always shown (regardless of `expanded`)
    /// so an edit's changes are visible directly in the transcript.
    pub fn set_diff(&self, lines: Vec<String>) {
        if let Ok(mut d) = self.diff_lines.lock() {
            *d = Some(lines);
        }
        self.bump();
    }

    /// Render the result body as markdown instead of plain indented text.
    ///
    /// The host turns this on when a tool result carries `details.markdown =
    /// true`, so a tool whose payload is markdown (a todo table, a report)
    /// gets its tables/lists/bold rendered by the shared markdown component
    /// rather than printed literally. Markdown rows already wrap themselves to
    /// the panel width, so they are not re-wrapped here.
    pub fn set_result_markdown(&self, enabled: bool) {
        if let Ok(mut markdown) = self.result_markdown.lock() {
            *markdown = enabled;
        }
        self.bump();
    }
}

impl Component for ToolExecutionComponent {
    fn render(&self, width: usize) -> Vec<String> {
        let status = *self.status.lock().unwrap();
        let revision = self.revision.load(Ordering::Acquire);
        let theme_revision = theme_revision();

        // A finished panel is immutable; a running/pending one has a live
        // elapsed timer and may still stream, so only the finished states are
        // memoized. (Mirrors native pi's width-keyed cache, gated on the
        // elapsed readout no longer advancing.)
        let finished = matches!(status, ToolStatus::Completed | ToolStatus::Failed);
        if finished {
            if let Ok(cache) = self.cache.lock() {
                if let Some(cached) = cache.as_ref() {
                    if cached.width == width
                        && cached.revision == revision
                        && cached.theme_revision == theme_revision
                    {
                        return cached.lines.clone();
                    }
                }
            }
        }

        let colors = theme().colors;
        let mut lines = Vec::new();

        // Top spacer — pi's tool-execution.ts adds a Spacer(1) child inside
        // the component so each tool panel is visually separated from the
        // surrounding transcript (the old rpi drain path had no gap between
        // consecutive tool panels).
        lines.push(String::new());

        let name = self.name.lock().unwrap();
        let display_title = self.display_title.lock().unwrap();
        let skill_name = self.skill_name.lock().unwrap();
        let status = self.status.lock().unwrap();
        let args = self.args.lock().unwrap();
        let result = self.result.lock().unwrap();
        let expanded = self.expanded.lock().unwrap();
        let diff_lines = self.diff_lines.lock().unwrap();
        let result_markdown = self.result_markdown.lock().unwrap();
        let started_at = self.started_at.lock().unwrap();
        let finished_at = self.finished_at.lock().unwrap();

        // Skill invocation mode: render as native-Pi's `[skill]` box rather
        // than a generic tool panel — custom-message background, collapsed to
        // a single `[skill] <name> (Ctrl+T to expand)` line, expanded to the
        // full skill markdown (the `read` result). Mirrors pi's
        // `SkillInvocationMessageComponent` while reusing the tool panel's
        // result streaming + Ctrl+T expand plumbing.
        if let Some(skill) = skill_name.as_deref() {
            let content = result.as_deref().unwrap_or("");
            let lines = render_skill(&colors, skill, content, *expanded, width);
            if finished {
                if let Ok(mut cache) = self.cache.lock() {
                    *cache = Some(ToolRenderCache {
                        width,
                        revision,
                        theme_revision,
                        lines: lines.clone(),
                    });
                }
            }
            return lines;
        }

        // Status indicator — a colored glyph (no emoji), pi style.
        let (status_icon, status_color) = match *status {
            ToolStatus::Pending => ("●", colors.muted),
            ToolStatus::Running => ("●", colors.accent),
            ToolStatus::Completed => ("✓", colors.success),
            ToolStatus::Failed => ("✗", colors.error),
        };

        // Background tint for the header row reflects status (pi tool*Bg).
        let bg = match *status {
            ToolStatus::Pending | ToolStatus::Running => colors.tool_pending_bg,
            ToolStatus::Failed => colors.tool_error_bg,
            ToolStatus::Completed => colors.tool_success_bg,
        };

        // Tool header line.
        // For args JSON we display a compact signature (e.g. `read src/foo.rs`)
        // instead of the raw `{"path":"..."}` blob — see `parse_args_summary`.
        // The verbose JSON still shows in the expanded args block below.
        let chevron = if *expanded { "▾" } else { "▸" };
        let label = display_title
            .as_deref()
            .map(str::to_string)
            .unwrap_or_else(|| tools::tool_label(&name));
        let summary = tools::parse_args_summary(&name, &args);
        // Calculate elapsed time
        let elapsed_str = if *status == ToolStatus::Running {
            // Real-time elapsed while running
            if let Some(started) = *started_at {
                let elapsed = started.elapsed();
                format_elapsed(elapsed)
            } else {
                String::new()
            }
        } else if *status == ToolStatus::Completed || *status == ToolStatus::Failed {
            // Total elapsed after completion
            if let (Some(started), Some(finished)) = (*started_at, *finished_at) {
                let elapsed = finished.duration_since(started);
                format_elapsed(elapsed)
            } else {
                String::new()
            }
        } else {
            String::new()
        };
        let head_parts = if summary.is_empty() && elapsed_str.is_empty() {
            format!(
                "{} {} {}",
                status_color.fg(status_icon),
                colors.tool_title.fg(&bold(&label)),
                colors.muted.fg(chevron),
            )
        } else if summary.is_empty() {
            format!(
                "{} {} {} {}",
                status_color.fg(status_icon),
                colors.tool_title.fg(&bold(&label)),
                colors.muted.fg(&elapsed_str),
                colors.muted.fg(chevron),
            )
        } else if elapsed_str.is_empty() {
            format!(
                "{} {} {} {}",
                status_color.fg(status_icon),
                colors.tool_title.fg(&bold(&label)),
                colors.tool_output.fg(&summary),
                colors.muted.fg(chevron),
            )
        } else {
            format!(
                "{} {} {} {} {}",
                status_color.fg(status_icon),
                colors.tool_title.fg(&bold(&label)),
                colors.tool_output.fg(&summary),
                colors.muted.fg(&elapsed_str),
                colors.muted.fg(chevron),
            )
        };
        // Do not sacrifice a long tool name/path summary for the running
        // indicator. Tool calls often carry generated paths or extension
        // names; wrap the header into panel rows so it remains inspectable.
        let header_width = width.saturating_sub(1).max(1);
        for part in wrap_text_with_ansi(&format!(" {}", head_parts), header_width) {
            lines.push(apply_background_to_line(&part, width, |s| bg.bg(s)));
        }

        // Expanded: the full args JSON (indented, dim) above the result. The
        // compact summary already lives in the header, so this is the
        // "show me everything" path for debugging a tool call.
        if *expanded {
            if !args.is_empty() && args.trim() != "{}" {
                let args_line = format!(
                    "  {} {}",
                    colors.muted.fg("args:"),
                    colors.dim.fg(&pretty_args(&args))
                );
                for part in wrap_text_with_ansi(&args_line, width.max(1)) {
                    lines.push(apply_background_to_line(&part, width, |s| bg.bg(s)));
                }
            }
        }

        // Show result if available (always — a failure's error text is the
        // payload, not a detail to hide behind expand). Long logical lines wrap
        // inside the panel instead of overflowing into the next terminal row.
        if let Some(ref r) = *result {
            let body_width = width.saturating_sub(4).max(1);
            // Markdown results are rendered by the markdown component, which
            // wraps and styles its own rows (tables, lists, inline code). The
            // plain path keeps the existing naive wrap so non-markdown tool
            // output is unchanged.
            let visual_lines: Vec<String> = if *result_markdown {
                crate::markdown::Markdown::new(r.clone(), 0, 0).render(body_width)
            } else {
                normalized_output_lines(r)
                    .into_iter()
                    .flat_map(|line| wrap_text_with_ansi(&line, body_width))
                    .collect()
            };
            let shown = if *expanded {
                visual_lines.len()
            } else {
                visual_lines.len().min(OUTPUT_PREVIEW_LINES)
            };
            for part in visual_lines.iter().take(shown) {
                let result_line = if *result_markdown {
                    // Markdown carries its own styling; drop the `│` gutter so
                    // tables keep clean box-drawing edges.
                    format!("  {part}")
                } else {
                    format!("  {} {}", colors.dim.fg("│"), colors.tool_output.fg(part))
                };
                let result_line = apply_background_to_line(&result_line, width, |s| bg.bg(s));
                lines.push(result_line);
            }
            let hidden = visual_lines.len().saturating_sub(shown);
            if hidden > 0 {
                let hint = format!(
                    "  {} … {hidden} more lines (Ctrl+T to expand)",
                    colors.dim.fg("│")
                );
                let hint = colors.muted.fg(&hint);
                lines.push(apply_background_to_line(&hint, width, |s| bg.bg(s)));
            } else if *expanded && visual_lines.len() > OUTPUT_PREVIEW_LINES {
                let hint = format!("  {} Ctrl+T to collapse", colors.dim.fg("│"));
                let hint = colors.muted.fg(&hint);
                lines.push(apply_background_to_line(&hint, width, |s| bg.bg(s)));
            }
        } else if diff_lines.as_ref().map_or(true, |d| d.is_empty()) && !*expanded {
            // No result yet, no diff, and collapsed: pad one bg-tinted row so
            // the tool block still reads as a block (pi keeps the bg band).
            let pad = apply_background_to_line("", width, |s| bg.bg(s));
            lines.push(pad);
        }

        // A colored diff (from `render_diff`) is shown collapsed by default
        // (a small preview) and fully when expanded — an edit's diff is the
        // useful payload, but dumping 40 lines into the transcript by default
        // swamped the conversation. Cap at DIFF_LINE_CAP even when expanded.
        if let Some(diff) = diff_lines.as_ref() {
            let total = diff.len();
            let cap = if *expanded {
                DIFF_LINE_CAP
            } else {
                DIFF_PREVIEW_LINES
            };
            let shown = diff.iter().take(cap);
            for dl in shown {
                // Diff lines are already complete (colors + content). Indent
                // by 2 cols so the `+`/`-` gutter lines up under the header.
                let body = strip_ansi(dl);
                if body.is_empty() {
                    lines.push(String::new());
                } else {
                    let indented = format!("  {}", dl);
                    lines.push(truncate_to_width(&indented, width, "…"));
                }
            }
            if total > cap {
                let more = total - cap;
                let hint = if *expanded {
                    format!("… {} more diff lines (Ctrl+T to collapse)", more)
                } else {
                    format!("… {} more diff lines (Ctrl+T to expand)", more)
                };
                lines.push(format!("  {}", colors.muted.fg(&hint)));
            }
        }

        if finished {
            if let Ok(mut cache) = self.cache.lock() {
                *cache = Some(ToolRenderCache {
                    width,
                    revision,
                    theme_revision,
                    lines: lines.clone(),
                });
            }
        } else if let Ok(mut cache) = self.cache.lock() {
            *cache = None;
        }

        lines
    }

    fn invalidate(&self) {
        self.bump();
    }

    fn as_any(&self) -> &dyn Any {
        self
    }
}

/// Render a skill-invocation box in native-Pi style.
///
/// Mirrors pi's `SkillInvocationMessageComponent`: a `[skill]` box on the
/// custom-message background. Collapsed it is a single line
/// `[skill] <name> (Ctrl+T to expand)`; expanded it shows the `[skill]` label,
/// the bold skill name, then the full skill markdown content (the `read`
/// result) rendered with the standard markdown component.
fn render_skill(
    colors: &ThemeColors,
    name: &str,
    content: &str,
    expanded: bool,
    width: usize,
) -> Vec<String> {
    let bg = colors.custom_message_bg;
    let label = crate::ansi::bold("[skill]");
    // Native Pi's `Box(1, 1, bg)` — one column of horizontal padding on each
    // side, one blank background row top and bottom.
    let pad = " ";
    let mut out: Vec<String> = Vec::new();

    // Box top padding (pi Box(1,1)).
    out.push(apply_background_to_line("", width, |s| bg.bg(s)));

    if !expanded {
        // Single collapsed line: `[skill] <name> (Ctrl+T to expand)`.
        let line = format!(
            "{pad}{} {} {}",
            colors.custom_message_label.fg(&label),
            colors.custom_message_text.fg(name),
            colors.dim.fg("(Ctrl+T to expand)"),
        );
        out.push(apply_background_to_line(&line, width, |s| bg.bg(s)));
        out.push(apply_background_to_line("", width, |s| bg.bg(s)));
        return out;
    }

    // Expanded: `[skill]` label, then a single markdown block whose first
    // paragraph is the bold skill name (native Pi renders
    // `**${name}**\n\n${content}` as one Markdown child), so the body keeps
    // its normal markdown colors on the custom-message background.
    out.push(apply_background_to_line(
        &format!("{pad}{}", colors.custom_message_label.fg(&label)),
        width,
        |s| bg.bg(s),
    ));

    let header = format!("{pad}{}", colors.custom_message_text.fg(&bold(name)));
    out.push(apply_background_to_line(&header, width, |s| bg.bg(s)));
    out.push(apply_background_to_line("", width, |s| bg.bg(s)));

    let body = strip_frontmatter(content);
    if !body.is_empty() {
        // Render the skill body with the shared markdown component. The
        // markdown component handles code blocks / tables / headings; each
        // line is re-tinted onto the custom-message background so the box
        // reads as a single panel.
        let body_width = width.saturating_sub(2).max(1);
        let md = crate::markdown::Markdown::new(body.to_string(), 0, 0);
        for md_line in md.render(body_width) {
            let line = format!("{pad}{md_line}");
            out.push(apply_background_to_line(&line, width, |s| bg.bg(s)));
        }
    }

    // Box bottom padding (pi Box(1,1)).
    out.push(apply_background_to_line("", width, |s| bg.bg(s)));
    out
}

/// Strip a leading YAML frontmatter block (`---\n...\n---`) from skill file
/// content. Native Pi's skill block carries the frontmatter-stripped body
/// (`parseSkillBlock` reads the `<skill>` payload, not the raw file), so the
/// expanded box shows the same instructions the model received.
fn strip_frontmatter(content: &str) -> &str {
    let Some(rest) = content.strip_prefix("---\n") else {
        return content;
    };
    let Some(end) = rest.find("\n---") else {
        return content;
    };
    let after = &rest[end + 4..];
    // Drop the blank line the closing delimiter is conventionally followed by
    // so the markdown body starts on its first heading/paragraph.
    after.strip_prefix('\n').unwrap_or(after)
}

/// Format a duration as a human-readable elapsed time string.
/// Shows seconds with one decimal place for short durations,
/// or minutes and seconds for longer durations.
pub(crate) fn format_elapsed(duration: std::time::Duration) -> String {
    let secs = duration.as_secs_f64();
    if secs < 60.0 {
        format!("{:.1}s", secs)
    } else {
        let mins = (secs / 60.0).floor() as u64;
        let remaining_secs = (secs % 60.0).floor() as u64;
        format!("{}m{}s", mins, remaining_secs)
    }
}

/// Normalize tool output for display. Tool payloads are not guaranteed to use
/// Unix line endings and may contain tabs/control sequences from subprocesses.
fn normalized_output_lines(output: &str) -> Vec<String> {
    let clean = strip_ansi(output).replace("\r\n", "\n").replace('\r', "\n");
    clean
        .split('\n')
        .map(|line| {
            let expanded = line.replace('\t', "    ");
            expanded
                .chars()
                .filter(|c| *c == ' ' || !c.is_control())
                .collect()
        })
        .collect()
}

/// Best-effort pretty-print of a tool args JSON blob for the expanded args
/// block. Falls back to the raw string if it isn't valid JSON. Kept inline
/// rather than reaching for `serde_json::to_string_pretty` so `rpi-tui` stays
/// free of a serde dep (project constraint) — this is display-only and a
/// compact one-liner is more useful in a terminal than a multi-line dump.
fn pretty_args(args: &str) -> String {
    // Compact single-line: `{"path":"src/foo.rs","offset":1}` →
    // `path=src/foo.rs offset=1`. Strings drop quotes, numbers/bools as-is.
    let trimmed = args.trim();
    if trimmed.is_empty() || trimmed == "{}" {
        return "{}".to_string();
    }
    // Lightweight parse: must start with `{`. If not, show raw.
    if !trimmed.starts_with('{') {
        return trimmed.to_string();
    }
    let inner = tools::flatten_json_object(trimmed);
    if inner.is_empty() {
        trimmed.to_string()
    } else {
        inner
    }
}

/// Tool-display helpers: turn a raw tool name + args JSON into a compact,
/// human-readable signature for the tool-block header (e.g.
/// `read src/foo.rs`, `grep pattern · src`, `bash ls -la`).
///
/// Lives in `rpi-tui` (no `rpi-tools` dep) so the render crate can stay
/// standalone; the mapping is purely lexical over the known builtin tool
/// arg shapes. Unknown tools fall back to the raw args.
mod tools {
    /// A short label for the tool name in the header. Pi displays tool
    /// names in their natural lowercase form (`read`, `edit`, …) with bold
    /// styling, matching the original casing from the tool definition.
    pub fn tool_label(name: &str) -> String {
        name.to_string()
    }

    /// Parse a known builtin tool's args JSON into a compact arg summary.
    /// Returns "" when there's nothing useful to show (e.g. unknown tool or
    /// empty args) so the caller can fall back to a header with no summary.
    ///
    /// Handles both complete and incomplete (streaming) JSON — when the args
    /// are still streaming, we fall back to a simple string search for the
    /// key fields so the header can show the file path even before the JSON
    /// is fully received.
    pub fn parse_args_summary(tool: &str, args_json: &str) -> String {
        let map = match parse_json_object(args_json) {
            Some(m) => m,
            None => {
                // JSON is incomplete (streaming) — fall back to simple
                // string extraction for the key field.
                return extract_incomplete_args(tool, args_json);
            }
        };
        let get = |k: &str| field(&map, k);
        match tool {
            "read" => get("path"),
            "write" => get("path"),
            "ls" => get("path"),
            "find" => {
                let p = get("pattern");
                let dir = get("path");
                match dir.as_str() {
                    "" => p,
                    d => format!("{} · {}", p, d),
                }
            }
            "grep" => {
                let p = get("pattern");
                let path = get("path");
                let glob = get("glob");
                let mut parts = vec![p];
                if !glob.is_empty() {
                    parts.push(format!("glob {}", glob));
                }
                if !path.is_empty() {
                    parts.push(path);
                }
                parts.join(" · ")
            }
            "edit" => {
                // path + count of edits (oldText is too long to inline).
                let path = get("path");
                if let Some(arr) = parse_json_array_len(args_json, "edits") {
                    if arr == 1 {
                        path
                    } else {
                        format!("{} ({} edits)", path, arr)
                    }
                } else {
                    path
                }
            }
            "bash" => get("command"),
            _ => {
                // Unknown tool: show the first string-valued field if any.
                map.into_iter().next().map(|(_, v)| v).unwrap_or_default()
            }
        }
    }

    /// Extract a summary from incomplete/streaming JSON by simple string matching.
    /// This is a fallback when the JSON is not yet complete (streaming in progress).
    /// We use regex-like pattern matching to extract key fields like "path".
    fn extract_incomplete_args(tool: &str, args_json: &str) -> String {
        match tool {
            "read" | "write" | "edit" | "ls" => extract_string_field(args_json, "path"),
            "find" => {
                let pattern = extract_string_field(args_json, "pattern");
                let path = extract_string_field(args_json, "path");
                if path.is_empty() {
                    pattern
                } else if pattern.is_empty() {
                    path
                } else {
                    format!("{} · {}", pattern, path)
                }
            }
            "grep" => {
                let pattern = extract_string_field(args_json, "pattern");
                let path = extract_string_field(args_json, "path");
                let glob = extract_string_field(args_json, "glob");
                let mut parts = vec![pattern];
                if !glob.is_empty() {
                    parts.push(format!("glob {}", glob));
                }
                if !path.is_empty() {
                    parts.push(path);
                }
                parts.join(" · ")
            }
            "bash" => extract_string_field(args_json, "command"),
            _ => extract_any_string_field(args_json),
        }
    }

    /// Extract a string field value from JSON using simple pattern matching.
    /// Looks for patterns like `"key":"value"` or `"key": "value"`.
    /// This is a best-effort extraction for incomplete/streaming JSON.
    fn extract_string_field(json: &str, key: &str) -> String {
        // Pattern 1: "key":"value" (no space)
        let pattern1 = format!("\"{}\":\"", key);
        if let Some(start) = json.find(&pattern1) {
            let value_start = start + pattern1.len();
            let remaining = &json[value_start..];
            if let Some(end) = remaining.find('"') {
                let value = &remaining[..end];
                // Unescape common JSON escapes
                return value
                    .replace("\\\"", "\"")
                    .replace("\\\\", "\\")
                    .replace("\\n", "\n")
                    .replace("\\t", "\t");
            }
        }

        // Pattern 2: "key": "value" (with space)
        let pattern2 = format!("\"{}\": \"", key);
        if let Some(start) = json.find(&pattern2) {
            let value_start = start + pattern2.len();
            let remaining = &json[value_start..];
            if let Some(end) = remaining.find('"') {
                let value = &remaining[..end];
                // Unescape common JSON escapes
                return value
                    .replace("\\\"", "\"")
                    .replace("\\\\", "\\")
                    .replace("\\n", "\n")
                    .replace("\\t", "\t");
            }
        }

        String::new()
    }

    /// Extract any string field value from incomplete JSON.
    /// Used as a fallback for unknown tools.
    fn extract_any_string_field(json: &str) -> String {
        // Look for the first string value pattern: "something":"value"
        let pattern = "\":\"";
        if let Some(start) = json.find(pattern) {
            let value_start = start + pattern.len();
            let remaining = &json[value_start..];
            if let Some(end) = remaining.find('"') {
                let value = &remaining[..end];
                // Unescape common JSON escapes
                return value
                    .replace("\\\"", "\"")
                    .replace("\\\\", "\\")
                    .replace("\\n", "\n")
                    .replace("\\t", "\t");
            }
        }
        String::new()
    }

    /// Look up a field's value (unquoted) in a parsed object map.
    fn field(map: &[(String, String)], key: &str) -> String {
        map.iter()
            .find(|(k, _)| k == key)
            .map(|(_, v)| unquote(v))
            .unwrap_or_default()
    }

    /// Flatten a JSON object string into `k=v k=v` (strings unquoted).
    /// Returns "" if the input isn't a `{...}` object or has no fields.
    /// This is a display-only best-effort parser — it does NOT handle nested
    /// objects/arrays (those stay as their raw JSON substring) or escapes;
    /// it's good enough for the expanded args block where the compact header
    /// already showed the important bit.
    pub fn flatten_json_object(json: &str) -> String {
        let Some(map) = parse_json_object(json) else {
            return String::new();
        };
        map.into_iter()
            .map(|(k, v)| format!("{}={}", k, unquote(&v)))
            .collect::<Vec<_>>()
            .join(" ")
    }

    /// Parse a flat JSON object `{"k":"v",...}` into an ordered (k,v) list.
    /// Values are kept as their raw JSON substring (strings keep quotes;
    /// numbers/bools are bare). Returns None if the input isn't a flat object.
    ///
    /// This is a tiny hand-rolled scanner — `rpi-tui` deliberately has no
    /// serde dep. It handles the arg shapes the builtin tools emit (flat,
    /// string/number/bool values); nested objects/arrays are returned as
    /// their raw substring (the caller treats them opaquely).
    fn parse_json_object(json: &str) -> Option<Vec<(String, String)>> {
        let s = json.trim();
        if !s.starts_with('{') || !s.ends_with('}') {
            return None;
        }
        let inner = &s[1..s.len() - 1];
        let mut out = Vec::new();
        let mut chars = inner.chars().peekable();
        loop {
            skip_ws(&mut chars);
            if chars.peek().is_none() {
                break;
            }
            // key (must be a quoted string)
            if chars.peek() != Some(&'"') {
                return None;
            }
            let key = read_string(&mut chars)?;
            skip_ws(&mut chars);
            if chars.next() != Some(':') {
                return None;
            }
            skip_ws(&mut chars);
            // value: string, number, true/false/null, or nested (raw).
            let val = read_value(&mut chars);
            out.push((key, val));
            skip_ws(&mut chars);
            match chars.peek() {
                Some(&',') => {
                    chars.next();
                }
                Some(_) => {
                    return None;
                } // malformed
                None => break,
            }
        }
        Some(out)
    }

    /// Count the elements of a JSON array field `name` in `json`. Used by the
    /// edit summary to show `(N edits)` without holding the array contents.
    fn parse_json_array_len(json: &str, name: &str) -> Option<usize> {
        // Find `"name":` then the `[...]` that follows.
        let pat = format!("\"{}\":", name);
        let idx = json.find(&pat)?;
        let rest = &json[idx + pat.len()..];
        let rest = rest.trim_start();
        if !rest.starts_with('[') {
            return None;
        }
        // Scan the array body respecting nested brackets + strings.
        let mut depth = 0isize;
        let mut in_str = false;
        let mut esc = false;
        let mut count = 0usize;
        let mut saw_any = false;
        for c in rest.chars() {
            if in_str {
                if esc {
                    esc = false;
                } else if c == '\\' {
                    esc = true;
                } else if c == '"' {
                    in_str = false;
                }
                continue;
            }
            match c {
                '"' => in_str = true,
                '[' | '{' => depth += 1,
                ']' | '}' => {
                    depth -= 1;
                    if depth == 0 {
                        break;
                    }
                }
                ',' if depth == 1 => count += 1,
                _ if !c.is_whitespace() && depth >= 1 => saw_any = true,
                _ => {}
            }
        }
        if !saw_any {
            Some(0)
        } else {
            Some(count + 1)
        }
    }

    fn skip_ws(chars: &mut std::iter::Peekable<std::str::Chars>) {
        while let Some(&c) = chars.peek() {
            if c.is_whitespace() {
                chars.next();
            } else {
                break;
            }
        }
    }

    fn read_string(chars: &mut std::iter::Peekable<std::str::Chars>) -> Option<String> {
        if chars.next()? != '"' {
            return None;
        }
        let mut s = String::new();
        let mut esc = false;
        while let Some(c) = chars.next() {
            if esc {
                esc = false;
                s.push(c);
                continue;
            }
            match c {
                '\\' => esc = true,
                '"' => return Some(s),
                _ => s.push(c),
            }
        }
        None
    }

    fn read_value(chars: &mut std::iter::Peekable<std::str::Chars>) -> String {
        match chars.peek() {
            Some(&'"') => {
                // Quoted string — include the quotes in the raw value (so the
                // caller can distinguish strings from numbers); `unquote`
                // strips them for display.
                let mut s = String::from("\"");
                chars.next();
                let mut esc = false;
                while let Some(c) = chars.next() {
                    s.push(c);
                    if esc {
                        esc = false;
                        continue;
                    }
                    if c == '\\' {
                        esc = true;
                        continue;
                    }
                    if c == '"' {
                        break;
                    }
                }
                s
            }
            Some(&'[') | Some(&'{') => read_nested(chars),
            _ => {
                // Bare token (number/true/false/null) — read until , or }.
                let mut s = String::new();
                while let Some(&c) = chars.peek() {
                    if c == ',' || c == '}' {
                        break;
                    }
                    s.push(c);
                    chars.next();
                }
                s.trim().to_string()
            }
        }
    }

    fn read_nested(chars: &mut std::iter::Peekable<std::str::Chars>) -> String {
        // Copy the raw substring for a nested array/object, tracking depth +
        // string state so commas inside don't terminate it early.
        let mut s = String::new();
        let mut depth = 0isize;
        let mut in_str = false;
        let mut esc = false;
        while let Some(c) = chars.next() {
            s.push(c);
            if in_str {
                if esc {
                    esc = false;
                } else if c == '\\' {
                    esc = true;
                } else if c == '"' {
                    in_str = false;
                }
                continue;
            }
            match c {
                '"' => in_str = true,
                '[' | '{' => depth += 1,
                ']' | '}' => {
                    depth -= 1;
                    if depth == 0 {
                        break;
                    }
                }
                _ => {}
            }
        }
        s
    }

    fn unquote(v: &str) -> String {
        if v.len() >= 2 && v.starts_with('"') && v.ends_with('"') {
            v[1..v.len() - 1].to_string()
        } else {
            v.to_string()
        }
    }
}

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

    #[test]
    fn test_tool_execution_basic() {
        let tool = ToolExecutionComponent::new("read", "file.txt");
        let lines = tool.render(80);
        assert!(!lines.is_empty());
    }

    #[test]
    fn test_tool_execution_status() {
        let tool = ToolExecutionComponent::new("bash", "ls -la");

        assert_eq!(tool.status(), ToolStatus::Pending);

        tool.set_running();
        assert_eq!(tool.status(), ToolStatus::Running);

        tool.set_result("output", false);
        assert_eq!(tool.status(), ToolStatus::Completed);
    }

    #[test]
    fn test_tool_execution_expanded() {
        let tool = ToolExecutionComponent::new("edit", "file.rs");
        tool.set_expanded(true);
        tool.set_result("success", false);

        let lines = tool.render(80);
        assert!(lines.len() > 1); // Should have more lines when expanded
    }

    #[test]
    fn test_tool_execution_error() {
        let tool = ToolExecutionComponent::new("bash", "invalid_command");
        tool.set_result("command not found", true);

        let lines = tool.render(80);
        let joined = lines.join("\n");
        // Failed state: error-colored ✗ glyph + the result text echoed.
        assert!(
            joined.contains("command not found"),
            "result text missing: {joined}"
        );
        assert!(joined.contains('✗'), "error glyph missing: {joined}");
    }

    #[test]
    fn long_tool_header_wraps_instead_of_truncating() {
        let title = "A VERY LONG EXTENSION TOOL NAME";
        let tool = ToolExecutionComponent::new("extension_tool", "{}");
        tool.set_display_title(title);
        tool.set_running();
        let lines = tool.render(16);
        let rendered = crate::ansi::strip_ansi(&lines.join("\n"));
        let compact: String = rendered.chars().filter(|ch| !ch.is_whitespace()).collect();
        let expected: String = title.chars().filter(|ch| !ch.is_whitespace()).collect();
        assert!(
            compact.contains(&expected),
            "header was truncated: {rendered}"
        );
        assert!(lines
            .iter()
            .all(|line| crate::utils::visible_width(line) <= 16));
    }

    #[test]
    fn tool_output_wraps_with_a_stable_gutter_and_background() {
        let tool = ToolExecutionComponent::new("read", r#"{"path":"wide.txt"}"#);
        tool.set_result("0123456789ABCDEFGHIJ", false);
        let rendered = tool.render(12);
        let body: Vec<String> = rendered
            .iter()
            .map(|line| crate::ansi::strip_ansi(line))
            .filter(|line| line.contains('│'))
            .collect();
        assert!(body.len() >= 2, "long output should wrap: {body:?}");
        assert!(body.iter().all(|line| line.starts_with("  │ ")));
        assert!(rendered
            .iter()
            .all(|line| crate::utils::visible_width(line) <= 12));
        // Nested foreground resets must re-apply the panel background.
        assert!(rendered
            .iter()
            .any(|line| line.matches("\x1b[48;2;38;48;52m").count() > 1));
    }

    #[test]
    fn markdown_result_renders_tables_instead_of_literal_pipes() {
        let tool = ToolExecutionComponent::new("todo", r#"{"action":"list"}"#);
        tool.set_result_markdown(true);
        tool.set_result(
            "**Todos** | 1 done\n\n| ID | Task |\n|----|------|\n| #1 | ship |",
            false,
        );
        let rendered = crate::ansi::strip_ansi(&tool.render(60).join("\n"));
        // The markdown component lays the table out with box-drawing borders
        // instead of the raw `| a | b |` source.
        assert!(
            rendered.contains('┌') && rendered.contains('│'),
            "table not rendered: {rendered}"
        );
        assert!(
            !rendered.contains("| ID |"),
            "raw markdown table leaked: {rendered}"
        );
        assert!(
            !rendered.contains("**Todos**"),
            "raw bold marker leaked: {rendered}"
        );
        assert!(rendered.contains("Todos"), "text missing: {rendered}");

        // The default (non-markdown) mode must keep rendering the same body as
        // plain text with the `│` gutter.
        let plain = ToolExecutionComponent::new("todo", r#"{"action":"list"}"#);
        plain.set_result("| ID | Task |", false);
        let plain_rendered = crate::ansi::strip_ansi(&plain.render(60).join("\n"));
        assert!(
            plain_rendered.contains("| ID | Task |"),
            "plain tools must not be markdown-rendered: {plain_rendered}"
        );
    }

    #[test]
    fn long_tool_output_collapses_and_ctrl_t_expands() {
        let tool = ToolExecutionComponent::new("read", r#"{"path":"large.rs"}"#);
        let output = (1..=20)
            .map(|line| format!("line {line}"))
            .collect::<Vec<_>>()
            .join("\n");
        tool.set_result(&output, false);

        let collapsed = tool.render(80);
        let collapsed_plain = crate::ansi::strip_ansi(&collapsed.join("\n"));
        assert!(collapsed_plain.contains("8 more lines (Ctrl+T to expand)"));
        assert!(!collapsed_plain.contains("line 20"));

        tool.set_expanded(true);
        let expanded = tool.render(80);
        let expanded_plain = crate::ansi::strip_ansi(&expanded.join("\n"));
        assert!(expanded_plain.contains("line 20"));
        assert!(expanded_plain.contains("Ctrl+T to collapse"));
    }

    /// The header summarizes the args JSON into a compact signature instead
    /// of dumping the raw `{"path":"..."}` blob. Each builtin tool maps its
    /// key fields to a one-liner.
    /// A `read` of a `SKILL.md` renders as native Pi's `[skill] <name>`
    /// invocation box: custom-message background, one collapsed line with an
    /// expand hint, and (when expanded) the frontmatter-stripped skill body.
    #[test]
    fn skill_invocation_renders_native_style_box() {
        let tool = ToolExecutionComponent::new("read", r#"{"path":"/skills/release/SKILL.md"}"#);
        tool.set_skill_name("release");
        tool.set_result(
            "---\nname: release\ndescription: cut a release\n---\n\n# Steps\n\nDo the thing.",
            false,
        );

        let collapsed = tool.render(80);
        let plain = crate::ansi::strip_ansi(&collapsed.join("\n"));
        assert!(
            plain.contains("[skill] release"),
            "collapsed label: {plain}"
        );
        assert!(plain.contains("(Ctrl+T to expand)"), "expand hint: {plain}");
        assert!(!plain.contains("Steps"), "collapsed hides body: {plain}");
        // Uses the custom-message background (dark: #2d2838), not a tool tint.
        assert!(
            collapsed.iter().any(|l| l.contains("\x1b[48;2;45;40;56m")),
            "custom-message bg missing: {collapsed:?}"
        );

        tool.set_expanded(true);
        let expanded = tool.render(80);
        let plain = crate::ansi::strip_ansi(&expanded.join("\n"));
        assert!(plain.contains("[skill]"), "expanded label: {plain}");
        assert!(plain.contains("release"), "expanded name: {plain}");
        assert!(
            plain.contains("Do the thing."),
            "expanded body missing: {plain}"
        );
        // Frontmatter is stripped (native Pi shows the parsed skill body only).
        assert!(
            !plain.contains("name: release"),
            "frontmatter leaked: {plain}"
        );
    }

    #[test]
    fn strip_frontmatter_only_strips_a_leading_block() {
        assert_eq!(strip_frontmatter("plain"), "plain");
        assert_eq!(strip_frontmatter("---\nname: x\n---\nbody"), "body");
        // No opening delimiter → untouched.
        assert_eq!(strip_frontmatter("a\n---\nb"), "a\n---\nb");
    }

    #[test]
    fn test_tool_header_args_summary() {
        // `read` → just the path.
        let t = ToolExecutionComponent::new("read", r#"{"path":"src/foo.rs"}"#);
        let joined = t.render(80).join("\n");
        let plain = crate::ansi::strip_ansi(&joined);
        assert!(plain.contains("read"), "tool label lowercase: {plain}");
        assert!(plain.contains("src/foo.rs"), "path in summary: {plain}");
        // The raw JSON must NOT leak into the header.
        assert!(!plain.contains("\"path\""), "raw JSON leaked: {plain}");

        // `grep` → pattern · path (no path field → just pattern).
        let t = ToolExecutionComponent::new("grep", r#"{"pattern":"TODO","path":"src"}"#);
        let plain = crate::ansi::strip_ansi(&t.render(80).join("\n"));
        assert!(plain.contains("TODO · src"), "grep summary: {plain}");

        // `edit` with multiple edits → `(N edits)` suffix.
        let t = ToolExecutionComponent::new(
            "edit",
            r#"{"path":"a.rs","edits":[{"oldText":"x"},{"oldText":"y"}]}"#,
        );
        let plain = crate::ansi::strip_ansi(&t.render(80).join("\n"));
        assert!(plain.contains("a.rs (2 edits)"), "edit count: {plain}");
    }

    /// Unknown tools fall back to the first string-valued arg field rather
    /// than showing nothing — keeps the header useful for plugin tools whose
    /// arg shapes the render crate doesn't know.
    #[test]
    fn test_tool_header_unknown_tool_falls_back() {
        let t = ToolExecutionComponent::new("mytool", r#"{"query":"hai"}"#);
        let plain = crate::ansi::strip_ansi(&t.render(80).join("\n"));
        assert!(plain.contains("hai"), "unknown tool summary: {plain}");
    }

    /// The collapsed diff preview caps at DIFF_PREVIEW_LINES and teases the
    /// remaining count; expanding lifts the cap to DIFF_LINE_CAP.
    #[test]
    fn test_tool_diff_preview_then_expand() {
        // Build a diff with 12 changed lines — over the 6-line preview, under
        // the 40-line expanded cap.
        let mut diff = String::new();
        for i in 1..=6 {
            diff.push_str(&format!("-{} old line {}\n", i, i));
            diff.push_str(&format!("+{} new line {}\n", i, i));
        }
        let t = ToolExecutionComponent::new("edit", r#"{"path":"f"}"#);
        t.set_result("ok", false);
        t.set_diff(crate::diff::render_diff(&diff, 80));

        let collapsed = t.render(80);
        // Preview cap = 6 lines + 1 header + 1 result + 1 hint.
        let diff_body = collapsed
            .iter()
            .filter(|l| {
                let p = crate::ansi::strip_ansi(l);
                p.trim_start().starts_with('-') || p.trim_start().starts_with('+')
            })
            .count();
        assert_eq!(
            diff_body, 6,
            "collapsed preview should cap at 6: {collapsed:?}"
        );
        let hint = collapsed
            .iter()
            .map(|l| crate::ansi::strip_ansi(l))
            .find(|l| l.contains("more diff lines"));
        assert!(hint.is_some(), "preview hint missing");
        assert!(
            hint.as_ref().unwrap().contains("Ctrl+T to expand"),
            "hint text: {hint:?}"
        );

        t.set_expanded(true);
        let expanded = t.render(80);
        let diff_body = expanded
            .iter()
            .filter(|l| {
                let p = crate::ansi::strip_ansi(l);
                p.trim_start().starts_with('-') || p.trim_start().starts_with('+')
            })
            .count();
        assert_eq!(diff_body, 12, "expanded should show all 12: {expanded:?}");
    }
}