oxi-tui 0.37.1

Terminal UI widgets and theme system for oxi, built on ratatui
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
//! Tool call renderer — formats tool calls and results for display.
//!
//! Provides specialized formatting for built-in tools (edit, bash, read, etc.)
//! based on the tool name, arguments JSON, and result text.
//!
//! Auto-detection: if a result looks like a unified diff, it's rendered
//! as a colored diff view even without explicit hints.

use ratatui::style::Modifier;
use ratatui::text::{Line, Span};
use serde_json::Value;
use unicode_width::UnicodeWidthStr;

use crate::text::truncate_to_width;
use crate::theme::ThemeStyles;

// ── Constants ────────────────────────────────────────────────────────────

/// Maximum lines to show in result preview
const RESULT_PREVIEW_LINES: usize = 5;
/// Maximum lines to show in diff view
const DIFF_PREVIEW_LINES: usize = 8;
/// Maximum lines to show for read output
const READ_PREVIEW_LINES: usize = 4;
/// Maximum content lines for generic results
const GENERIC_PREVIEW_LINES: usize = 4;

// ── Path utilities ───────────────────────────────────────────────────────

/// Shorten a file path by replacing home directory with ~.
pub fn shorten_path(path: &str) -> String {
    if let Some(home) = dirs::home_dir() {
        let home_str: String = home.to_string_lossy().into_owned();
        if let Some(rest) = path.strip_prefix(&*home_str) {
            return format!("~{}", rest);
        }
    }
    path.to_string()
}

// ── JSON parsing helpers ──────────────────────────────────────────────────

/// Parse arguments JSON to extract common fields.
pub fn parse_tool_args(arguments: &str) -> Value {
    serde_json::from_str(arguments).unwrap_or(Value::Null)
}

/// Extract a string field from parsed arguments.
pub fn get_str<'a>(args: &'a Value, key: &str) -> Option<&'a str> {
    args.get(key)?.as_str()
}

/// Extract an optional path field from arguments (handles path/file_path).
pub fn get_path(args: &Value) -> Option<String> {
    args.get("path")
        .or_else(|| args.get("file_path"))
        .and_then(|v| v.as_str())
        .map(shorten_path)
}

/// Extract an integer field from arguments.
pub fn get_int(args: &Value, key: &str) -> Option<i64> {
    args.get(key)?.as_i64()
}

// ── Auto-detection ────────────────────────────────────────────────────────

/// Check if result text looks like a unified diff.
pub fn looks_like_diff(text: &str) -> bool {
    text.lines().take(5).any(|l| {
        l.starts_with("@@ -")
            || (l.starts_with('-') && !l.starts_with("--"))
            || (l.starts_with('+') && !l.starts_with("++"))
    })
}

/// Check if result indicates a command exit status.
pub fn has_exit_status(text: &str) -> bool {
    text.contains("Command exited with code")
        || text.contains("Command timed out")
        || text.contains("Command aborted")
}

/// Count diff stats from a unified diff text.
pub fn count_diff_stats(diff: &str) -> (u32, u32) {
    let mut added = 0u32;
    let mut removed = 0u32;
    for line in diff.lines() {
        if line.starts_with('+') && !line.starts_with("++") {
            added += 1;
        } else if line.starts_with('-') && !line.starts_with("--") {
            removed += 1;
        }
    }
    (added, removed)
}

// ── Call formatters ───────────────────────────────────────────────────────

/// Format a tool call header line.
fn format_call_header(name: &str, extra: &str, styles: &ThemeStyles) -> Line<'static> {
    let name_style = styles.accent.add_modifier(Modifier::BOLD);
    let extra_style = styles.muted;
    Line::from(vec![
        Span::styled(format!("{} ", name), name_style),
        Span::styled(extra.to_string(), extra_style),
    ])
}

/// Format the edit tool call.
pub fn format_edit_call(args: &Value, styles: &ThemeStyles) -> Vec<Line<'static>> {
    let path = get_path(args);
    let path_display = path.unwrap_or_else(|| "?".to_string());

    // Count edits
    let edit_count = args
        .get("edits")
        .and_then(|v| v.as_array())
        .map(|a| a.len())
        .unwrap_or_else(|| {
            // Legacy mode: check oldText
            if args.get("oldText").or(args.get("oldText")).is_some() {
                1
            } else {
                0
            }
        });

    let extra = if edit_count > 0 {
        format!(
            "{} ({} replacement{})",
            path_display,
            edit_count,
            if edit_count == 1 { "" } else { "s" }
        )
    } else {
        path_display
    };

    vec![format_call_header("edit", &extra, styles)]
}

/// Format the bash tool call.
pub fn format_bash_call(
    args: &Value,
    max_width: usize,
    styles: &ThemeStyles,
) -> Vec<Line<'static>> {
    let command = get_str(args, "command").unwrap_or("...");
    // Account for "$ " prefix (2 chars)
    let command_display = truncate_to_width(command, max_width.saturating_sub(2).max(20));

    let mut lines = vec![Line::from(vec![
        Span::styled("$ ", styles.accent.add_modifier(Modifier::BOLD)),
        Span::styled(command_display, styles.normal),
    ])];

    // Add timeout if present
    if let Some(timeout) = get_int(args, "timeout") {
        lines.push(Line::from(Span::styled(
            format!("  (timeout {}s)", timeout),
            styles.muted,
        )));
    }

    lines
}

/// Format the read tool call.
pub fn format_read_call(args: &Value, styles: &ThemeStyles) -> Vec<Line<'static>> {
    let path = get_path(args).unwrap_or_else(|| "?".to_string());

    // Line range
    let offset = get_int(args, "offset");
    let limit = get_int(args, "limit");

    let extra = match (offset, limit) {
        (Some(o), Some(l)) => format!("{}:{}-{}", path, o, o + l - 1),
        (Some(o), None) => format!("{}:{}", path, o),
        (None, Some(l)) => format!("{}:1-{}", path, l),
        (None, None) => path,
    };

    vec![format_call_header("read", &extra, styles)]
}

/// Format the write tool call.
pub fn format_write_call(args: &Value, styles: &ThemeStyles) -> Vec<Line<'static>> {
    let path = get_path(args).unwrap_or_else(|| "?".to_string());
    let extra = format!("{} (new)", path);
    vec![format_call_header("write", &extra, styles)]
}

/// Format search tools (grep, find, ls).
pub fn format_search_call(name: &str, args: &Value, styles: &ThemeStyles) -> Vec<Line<'static>> {
    let icon = match name {
        "grep" => "[G]",
        "find" => "[F]",
        "ls" => "[D]",
        _ => "",
    };

    let path = get_path(args).unwrap_or_else(|| ".".to_string());

    // Pattern for grep
    let pattern = get_str(args, "pattern")
        .or_else(|| get_str(args, "query"))
        .map(|p| format!(" \"{}\"", truncate_to_width(p, 30)))
        .unwrap_or_default();

    let extra = format!("{}{} {}", icon, pattern, path);
    vec![Line::from(vec![
        Span::styled(
            format!("{} ", name),
            styles.accent.add_modifier(Modifier::BOLD),
        ),
        Span::styled(extra, styles.muted),
    ])]
}

// ── Issue tool formatter ────────────────────────────────────────────────────

/// Format the `issue` tool call. The tool has a single `action` discriminator
/// (list/read/create/update/start/release/close/link_session) and renders
/// compactly so the chat shows what's about to happen without dumping the
/// full parameter set.
pub fn format_issue_call(
    args: &Value,
    max_width: usize,
    styles: &ThemeStyles,
) -> Vec<Line<'static>> {
    let action = args.get("action").and_then(|v| v.as_str()).unwrap_or("?");
    let id = args.get("id").and_then(|v| v.as_i64());

    let header = Line::from(vec![
        Span::styled(
            "issue ".to_string(),
            styles.accent.add_modifier(Modifier::BOLD),
        ),
        Span::styled(format!("{action} "), styles.normal),
    ]);

    let mut lines = vec![header];
    match action {
        "create" => {
            // Title (highlighted) + priority/labels as tags on a second line.
            if let Some(title) = args.get("title").and_then(|v| v.as_str()) {
                let title_disp = truncate_to_width(title, max_width.saturating_sub(2));
                lines.push(Line::from(vec![
                    Span::styled("  ", styles.muted),
                    Span::styled(format!("{title_disp}"), styles.normal),
                ]));
            }
            let mut tags: Vec<String> = Vec::new();
            if let Some(p) = args.get("priority").and_then(|v| v.as_str()) {
                tags.push(format!("[{p}]"));
            }
            if let Some(arr) = args.get("labels").and_then(|v| v.as_array()) {
                let labels: Vec<String> = arr
                    .iter()
                    .filter_map(|v| v.as_str().map(String::from))
                    .collect();
                if !labels.is_empty() {
                    tags.push(format!("[{}]", labels.join(",")));
                }
            }
            if !tags.is_empty() {
                lines.push(Line::from(Span::styled(
                    format!("  {}", tags.join(" ")),
                    styles.muted,
                )));
            }
        }
        "list" => {
            // Show active filters as muted tag line.
            let mut filters: Vec<String> = Vec::new();
            if let Some(s) = args.get("status").and_then(|v| v.as_str()) {
                filters.push(format!("status={s}"));
            }
            if let Some(p) = args.get("priority").and_then(|v| v.as_str()) {
                filters.push(format!("priority={p}"));
            }
            if let Some(l) = args.get("label").and_then(|v| v.as_str()) {
                filters.push(format!("label={l}"));
            }
            if let Some(t) = args.get("text").and_then(|v| v.as_str()) {
                filters.push(format!("text=“{}", truncate_to_width(t, 24)));
            }
            if filters.is_empty() {
                lines.push(Line::from(Span::styled("  (all open)", styles.muted)));
            } else {
                lines.push(Line::from(Span::styled(
                    format!("  {}", filters.join("  ")),
                    styles.muted,
                )));
            }
        }
        "update" | "start" | "release" | "close" | "link_session" | "read" => {
            if let Some(i) = id {
                lines.push(Line::from(Span::styled(format!("  #{i}"), styles.muted)));
            }
            // For update, surface what fields are being changed.
            if action == "update" {
                let mut changed: Vec<&str> = Vec::new();
                if args.get("title").is_some() {
                    changed.push("title");
                }
                if args.get("body").is_some() {
                    changed.push("body");
                }
                if args.get("priority").is_some() {
                    changed.push("priority");
                }
                if args.get("status").is_some() {
                    changed.push("status");
                }
                if args.get("labels").is_some() {
                    changed.push("labels");
                }
                if !changed.is_empty() {
                    lines.push(Line::from(Span::styled(
                        format!("{}", changed.join(", ")),
                        styles.muted,
                    )));
                }
            }
        }
        other => {
            lines.push(Line::from(Span::styled(
                format!("  (unknown action: {other})"),
                styles.warning,
            )));
        }
    }
    lines
}

/// Format the `issue` tool result. We pattern-match the success/error strings
/// produced by `IssueTool` (and the underlying `FileIssueStore`) so the chat
/// surfaces semantic distinctions (created vs. closed vs. conflict).
pub fn format_issue_result(
    result: &str,
    max_width: usize,
    styles: &ThemeStyles,
) -> Vec<Line<'static>> {
    let mut lines = Vec::new();
    let text = result.trim();
    let first_line = text.lines().next().unwrap_or("");

    // ── Errors first — detect by leading prefix pattern ──────────────────
    if let Some(rest) = first_line.strip_prefix("issue ") {
        // Conflict / Assigned / NotAssigned are surfaced as `issue #N ...`.
        let lower = rest.to_lowercase();
        let (kind, detail) = if lower.contains("was modified since last read") {
            ("conflict", "re-read and retry")
        } else if lower.contains("is currently being worked on by") {
            ("assigned", "another session owns it")
        } else if lower.contains("is not assigned to session") {
            ("not owner", "run start first")
        } else if lower.contains("not found") {
            ("missing", "id does not exist")
        } else if lower.starts_with("#") && lower.contains("failed") {
            ("failed", "")
        } else {
            ("", "")
        };
        if !kind.is_empty() {
            lines.push(Line::from(Span::styled(
                format!(
                    "{}",
                    truncate_to_width(first_line, max_width.saturating_sub(4))
                ),
                styles.error,
            )));
            if !detail.is_empty() {
                lines.push(Line::from(Span::styled(
                    format!("{detail}"),
                    styles.muted,
                )));
            }
            // Show remaining lines muted (truncated).
            for extra in text.lines().skip(1).take(3) {
                lines.push(Line::from(Span::styled(
                    format!(
                        "    {}",
                        truncate_to_width(extra, max_width.saturating_sub(6))
                    ),
                    styles.muted,
                )));
            }
            return lines;
        }
    }

    // ── Success patterns ────────────────────────────────────────────────
    let success_style = styles.success;
    let neutral_style = styles.normal;
    let muted_style = styles.muted;

    if first_line.starts_with("created issue ") {
        // "created issue #12: Fix login bug"
        lines.push(Line::from(Span::styled(
            format!(
                "{}",
                truncate_to_width(first_line, max_width.saturating_sub(4))
            ),
            success_style,
        )));
        // Subsequent lines may be a follow-up notification (e.g., the
        // store emits nothing extra, but callers sometimes append).
        for extra in text.lines().skip(1).take(3) {
            lines.push(Line::from(Span::styled(
                format!(
                    "    {}",
                    truncate_to_width(extra, max_width.saturating_sub(6))
                ),
                muted_style,
            )));
        }
    } else if first_line.starts_with("closed issue ") {
        lines.push(Line::from(Span::styled(
            format!(
                "{}",
                truncate_to_width(first_line, max_width.saturating_sub(4))
            ),
            success_style,
        )));
    } else if first_line.starts_with("updated issue ") {
        lines.push(Line::from(Span::styled(
            format!(
                "{}",
                truncate_to_width(first_line, max_width.saturating_sub(4))
            ),
            neutral_style,
        )));
    } else if first_line.starts_with("released issue ") {
        // Released is a soft-yellow action — assignment ended.
        lines.push(Line::from(Span::styled(
            format!(
                "{}",
                truncate_to_width(first_line, max_width.saturating_sub(4))
            ),
            styles.warning,
        )));
    } else if first_line.starts_with("linked session to issue ") {
        lines.push(Line::from(Span::styled(
            format!(
                "  + {}",
                truncate_to_width(first_line, max_width.saturating_sub(4))
            ),
            muted_style,
        )));
    } else if first_line.starts_with("assigned issue ") {
        lines.push(Line::from(Span::styled(
            format!(
                "{}",
                truncate_to_width(first_line, max_width.saturating_sub(4))
            ),
            success_style,
        )));
    } else if first_line == "no issues match the filter" {
        lines.push(Line::from(Span::styled(
            "  (no issues match the filter)".to_string(),
            muted_style,
        )));
    } else if first_line.starts_with("issue #") && first_line.contains(" failed: ") {
        // Slash command fallback: "issue #N start failed: <reason>"
        lines.push(Line::from(Span::styled(
            format!(
                "{}",
                truncate_to_width(first_line, max_width.saturating_sub(4))
            ),
            styles.error,
        )));
    } else {
        // Multi-line list result — color-code each entry.
        let total = text.lines().count();
        for (i, line) in text.lines().take(8).enumerate() {
            let display = truncate_to_width(line, max_width.saturating_sub(2));
            // Color by the status token in `[open]` / `[closed]`.
            let span = if display.contains("[closed]") {
                Span::styled(format!("  {display}"), muted_style)
            } else if display.contains("[open]") {
                Span::styled(format!("  {display}"), styles.normal)
            } else if display.contains("🔒") {
                Span::styled(format!("  {display}"), styles.warning)
            } else {
                Span::styled(format!("  {display}"), muted_style)
            };
            lines.push(Line::from(span));
            // Hint at truncation on the last rendered line.
            if i == 7 && total > 8 {
                lines.push(Line::from(Span::styled(
                    format!("    … ({} more)", total - 8),
                    muted_style,
                )));
            }
        }
        if total == 0 {
            lines.push(Line::from(Span::styled(
                "  (empty result)".to_string(),
                muted_style,
            )));
        }
    }
    lines
}

/// Parse a priority string into a normalized display label.
/// Format a generic tool call (fallback for unknown tools).
pub fn format_generic_call(
    name: &str,
    args: &Value,
    max_width: usize,
    styles: &ThemeStyles,
) -> Vec<Line<'static>> {
    let name_style = styles.accent.add_modifier(Modifier::BOLD);
    let mut lines = vec![Line::from(vec![Span::styled(
        format!("{} ", name),
        name_style,
    )])];

    // Show first few args as key: value
    if let Some(obj) = args.as_object() {
        for (key, v) in obj.iter().take(3) {
            let val_str = match v {
                Value::String(s) => s.clone(),
                other => other.to_string(),
            };
            let prefix_len = 2 + UnicodeWidthStr::width(key.as_str()) + 2;
            let avail = max_width.saturating_sub(prefix_len);
            let display = truncate_to_width(&val_str, avail);
            lines.push(Line::from(vec![
                Span::styled(format!("  {}", key), styles.muted),
                Span::styled(": ", styles.muted),
                Span::styled(display, styles.normal),
            ]));
        }
    }

    lines
}

/// Format a tool call by tool name.
pub fn format_tool_call(
    name: &str,
    arguments: &str,
    max_width: usize,
    styles: &ThemeStyles,
) -> Vec<Line<'static>> {
    let args = parse_tool_args(arguments);

    match name {
        "edit" => format_edit_call(&args, styles),
        "bash" => format_bash_call(&args, max_width, styles),
        "read" => format_read_call(&args, styles),
        "write" => format_write_call(&args, styles),
        "grep" | "find" | "ls" => format_search_call(name, &args, styles),
        "issue" => format_issue_call(&args, max_width, styles),
        _ => format_generic_call(name, &args, max_width, styles),
    }
}

// ── Result formatters ─────────────────────────────────────────────────────

/// Format an error result.
pub fn format_error_result(
    error: &str,
    max_width: usize,
    styles: &ThemeStyles,
) -> Vec<Line<'static>> {
    let mut lines = Vec::new();

    for line in error.lines().take(4) {
        let display = truncate_to_width(line, max_width);
        lines.push(Line::from(Span::styled(
            format!("  {}", display),
            styles.error,
        )));
    }

    if error.lines().count() > 4 {
        lines.push(Line::from(Span::styled("  \u{2026}", styles.muted)));
    }

    lines
}

/// Format a unified diff result with colors.
pub fn format_diff_result(
    diff: &str,
    max_width: usize,
    styles: &ThemeStyles,
) -> Vec<Line<'static>> {
    let mut lines = Vec::new();
    let total_lines = diff.lines().count();

    for raw_line in diff.lines().take(DIFF_PREVIEW_LINES) {
        let line = if raw_line.starts_with("@@") {
            // Hunk header
            Line::from(Span::styled(
                truncate_to_width(raw_line, max_width),
                styles.muted,
            ))
        } else if raw_line.starts_with('-') && !raw_line.starts_with("--") {
            // Removed line — red
            Line::from(Span::styled(
                format!(
                    " {}",
                    truncate_to_width(raw_line, max_width.saturating_sub(1))
                ),
                styles.error,
            ))
        } else if raw_line.starts_with('+') && !raw_line.starts_with("++") {
            // Added line — green
            Line::from(Span::styled(
                format!(
                    " {}",
                    truncate_to_width(raw_line, max_width.saturating_sub(1))
                ),
                styles.success,
            ))
        } else {
            // Context line
            Line::from(Span::styled(
                format!(
                    " {}",
                    truncate_to_width(raw_line, max_width.saturating_sub(1))
                ),
                styles.muted,
            ))
        };
        lines.push(line);
    }

    // Show diff stats if significant
    let (added, removed) = count_diff_stats(diff);
    if total_lines > DIFF_PREVIEW_LINES {
        lines.push(Line::from(Span::styled(
            format!(
                "  \u{2026} ({} more lines)",
                total_lines - DIFF_PREVIEW_LINES
            ),
            styles.muted,
        )));
    } else if added > 0 || removed > 0 {
        lines.push(Line::from(Span::styled(
            format!("  [+{} / -{}]", added, removed),
            styles.muted,
        )));
    }

    lines
}

/// Format a bash command result.
pub fn format_bash_result(
    result: &str,
    max_width: usize,
    styles: &ThemeStyles,
) -> Vec<Line<'static>> {
    let mut lines = Vec::new();

    // Show last N lines of output
    let all_lines: Vec<&str> = result.lines().collect();
    let _preview_lines = if all_lines.len() > RESULT_PREVIEW_LINES {
        // Show last N lines
        let start = all_lines.len() - RESULT_PREVIEW_LINES;
        for line in &all_lines[start..] {
            let display = truncate_to_width(line, max_width.saturating_sub(2));
            lines.push(Line::from(Span::styled(
                format!("  {}", display),
                styles.normal,
            )));
        }
        if start > 0 {
            lines.insert(
                0,
                Line::from(Span::styled(
                    format!("  … ({} earlier lines)", start),
                    styles.muted,
                )),
            );
        }
        all_lines.len()
    } else {
        for line in &all_lines {
            let display = truncate_to_width(line, max_width.saturating_sub(2));
            lines.push(Line::from(Span::styled(
                format!("  {}", display),
                styles.normal,
            )));
        }
        all_lines.len()
    };

    // Note: "Full output:" truncation info is intentionally NOT appended
    // as a separate line here. When the bash output is large, the tool
    // result already includes this text, and it will appear in the preview
    // naturally. Adding it separately caused a height measurement mismatch
    // (format_bash_result produced more lines than measure_result_height
    // expected), leading to content clipping in bordered tool boxes.

    lines
}

/// Format a read tool result (file content preview).
pub fn format_read_result(
    result: &str,
    max_width: usize,
    styles: &ThemeStyles,
) -> Vec<Line<'static>> {
    let mut lines = Vec::new();
    let all_lines: Vec<&str> = result.lines().collect();
    let total = all_lines.len();

    // Show first N lines with line numbers
    for (i, line) in all_lines.iter().take(READ_PREVIEW_LINES).enumerate() {
        let line_num = i + 1;
        let display = truncate_to_width(line, max_width.saturating_sub(10));
        lines.push(Line::from(vec![
            Span::styled(format!("{:4} ", line_num), styles.muted),
            Span::styled(display, styles.normal),
        ]));
    }

    if total > READ_PREVIEW_LINES {
        let remaining = total - READ_PREVIEW_LINES;
        lines.push(Line::from(Span::styled(
            format!("  \u{2026} ({} more lines, {} total)", remaining, total),
            styles.muted,
        )));
    } else if total > 0 {
        lines.push(Line::from(Span::styled(
            format!("  ({} lines)", total),
            styles.muted,
        )));
    }

    lines
}

/// Format a generic tool result (fallback).
pub fn format_generic_result(
    result: &str,
    max_width: usize,
    styles: &ThemeStyles,
) -> Vec<Line<'static>> {
    let mut lines = Vec::new();
    let all_lines: Vec<&str> = result.lines().collect();

    for line in all_lines.iter().take(GENERIC_PREVIEW_LINES) {
        let display = truncate_to_width(line, max_width.saturating_sub(2));
        lines.push(Line::from(Span::styled(
            format!("  {}", display),
            styles.normal,
        )));
    }

    if all_lines.len() > GENERIC_PREVIEW_LINES {
        lines.push(Line::from(Span::styled(
            format!(
                "  \u{2026} ({} more lines)",
                all_lines.len() - GENERIC_PREVIEW_LINES
            ),
            styles.muted,
        )));
    }

    lines
}

/// Format a tool result by tool name.
pub fn format_tool_result(
    name: &str,
    result: &str,
    is_error: bool,
    max_width: usize,
    styles: &ThemeStyles,
) -> Vec<Line<'static>> {
    if is_error {
        return format_error_result(result, max_width, styles);
    }

    // Auto-detect diff if result contains diff markers
    if looks_like_diff(result) {
        return format_diff_result(result, max_width, styles);
    }

    match name {
        "edit" => format_diff_result(result, max_width, styles),
        "bash" => format_bash_result(result, max_width, styles),
        "read" => format_read_result(result, max_width, styles),
        "issue" => format_issue_result(result, max_width, styles),
        _ => format_generic_result(result, max_width, styles),
    }
}

// ── Height calculation ─────────────────────────────────────────────────────

/// Calculate the rendered height for a tool call.
pub fn measure_call_height(name: &str, arguments: &str, max_width: usize) -> u16 {
    let args = parse_tool_args(arguments);

    match name {
        "edit" => format_edit_call(&args, &ThemeStyles::default()).len() as u16,
        "bash" => format_bash_call(&args, max_width, &ThemeStyles::default()).len() as u16,
        "read" => 1, // Always 1 line for read
        "write" => 1,
        "grep" | "find" | "ls" => 1,
        "issue" => {
            // Header + (title + optional tags) for create, or
            // header + #id + (optional changed-fields) for update,
            // or just header + #id for the rest.
            let action = args.get("action").and_then(|v| v.as_str()).unwrap_or("");
            let base = 1u16;
            match action {
                "create" => {
                    base + 1
                        + if args.get("priority").is_some() || args.get("labels").is_some() {
                            1
                        } else {
                            0
                        }
                }
                "list" => base + 1,
                "update" => {
                    let mut extra = 1; // #id line
                    let mut changed = 0u16;
                    if args.get("title").is_some() {
                        changed += 1;
                    }
                    if args.get("body").is_some() {
                        changed += 1;
                    }
                    if args.get("priority").is_some() {
                        changed += 1;
                    }
                    if args.get("status").is_some() {
                        changed += 1;
                    }
                    if args.get("labels").is_some() {
                        changed += 1;
                    }
                    if changed > 0 {
                        extra += 1;
                    }
                    base + extra
                }
                _ => base + 1,
            }
        }
        _ => {
            // Generic: 1 header + up to 3 args
            let args_count = args.as_object().map(|o| o.len().min(3)).unwrap_or(0);
            1 + args_count as u16
        }
    }
}

/// Calculate the rendered height for a tool result.
pub fn measure_result_height(name: &str, result: &str, is_error: bool) -> u16 {
    if is_error {
        let total = result.lines().count();
        let shown = total.min(4);
        return shown as u16 + if total > 4 { 1 } else { 0 };
    }

    if looks_like_diff(result) {
        let total = result.lines().count();
        let shown = total.min(DIFF_PREVIEW_LINES);
        let extra = if total > DIFF_PREVIEW_LINES
            || count_diff_stats(result).0 > 0
            || count_diff_stats(result).1 > 0
        {
            1
        } else {
            0
        };
        return shown as u16 + extra;
    }

    match name {
        "edit" => {
            let total = result.lines().count();
            let shown = total.min(DIFF_PREVIEW_LINES);
            let has_more = total > DIFF_PREVIEW_LINES;
            let has_stats =
                !has_more && (count_diff_stats(result).0 > 0 || count_diff_stats(result).1 > 0);
            let extra = if has_more || has_stats { 1 } else { 0 };
            shown as u16 + extra
        }
        "bash" => {
            let total = result.lines().count();
            let shown = total.min(RESULT_PREVIEW_LINES);
            let extra = if total > RESULT_PREVIEW_LINES { 1 } else { 0 };
            shown as u16 + extra
        }
        "read" => {
            let total = result.lines().count();
            let shown = total.min(READ_PREVIEW_LINES);
            let extra: u16 = 1; // Always show count
            shown as u16 + extra
        }
        "issue" => {
            // We render at most 9 lines (header + up to 8 list entries, or
            // 1 success line + 0–3 follow-ups, or 1 error line + 0–3 details).
            let first = result.lines().next().unwrap_or("");
            let lower = first.to_lowercase();
            let is_error = first.starts_with("issue ")
                && (lower.contains("was modified since last read")
                    || lower.contains("is currently being worked on by")
                    || lower.contains("is not assigned to session")
                    || lower.contains("not found"));
            if is_error {
                1 + result.lines().skip(1).take(3).count() as u16
            } else if first.starts_with("created issue ")
                || first.starts_with("closed issue ")
                || first.starts_with("updated issue ")
                || first.starts_with("released issue ")
                || first.starts_with("linked session to issue ")
                || first.starts_with("assigned issue ")
                || first == "no issues match the filter"
                || (first.starts_with("issue #") && first.contains(" failed: "))
            {
                // Header + up to 3 follow-up lines.
                (1 + result.lines().skip(1).take(3).count() as u16).min(4)
            } else {
                // Multi-line list — cap at 8 + 1 trailing hint.
                let total = result.lines().count();
                let shown = total.min(8);
                let extra = if total > 8 { 1 } else { 0 };
                shown as u16 + extra
            }
        }
        _ => {
            let total = result.lines().count();
            let shown = total.min(GENERIC_PREVIEW_LINES);
            let extra = if total > GENERIC_PREVIEW_LINES { 1 } else { 0 };
            shown as u16 + extra
        }
    }
}

// ── Tests ─────────────────────────────────────────────────────────────────

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

    #[test]
    fn test_shorten_path() {
        let home = dirs::home_dir().unwrap().to_string_lossy().to_string();
        let path = format!("{}/src/main.rs", home);
        assert_eq!(shorten_path(&path), "~/src/main.rs");
    }

    #[test]
    fn test_parse_args() {
        // Use actual home directory so shorten_path works
        let home = dirs::home_dir().unwrap();
        let path = format!("{}/file.rs", home.to_string_lossy());
        let args = format!(r#"{{"path":"{}","offset":10,"limit":50}}"#, path);
        let parsed = parse_tool_args(&args);
        assert_eq!(get_path(&parsed), Some("~/file.rs".to_string()));
        assert_eq!(get_int(&parsed, "offset"), Some(10));
        assert_eq!(get_int(&parsed, "limit"), Some(50));
    }

    #[test]
    fn test_looks_like_diff() {
        assert!(looks_like_diff("@@ -10,3 +10,4 @@\n-old\n+new"));
        assert!(looks_like_diff("-removed\n+added"));
        assert!(!looks_like_diff("hello world\njust text"));
    }

    #[test]
    fn test_count_diff_stats() {
        let diff = "-removed\n-old\n+added\n+new";
        let (added, removed) = count_diff_stats(diff);
        assert_eq!(added, 2);
        assert_eq!(removed, 2);
    }

    #[test]
    fn test_truncate_to_width() {
        let text = "hello world";
        assert_eq!(truncate_to_width(text, 100), "hello world");
        // For max_width=5: "hello" (5 chars) overflows, so truncate to 4 + ellipsis
        // This matches the behavior of the original truncate_str in chat.rs
        assert_eq!(truncate_to_width(text, 5), "hell…");
        assert_eq!(truncate_to_width(text, 0), "");
    }

    #[test]
    fn test_format_edit_call() {
        let args = serde_json::json!({
            "path": "/home/user/src/main.rs",
            "edits": [{"oldText": "foo", "newText": "bar"}]
        });
        let lines = format_edit_call(&args, &ThemeStyles::default());
        assert!(lines[0].to_string().contains("edit"));
        assert!(lines[0].to_string().contains("main.rs"));
    }

    #[test]
    fn test_format_bash_call() {
        let args = serde_json::json!({
            "command": "cargo build --release",
            "timeout": 120
        });
        let lines = format_bash_call(&args, 80, &ThemeStyles::default());
        assert!(lines[0].to_string().contains("$ cargo build"));
    }

    #[test]
    fn test_format_read_call() {
        let args = serde_json::json!({
            "path": "/home/user/src/main.rs",
            "offset": 10,
            "limit": 50
        });
        let lines = format_read_call(&args, &ThemeStyles::default());
        assert!(lines[0].to_string().contains("read"));
        assert!(lines[0].to_string().contains("main.rs:10-59"));
    }

    #[test]
    fn test_format_diff_result() {
        let diff = "@@ -10,3 +10,4 @@\n-old line\n context\n+new line\n+extra line";
        let lines = format_diff_result(diff, 80, &ThemeStyles::default());
        // Should have hunk header + lines + stats
        assert!(!lines.is_empty());
    }

    #[test]
    fn test_format_bash_result() {
        let output = "Compiling mycrate v0.1.0\nFinished release [optimized]";
        let lines = format_bash_result(output, 80, &ThemeStyles::default());
        assert!(!lines.is_empty());
        assert!(lines[0].to_string().contains("Compiling"));
    }

    #[test]
    fn test_format_read_result() {
        let content = "use std::io;\n\nfn main() {\n    println!(\"hello\");\n}\n";
        let lines = format_read_result(content, 80, &ThemeStyles::default());
        assert!(lines[0].to_string().contains("1"));
        assert!(lines[0].to_string().contains("use std"));
    }

    #[test]
    fn test_format_generic_call() {
        let args = serde_json::json!({
            "param1": "value1",
            "param2": "value2"
        });
        let lines = format_generic_call("my_tool", &args, 80, &ThemeStyles::default());
        assert!(!lines.is_empty());
        assert!(lines[0].to_string().contains("my_tool"));
    }

    #[test]
    fn test_has_exit_status() {
        assert!(has_exit_status("Command exited with code 1"));
        assert!(has_exit_status("Command timed out after 120 seconds"));
        assert!(!has_exit_status("Everything is fine"));
    }

    #[test]
    fn test_format_issue_call_create() {
        let args = serde_json::json!({
            "action": "create",
            "title": "Fix login bug",
            "priority": "high",
            "labels": ["bug", "auth"],
        });
        let lines = format_issue_call(&args, 80, &ThemeStyles::default());
        assert!(lines[0].to_string().contains("issue"));
        assert!(lines[0].to_string().contains("create"));
        // Title appears quoted on line 2
        assert!(
            lines
                .iter()
                .any(|l| l.to_string().contains("Fix login bug"))
        );
        // Priority chip present
        assert!(lines.iter().any(|l| l.to_string().contains("[high]")));
        // Labels chip present
        assert!(lines.iter().any(|l| l.to_string().contains("bug,auth")));
    }

    #[test]
    fn test_format_issue_call_start() {
        let args = serde_json::json!({"action": "start", "id": 12});
        let lines = format_issue_call(&args, 80, &ThemeStyles::default());
        assert!(lines[0].to_string().contains("start"));
        assert!(lines[1].to_string().contains("#12"));
    }

    #[test]
    fn test_format_issue_call_list_with_filters() {
        let args = serde_json::json!({
            "action": "list",
            "status": "open",
            "priority": "high",
            "label": "auth",
            "text": "login",
        });
        let lines = format_issue_call(&args, 80, &ThemeStyles::default());
        assert!(lines[0].to_string().contains("list"));
        let combined: String = lines.iter().map(|l| l.to_string()).collect();
        assert!(combined.contains("status=open"));
        assert!(combined.contains("priority=high"));
        assert!(combined.contains("label=auth"));
        assert!(combined.contains("text="));
    }

    #[test]
    fn test_format_issue_result_success() {
        let result = "created issue #12: Fix login bug";
        let lines = format_issue_result(result, 80, &ThemeStyles::default());
        assert!(lines[0].to_string().contains(""));
        assert!(lines[0].to_string().contains("created issue #12"));
    }

    #[test]
    fn test_format_issue_result_closed() {
        let lines = format_issue_result(
            "closed issue #7: Outdated task",
            80,
            &ThemeStyles::default(),
        );
        assert!(lines[0].to_string().contains(""));
        assert!(lines[0].to_string().contains("closed"));
    }

    #[test]
    fn test_format_issue_result_released_warning_color() {
        let lines = format_issue_result("released issue #3", 80, &ThemeStyles::default());
        // Released uses warning style; we only assert semantic content here.
        assert!(lines[0].to_string().contains("released"));
    }

    #[test]
    fn test_format_issue_result_empty_list() {
        let lines = format_issue_result("no issues match the filter", 80, &ThemeStyles::default());
        assert!(lines[0].to_string().contains("no issues"));
    }

    #[test]
    fn test_format_issue_result_conflict() {
        let lines = format_issue_result(
            "issue #12 was modified since last read; re-read and retry",
            80,
            &ThemeStyles::default(),
        );
        // Conflict marker must appear.
        assert!(lines[0].to_string().contains(""));
        assert!(
            lines.iter().any(|l| l.to_string().contains("Conflict"))
                || lines.iter().any(|l| l.to_string().contains("re-read"))
        );
    }

    #[test]
    fn test_format_issue_result_assigned_error() {
        let lines = format_issue_result(
            "issue #12 is currently being worked on by session tui",
            80,
            &ThemeStyles::default(),
        );
        assert!(lines[0].to_string().contains(""));
    }

    #[test]
    fn test_format_issue_result_list_multiline_color() {
        let result = "\
#1    [open]    medium     Fix login bug
#2    [open]    high   🔒  Refactor auth
#3    [closed]  low       Old task";
        let lines = format_issue_result(result, 80, &ThemeStyles::default());
        // 3 entries + no truncation hint.
        assert!(lines.len() >= 3);
        assert!(lines.iter().any(|l| l.to_string().contains("#1")));
        assert!(lines.iter().any(|l| l.to_string().contains("#3")));
    }

    #[test]
    fn test_format_issue_call_unknown_action() {
        let args = serde_json::json!({"action": "frobnicate"});
        let lines = format_issue_call(&args, 80, &ThemeStyles::default());
        assert!(
            lines
                .iter()
                .any(|l| l.to_string().contains("unknown action"))
        );
    }

    #[test]
    fn test_measure_issue_call_create() {
        // 1 header + 1 title + 1 tags = 3
        let args = r#"{"action":"create","title":"X","priority":"high"}"#;
        assert!(measure_call_height("issue", args, 80) >= 3);
    }

    #[test]
    fn test_measure_issue_call_id_only() {
        let args = r#"{"action":"start","id":1}"#;
        // 1 header + 1 id = 2
        assert!(measure_call_height("issue", args, 80) >= 2);
    }

    #[test]
    fn test_measure_issue_result_success_short() {
        let result = "created issue #12: Title";
        assert!(measure_result_height("issue", result, false) >= 1);
    }

    #[test]
    fn test_measure_issue_result_long_list() {
        let result = (1..=20)
            .map(|i| format!("#{i:<4} [open]    medium     Issue {i}"))
            .collect::<Vec<_>>()
            .join("\n");
        // Capped at 8 + 1 hint = 9 lines max.
        let h = measure_result_height("issue", &result, false);
        assert!(h <= 10, "expected height ≤10, got {h}");
    }
}