claude-code-rust 0.3.0

A native Rust terminal interface for Claude Code
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
// Claude Code Rust - A native Rust terminal interface for Claude Code
// Copyright (C) 2025  Simon Peter Rothgang
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.

use crate::app::{InlinePermission, ToolCallInfo};
use crate::ui::diff::{is_markdown_file, lang_from_title, render_diff, strip_outer_code_fence};
use crate::ui::markdown;
use crate::ui::theme;
use agent_client_protocol::{self as acp, PermissionOptionKind};
use ansi_to_tui::IntoText as _;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span, Text};
use ratatui::widgets::{Paragraph, Wrap};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

/// Spinner frames as `&'static str` for use in `status_icon` return type.
const SPINNER_STRS: &[&str] = &[
    "\u{280B}", "\u{2819}", "\u{2839}", "\u{2838}", "\u{283C}", "\u{2834}", "\u{2826}", "\u{2827}",
    "\u{2807}", "\u{280F}",
];

/// Max visible output lines for Execute/Bash tool calls.
/// Total box height = 1 (title) + 1 (command) + this + 1 (bottom border) = 15.
/// TODO: make configurable (see ROADMAP.md)
const TERMINAL_MAX_LINES: usize = 12;

pub fn status_icon(status: acp::ToolCallStatus, spinner_frame: usize) -> (&'static str, Color) {
    match status {
        acp::ToolCallStatus::Pending | acp::ToolCallStatus::InProgress => {
            let s = SPINNER_STRS[spinner_frame % SPINNER_STRS.len()];
            (s, theme::RUST_ORANGE)
        }
        acp::ToolCallStatus::Completed => (theme::ICON_COMPLETED, theme::RUST_ORANGE),
        acp::ToolCallStatus::Failed => (theme::ICON_FAILED, theme::STATUS_ERROR),
        _ => ("?", theme::DIM),
    }
}

/// Render a tool call with caching. Only re-renders when cache is stale.
///
/// For Execute/Bash tool calls, the cache stores **content only** (command, output,
/// permissions) without border decoration. Borders are applied at render time using
/// the current width, so they always fill the terminal correctly after resize.
/// Height for Execute = `content_lines + 2` (title border + bottom border).
///
/// For other tool calls, in-progress calls split title (re-rendered each frame for
/// spinner) from body (cached). Completed calls cache title + body together.
pub fn render_tool_call_cached(
    tc: &mut ToolCallInfo,
    width: u16,
    spinner_frame: usize,
    out: &mut Vec<Line<'static>>,
) {
    let is_execute = matches!(tc.kind, acp::ToolKind::Execute);

    // Execute/Bash: two-layer rendering (cache content, apply borders at render time)
    if is_execute {
        // Ensure content is cached
        if tc.cache.get().is_none() {
            crate::perf::mark("tc::cache_miss_execute");
            let _t = crate::perf::start("tc::render_exec");
            let content = render_execute_content(tc);
            tc.cache.store(content);
        } else {
            crate::perf::mark("tc::cache_hit_execute");
        }
        // Apply borders at render time with current width
        if let Some(content) = tc.cache.get() {
            let bordered = render_execute_with_borders(tc, content, width, spinner_frame);
            let h = {
                let _t = crate::perf::start_with("tc::wrap_height_exec", "lines", bordered.len());
                Paragraph::new(Text::from(bordered.clone()))
                    .wrap(Wrap { trim: false })
                    .line_count(width)
            };
            tc.cache.set_height(h, width);
            out.extend(bordered);
        }
        return;
    }

    // Non-Execute tool calls: existing caching strategy
    let is_in_progress =
        matches!(tc.status, acp::ToolCallStatus::InProgress | acp::ToolCallStatus::Pending);

    // Completed/failed: full cache (title + body together)
    if !is_in_progress {
        if let Some(cached_lines) = tc.cache.get() {
            crate::perf::mark_with("tc::cache_hit", "lines", cached_lines.len());
            out.extend_from_slice(cached_lines);
            return;
        }
        crate::perf::mark("tc::cache_miss");
        let _t = crate::perf::start("tc::render");
        let fresh = render_tool_call(tc, width, spinner_frame);
        let h = {
            let _t = crate::perf::start_with("tc::wrap_height", "lines", fresh.len());
            Paragraph::new(Text::from(fresh.clone())).wrap(Wrap { trim: false }).line_count(width)
        };
        tc.cache.store(fresh);
        tc.cache.set_height(h, width);
        if let Some(stored) = tc.cache.get() {
            out.extend_from_slice(stored);
        }
        return;
    }

    // In-progress: re-render only the title line (spinner), cache the body.
    let fresh_title = render_tool_call_title(tc, width, spinner_frame);
    out.push(fresh_title);

    // Body: use cache if valid, otherwise render and cache.
    if let Some(cached_body) = tc.cache.get() {
        crate::perf::mark_with("tc::cache_hit_body", "lines", cached_body.len());
        out.extend_from_slice(cached_body);
    } else {
        crate::perf::mark("tc::cache_miss_body");
        let _t = crate::perf::start("tc::render_body");
        let body = render_tool_call_body(tc);
        let h = {
            let _t = crate::perf::start_with("tc::wrap_height_body", "lines", body.len());
            Paragraph::new(Text::from(body.clone())).wrap(Wrap { trim: false }).line_count(width)
        };
        tc.cache.store(body);
        tc.cache.set_height(h, width);
        if let Some(stored) = tc.cache.get() {
            out.extend_from_slice(stored);
        }
    }
}

/// Ensure tool call caches are up-to-date and return visual wrapped height at `width`.
/// Returns `(height, lines_wrapped_for_measurement)`.
pub fn measure_tool_call_height_cached(
    tc: &mut ToolCallInfo,
    width: u16,
    spinner_frame: usize,
) -> (usize, usize) {
    let is_execute = matches!(tc.kind, acp::ToolKind::Execute);
    if is_execute {
        if tc.cache.get().is_none() {
            let content = render_execute_content(tc);
            tc.cache.store(content);
        }
        if let Some(content) = tc.cache.get() {
            let bordered = render_execute_with_borders(tc, content, width, spinner_frame);
            let h = Paragraph::new(Text::from(bordered.clone()))
                .wrap(Wrap { trim: false })
                .line_count(width);
            tc.cache.set_height(h, width);
            return (h, bordered.len());
        }
        return (0, 0);
    }

    let is_in_progress =
        matches!(tc.status, acp::ToolCallStatus::InProgress | acp::ToolCallStatus::Pending);

    if !is_in_progress {
        if let Some(h) = tc.cache.height_at(width) {
            return (h, 0);
        }
        if let Some(cached_lines) = tc.cache.get().cloned() {
            let h = Paragraph::new(Text::from(cached_lines.clone()))
                .wrap(Wrap { trim: false })
                .line_count(width);
            tc.cache.set_height(h, width);
            return (h, cached_lines.len());
        }
        let fresh = render_tool_call(tc, width, spinner_frame);
        let h =
            Paragraph::new(Text::from(fresh.clone())).wrap(Wrap { trim: false }).line_count(width);
        tc.cache.store(fresh);
        tc.cache.set_height(h, width);
        return (h, tc.cache.get().map_or(0, Vec::len));
    }

    // In-progress non-execute: title is dynamic, body is cached separately.
    let title = render_tool_call_title(tc, width, spinner_frame);
    let title_h =
        Paragraph::new(Text::from(vec![title])).wrap(Wrap { trim: false }).line_count(width);

    if let Some(body_h) = tc.cache.height_at(width) {
        return (title_h + body_h, 1);
    }
    if let Some(cached_body) = tc.cache.get().cloned() {
        let body_h = Paragraph::new(Text::from(cached_body.clone()))
            .wrap(Wrap { trim: false })
            .line_count(width);
        tc.cache.set_height(body_h, width);
        return (title_h + body_h, cached_body.len() + 1);
    }

    let body = render_tool_call_body(tc);
    let body_h =
        Paragraph::new(Text::from(body.clone())).wrap(Wrap { trim: false }).line_count(width);
    tc.cache.store(body);
    tc.cache.set_height(body_h, width);
    (title_h + body_h, tc.cache.get().map_or(1, |b| b.len() + 1))
}

/// Render just the title line for a non-Execute tool call (the line containing the spinner icon).
/// Used for in-progress tool calls where only the spinner changes each frame.
/// Execute tool calls are handled separately via `render_execute_with_borders`.
fn render_tool_call_title(tc: &ToolCallInfo, _width: u16, spinner_frame: usize) -> Line<'static> {
    let (icon, icon_color) = status_icon(tc.status, spinner_frame);
    let (kind_icon, _kind_name) = theme::tool_kind_label(tc.kind, tc.claude_tool_name.as_deref());

    let mut title_spans = vec![
        Span::styled(format!("  {icon} "), Style::default().fg(icon_color)),
        Span::styled(
            format!("{kind_icon} "),
            Style::default().fg(Color::White).add_modifier(Modifier::BOLD),
        ),
    ];

    title_spans.extend(markdown_inline_spans(&tc.title));

    Line::from(title_spans)
}

/// Render the body lines (everything after the title) for a non-Execute tool call.
/// Used for in-progress tool calls where the body is cached separately from the title.
/// Execute tool calls are handled separately via `render_execute_with_borders`.
fn render_tool_call_body(tc: &ToolCallInfo) -> Vec<Line<'static>> {
    let mut lines = Vec::new();
    render_standard_body(tc, &mut lines);
    lines
}

/// Render a complete non-Execute tool call (title + body).
/// Execute tool calls are handled separately via `render_execute_with_borders`.
fn render_tool_call(tc: &ToolCallInfo, width: u16, spinner_frame: usize) -> Vec<Line<'static>> {
    let title = render_tool_call_title(tc, width, spinner_frame);
    let mut lines = vec![title];
    render_standard_body(tc, &mut lines);
    lines
}

/// Render the body (everything after the title line) of a standard (non-Execute) tool call.
fn render_standard_body(tc: &ToolCallInfo, lines: &mut Vec<Line<'static>>) {
    let pipe_style = Style::default().fg(theme::DIM);
    let has_permission = tc.pending_permission.is_some();

    // Diffs (Edit tool) are always shown -- user needs to see changes
    let has_diff = tc.content.iter().any(|c| matches!(c, acp::ToolCallContent::Diff(_)));

    if tc.content.is_empty() && !has_permission {
        return;
    }

    // Force expanded when permission is pending (user needs to see context)
    let effectively_collapsed = tc.collapsed && !has_diff && !has_permission;

    if effectively_collapsed {
        // Collapsed: show summary + ctrl+o hint
        let summary = content_summary(tc);
        lines.push(Line::from(vec![
            Span::styled("  \u{2514}\u{2500} ", pipe_style),
            Span::styled(summary, Style::default().fg(theme::DIM)),
            Span::styled("  ctrl+o to expand", Style::default().fg(theme::DIM)),
        ]));
    } else {
        // Expanded: render full content with | prefix on each line
        let mut content_lines = render_tool_content(tc);

        // Append inline permission controls if pending
        if let Some(ref perm) = tc.pending_permission {
            content_lines.extend(render_permission_lines(perm));
        }

        let last_idx = content_lines.len().saturating_sub(1);
        for (i, content_line) in content_lines.into_iter().enumerate() {
            let prefix = if i == last_idx {
                "  \u{2514}\u{2500} " // corner
            } else {
                "  \u{2502}  " // pipe
            };
            let mut spans = vec![Span::styled(prefix.to_owned(), pipe_style)];
            spans.extend(content_line.spans);
            lines.push(Line::from(spans));
        }
    }
}

/// Render Execute/Bash content lines WITHOUT any border decoration.
/// This is width-independent and safe to cache across resizes.
/// Returns: command line + output lines + permission lines (no border prefixes).
fn render_execute_content(tc: &ToolCallInfo) -> Vec<Line<'static>> {
    let mut lines: Vec<Line<'static>> = Vec::new();

    // Command line (no border prefix)
    if let Some(ref cmd) = tc.terminal_command {
        lines.push(Line::from(vec![
            Span::styled(
                "$ ",
                Style::default().fg(theme::RUST_ORANGE).add_modifier(Modifier::BOLD),
            ),
            Span::styled(cmd.clone(), Style::default().fg(Color::Yellow)),
        ]));
    }

    // Output lines (capped, no border prefix)
    let mut body_lines: Vec<Line<'static>> = Vec::new();

    if let Some(ref output) = tc.terminal_output {
        let raw_lines: Vec<Line<'static>> = if let Ok(ansi_text) = output.as_bytes().into_text() {
            ansi_text
                .lines
                .into_iter()
                .map(|line| {
                    let owned: Vec<Span<'static>> = line
                        .spans
                        .into_iter()
                        .map(|s| Span::styled(s.content.into_owned(), s.style))
                        .collect();
                    Line::from(owned)
                })
                .collect()
        } else {
            output.lines().map(|l| Line::from(l.to_owned())).collect()
        };

        let total = raw_lines.len();
        if total > TERMINAL_MAX_LINES {
            let skipped = total - TERMINAL_MAX_LINES;
            body_lines.push(Line::from(Span::styled(
                format!("... {skipped} lines hidden ..."),
                Style::default().fg(theme::DIM),
            )));
            body_lines.extend(raw_lines.into_iter().skip(skipped));
        } else {
            body_lines = raw_lines;
        }
    } else if matches!(tc.status, acp::ToolCallStatus::InProgress) {
        body_lines.push(Line::from(Span::styled("running...", Style::default().fg(theme::DIM))));
    }

    lines.extend(body_lines);

    // Inline permission controls (no border prefix)
    if let Some(ref perm) = tc.pending_permission {
        lines.extend(render_permission_lines(perm));
    }

    lines
}

/// Apply Execute/Bash box borders around pre-rendered content lines.
/// This is called at render time with the current width, so borders always
/// fill the terminal correctly even after resize.
fn render_execute_with_borders(
    tc: &ToolCallInfo,
    content: &[Line<'static>],
    width: u16,
    spinner_frame: usize,
) -> Vec<Line<'static>> {
    let border = Style::default().fg(theme::DIM);
    let inner_w = (width as usize).saturating_sub(2);
    let mut out = Vec::with_capacity(content.len() + 2);

    // Top border with status icon and title
    let (status_icon_str, icon_color) = status_icon(tc.status, spinner_frame);
    let line_budget = width as usize;
    let left_prefix = vec![
        Span::styled("  \u{256D}\u{2500}", border),
        Span::styled(format!(" {status_icon_str} "), Style::default().fg(icon_color)),
        Span::styled("Bash ", Style::default().fg(Color::White).add_modifier(Modifier::BOLD)),
    ];
    let prefix_w = spans_width(&left_prefix);
    let right_border_w = 1; // "â•®"
    // Reserve at least one fill char so the border looks continuous.
    let title_max_w = line_budget.saturating_sub(prefix_w + right_border_w + 1);
    let title_spans = truncate_spans_to_width(markdown_inline_spans(&tc.title), title_max_w);
    let title_w = spans_width(&title_spans);
    let fill_w = line_budget.saturating_sub(prefix_w + title_w + right_border_w);
    let top_fill: String = "\u{2500}".repeat(fill_w);

    let mut top = left_prefix;
    top.extend(title_spans);
    top.push(Span::styled(format!("{top_fill}\u{256E}"), border));
    out.push(Line::from(top));

    // Content lines with left border prefix
    for line in content {
        let mut spans = vec![Span::styled("  \u{2502} ", border)];
        spans.extend(line.spans.iter().cloned());
        out.push(Line::from(spans));
    }

    // Bottom border
    let bottom_fill: String = "\u{2500}".repeat(inner_w.saturating_sub(2));
    out.push(Line::from(Span::styled(format!("  \u{2570}{bottom_fill}\u{256F}"), border)));

    out
}

/// Render inline permission options on a single compact line.
/// Format: `▸ ✓ Allow once (Ctrl+y)  ·  ✓ Allow always (Ctrl+a)  ·  ✗ Reject (Ctrl+n)`
/// Unfocused permissions are dimmed to indicate they don't have keyboard input.
fn render_permission_lines(perm: &InlinePermission) -> Vec<Line<'static>> {
    // Unfocused permissions: show a dimmed "waiting for focus" line
    if !perm.focused {
        return vec![
            Line::default(),
            Line::from(Span::styled(
                "  \u{25cb} Waiting for input\u{2026} (\u{2191}\u{2193} to focus)",
                Style::default().fg(theme::DIM),
            )),
        ];
    }

    let mut spans: Vec<Span<'static>> = Vec::new();
    let dot = Span::styled("  \u{00b7}  ", Style::default().fg(theme::DIM));

    for (i, opt) in perm.options.iter().enumerate() {
        let is_selected = i == perm.selected_index;
        let is_allow =
            matches!(opt.kind, PermissionOptionKind::AllowOnce | PermissionOptionKind::AllowAlways);

        let (icon, icon_color) = if is_allow {
            ("\u{2713}", Color::Green) // ✓
        } else {
            ("\u{2717}", Color::Red) // ✗
        };

        // Separator between options
        if i > 0 {
            spans.push(dot.clone());
        }

        // Selection indicator
        if is_selected {
            spans.push(Span::styled(
                "\u{25b8} ",
                Style::default().fg(theme::RUST_ORANGE).add_modifier(Modifier::BOLD),
            ));
        }

        spans.push(Span::styled(format!("{icon} "), Style::default().fg(icon_color)));

        let name_style = if is_selected {
            Style::default().fg(Color::White).add_modifier(Modifier::BOLD)
        } else {
            Style::default().fg(Color::Gray)
        };
        let mut name_spans = markdown_inline_spans(&opt.name);
        if name_spans.is_empty() {
            spans.push(Span::styled(opt.name.clone(), name_style));
        } else {
            for span in &mut name_spans {
                span.style = span.style.patch(name_style);
            }
            spans.extend(name_spans);
        }

        let shortcut = match opt.kind {
            PermissionOptionKind::AllowOnce => " (Ctrl+y)",
            PermissionOptionKind::AllowAlways => " (Ctrl+a)",
            PermissionOptionKind::RejectOnce => " (Ctrl+n)",
            _ => "",
        };
        spans.push(Span::styled(shortcut, Style::default().fg(theme::DIM)));
    }

    vec![
        Line::default(),
        Line::from(spans),
        Line::from(Span::styled(
            "\u{2190}\u{2192} select  \u{2191}\u{2193} next  enter confirm  esc reject",
            Style::default().fg(theme::DIM),
        )),
    ]
}

fn markdown_inline_spans(input: &str) -> Vec<Span<'static>> {
    markdown::render_markdown_safe(input, None).into_iter().next().map_or_else(Vec::new, |line| {
        line.spans.into_iter().map(|s| Span::styled(s.content.into_owned(), s.style)).collect()
    })
}

fn spans_width(spans: &[Span<'static>]) -> usize {
    spans.iter().map(|s| UnicodeWidthStr::width(s.content.as_ref())).sum()
}

fn truncate_spans_to_width(spans: Vec<Span<'static>>, max_width: usize) -> Vec<Span<'static>> {
    if max_width == 0 {
        return Vec::new();
    }
    if spans_width(&spans) <= max_width {
        return spans;
    }

    let keep_width = max_width.saturating_sub(1);
    let mut used = 0usize;
    let mut out: Vec<Span<'static>> = Vec::new();

    for span in spans {
        if used >= keep_width {
            break;
        }
        let mut chunk = String::new();
        for ch in span.content.chars() {
            let w = UnicodeWidthChar::width(ch).unwrap_or(0);
            if used + w > keep_width {
                break;
            }
            chunk.push(ch);
            used += w;
        }
        if !chunk.is_empty() {
            out.push(Span::styled(chunk, span.style));
        }
    }
    out.push(Span::styled("\u{2026}", Style::default().fg(theme::DIM)));
    out
}

/// One-line summary for collapsed tool calls.
fn content_summary(tc: &ToolCallInfo) -> String {
    // For Execute tool calls, show last non-empty line of terminal output
    if tc.terminal_id.is_some() {
        if let Some(ref output) = tc.terminal_output {
            if matches!(tc.status, acp::ToolCallStatus::Failed)
                && let Some(msg) = extract_tool_use_error_message(output)
            {
                return msg;
            }
            let last = output.lines().rev().find(|l| !l.trim().is_empty());
            if let Some(line) = last {
                return if line.chars().count() > 80 {
                    let truncated: String = line.chars().take(77).collect();
                    format!("{truncated}...")
                } else {
                    line.to_owned()
                };
            }
        }
        return if matches!(tc.status, acp::ToolCallStatus::InProgress) {
            "running...".to_owned()
        } else {
            String::new()
        };
    }

    for content in &tc.content {
        match content {
            acp::ToolCallContent::Diff(diff) => {
                let name = diff.path.file_name().map_or_else(
                    || diff.path.to_string_lossy().into_owned(),
                    |f| f.to_string_lossy().into_owned(),
                );
                return name;
            }
            acp::ToolCallContent::Content(c) => {
                if let acp::ContentBlock::Text(text) = &c.content {
                    let stripped = strip_outer_code_fence(&text.text);
                    if matches!(tc.status, acp::ToolCallStatus::Failed)
                        && let Some(msg) = extract_tool_use_error_message(&stripped)
                    {
                        return msg;
                    }
                    let first = stripped.lines().next().unwrap_or("");
                    return if first.chars().count() > 60 {
                        let truncated: String = first.chars().take(57).collect();
                        format!("{truncated}...")
                    } else {
                        first.to_owned()
                    };
                }
            }
            _ => {}
        }
    }
    String::new()
}

/// Render the full content of a tool call as lines.
fn render_tool_content(tc: &ToolCallInfo) -> Vec<Line<'static>> {
    let is_execute = matches!(tc.kind, acp::ToolKind::Execute);
    let mut lines: Vec<Line<'static>> = Vec::new();

    // For Execute tool calls with terminal output, render the live output
    if is_execute {
        if let Some(ref output) = tc.terminal_output {
            if matches!(tc.status, acp::ToolCallStatus::Failed)
                && let Some(msg) = extract_tool_use_error_message(output)
            {
                lines.extend(render_tool_use_error_content(&msg));
            } else if let Ok(ansi_text) = output.as_bytes().into_text() {
                for line in ansi_text.lines {
                    let owned: Vec<Span<'static>> = line
                        .spans
                        .into_iter()
                        .map(|s| Span::styled(s.content.into_owned(), s.style))
                        .collect();
                    lines.push(Line::from(owned));
                }
            } else {
                for text_line in output.lines() {
                    lines.push(Line::from(text_line.to_owned()));
                }
            }
        } else if matches!(tc.status, acp::ToolCallStatus::InProgress) {
            lines.push(Line::from(Span::styled("running...", Style::default().fg(theme::DIM))));
        }
        debug_failed_tool_render(tc);
        return lines;
    }

    for content in &tc.content {
        match content {
            acp::ToolCallContent::Diff(diff) => {
                lines.extend(render_diff(diff));
            }
            acp::ToolCallContent::Content(c) => {
                if let acp::ContentBlock::Text(text) = &c.content {
                    let stripped = strip_outer_code_fence(&text.text);
                    if matches!(tc.status, acp::ToolCallStatus::Failed)
                        && let Some(msg) = extract_tool_use_error_message(&stripped)
                    {
                        lines.extend(render_tool_use_error_content(&msg));
                        continue;
                    }
                    if matches!(tc.status, acp::ToolCallStatus::Failed)
                        && looks_like_internal_error(&stripped)
                    {
                        lines.extend(render_internal_failure_content(&stripped));
                        continue;
                    }
                    let md_source = if is_markdown_file(&tc.title) {
                        stripped
                    } else {
                        let lang = lang_from_title(&tc.title);
                        format!("```{lang}\n{stripped}\n```")
                    };
                    for line in markdown::render_markdown_safe(&md_source, None) {
                        let owned: Vec<Span<'static>> = line
                            .spans
                            .into_iter()
                            .map(|s| Span::styled(s.content.into_owned(), s.style))
                            .collect();
                        lines.push(Line::from(owned));
                    }
                }
            }
            _ => {}
        }
    }

    debug_failed_tool_render(tc);
    lines
}

fn render_internal_failure_content(payload: &str) -> Vec<Line<'static>> {
    let summary = summarize_internal_error(payload);
    let mut lines = vec![Line::from(Span::styled(
        "Internal ACP/adapter error",
        Style::default().fg(theme::STATUS_ERROR).add_modifier(Modifier::BOLD),
    ))];
    if !summary.is_empty() {
        lines.push(Line::from(Span::styled(summary, Style::default().fg(theme::STATUS_ERROR))));
    }
    lines
}

fn render_tool_use_error_content(message: &str) -> Vec<Line<'static>> {
    message
        .lines()
        .filter(|line| !line.trim().is_empty())
        .map(|line| {
            Line::from(Span::styled(line.to_owned(), Style::default().fg(theme::STATUS_ERROR)))
        })
        .collect()
}

fn debug_failed_tool_render(tc: &ToolCallInfo) {
    if !matches!(tc.status, acp::ToolCallStatus::Failed) {
        return;
    }

    let Some(text_payload) = tc.content.iter().find_map(|content| match content {
        acp::ToolCallContent::Content(c) => match &c.content {
            acp::ContentBlock::Text(t) => Some(t.text.as_str().to_owned()),
            _ => None,
        },
        _ => None,
    }) else {
        // Skip generic command failures that only have terminal stderr/stdout.
        // We want ACP/adapter-style structured error payloads here.
        return;
    };
    if !looks_like_internal_error(&text_payload) {
        return;
    }
    let text_preview = summarize_internal_error(&text_payload);

    let terminal_preview = tc
        .terminal_output
        .as_deref()
        .map_or_else(|| "<no terminal output>".to_owned(), preview_for_log);

    tracing::debug!(
        tool_call_id = %tc.id,
        title = %tc.title,
        kind = ?tc.kind,
        content_blocks = tc.content.len(),
        text_preview = %text_preview,
        terminal_preview = %terminal_preview,
        "Failed tool call render payload"
    );
}

fn preview_for_log(input: &str) -> String {
    const LIMIT: usize = 240;
    let mut out = String::new();
    for (i, ch) in input.chars().enumerate() {
        if i >= LIMIT {
            out.push_str("...");
            break;
        }
        out.push(ch);
    }
    out.replace('\n', "\\n")
}

fn looks_like_internal_error(input: &str) -> bool {
    let lower = input.to_ascii_lowercase();
    has_internal_error_keywords(&lower)
        || looks_like_json_rpc_error_shape(&lower)
        || looks_like_xml_error_shape(&lower)
}

fn has_internal_error_keywords(lower: &str) -> bool {
    [
        "internal error",
        "adapter",
        "acp",
        "json-rpc",
        "rpc",
        "protocol error",
        "transport",
        "handshake failed",
        "session creation failed",
        "connection closed",
        "event channel closed",
    ]
    .iter()
    .any(|needle| lower.contains(needle))
}

fn looks_like_json_rpc_error_shape(lower: &str) -> bool {
    (lower.contains("\"jsonrpc\"") && lower.contains("\"error\""))
        || lower.contains("\"code\":-32603")
        || lower.contains("\"code\": -32603")
}

fn looks_like_xml_error_shape(lower: &str) -> bool {
    let has_error_node = lower.contains("<error") || lower.contains("<fault");
    let has_detail_node = lower.contains("<message>") || lower.contains("<code>");
    has_error_node && has_detail_node
}

fn extract_tool_use_error_message(input: &str) -> Option<String> {
    extract_xml_tag_value(input, "tool_use_error")
        .map(str::trim)
        .filter(|s| !s.is_empty())
        .map(str::to_owned)
}

fn summarize_internal_error(input: &str) -> String {
    if let Some(msg) = extract_xml_tag_value(input, "message") {
        return preview_for_log(msg);
    }
    if let Some(msg) = extract_json_string_field(input, "message") {
        return preview_for_log(&msg);
    }
    let fallback = input.lines().find(|line| !line.trim().is_empty()).unwrap_or(input);
    preview_for_log(fallback.trim())
}

fn extract_xml_tag_value<'a>(input: &'a str, tag: &str) -> Option<&'a str> {
    let lower = input.to_ascii_lowercase();
    let open = format!("<{tag}>");
    let close = format!("</{tag}>");
    let start = lower.find(&open)? + open.len();
    let end = start + lower[start..].find(&close)?;
    let value = input[start..end].trim();
    (!value.is_empty()).then_some(value)
}

fn extract_json_string_field(input: &str, field: &str) -> Option<String> {
    let needle = format!("\"{field}\"");
    let start = input.find(&needle)? + needle.len();
    let rest = input[start..].trim_start();
    let colon_idx = rest.find(':')?;
    let mut chars = rest[colon_idx + 1..].trim_start().chars();
    if chars.next()? != '"' {
        return None;
    }

    let mut escaped = false;
    let mut out = String::new();
    for ch in chars {
        if escaped {
            let mapped = match ch {
                'n' => '\n',
                'r' => '\r',
                't' => '\t',
                '"' => '"',
                '\\' => '\\',
                _ => ch,
            };
            out.push(mapped);
            escaped = false;
            continue;
        }
        match ch {
            '\\' => escaped = true,
            '"' => return Some(out),
            _ => out.push(ch),
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::BlockCache;
    use pretty_assertions::assert_eq;

    // status_icon

    #[test]
    fn status_icon_pending() {
        let (icon, color) = status_icon(acp::ToolCallStatus::Pending, 0);
        assert!(!icon.is_empty());
        assert_eq!(color, theme::RUST_ORANGE);
    }

    #[test]
    fn status_icon_in_progress() {
        let (icon, color) = status_icon(acp::ToolCallStatus::InProgress, 3);
        assert!(!icon.is_empty());
        assert_eq!(color, theme::RUST_ORANGE);
    }

    #[test]
    fn status_icon_completed() {
        let (icon, color) = status_icon(acp::ToolCallStatus::Completed, 0);
        assert_eq!(icon, theme::ICON_COMPLETED);
        assert_eq!(color, theme::RUST_ORANGE);
    }

    #[test]
    fn status_icon_failed() {
        let (icon, color) = status_icon(acp::ToolCallStatus::Failed, 0);
        assert_eq!(icon, theme::ICON_FAILED);
        assert_eq!(color, theme::STATUS_ERROR);
    }

    #[test]
    fn status_icon_spinner_wraps() {
        let (icon_a, _) = status_icon(acp::ToolCallStatus::InProgress, 0);
        let (icon_b, _) = status_icon(acp::ToolCallStatus::InProgress, SPINNER_STRS.len());
        assert_eq!(icon_a, icon_b);
    }

    #[test]
    fn status_icon_all_spinner_frames_valid() {
        for i in 0..SPINNER_STRS.len() {
            let (icon, _) = status_icon(acp::ToolCallStatus::InProgress, i);
            assert!(!icon.is_empty());
        }
    }

    /// Spinner frames are all distinct.
    #[test]
    fn status_icon_spinner_frames_distinct() {
        let frames: Vec<&str> = (0..SPINNER_STRS.len())
            .map(|i| status_icon(acp::ToolCallStatus::InProgress, i).0)
            .collect();
        for i in 0..frames.len() {
            for j in (i + 1)..frames.len() {
                assert_ne!(frames[i], frames[j], "frames {i} and {j} are identical");
            }
        }
    }

    /// Large spinner frame number wraps correctly.
    #[test]
    fn status_icon_spinner_large_frame() {
        let (icon, _) = status_icon(acp::ToolCallStatus::Pending, 999_999);
        assert!(!icon.is_empty());
    }

    #[test]
    fn truncate_spans_adds_ellipsis_when_needed() {
        let spans = vec![Span::raw("abcdefghijklmnopqrstuvwxyz")];
        let out = truncate_spans_to_width(spans, 8);
        let rendered: String = out.iter().map(|s| s.content.as_ref()).collect();
        assert_eq!(rendered, "abcdefg\u{2026}");
        assert!(spans_width(&out) <= 8);
    }

    #[test]
    fn markdown_inline_spans_removes_markdown_syntax() {
        let spans = markdown_inline_spans("**Allow** _once_");
        let rendered: String = spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(rendered.contains("Allow"));
        assert!(rendered.contains("once"));
        assert!(!rendered.contains('*'));
        assert!(!rendered.contains('_'));
    }

    #[test]
    fn execute_top_border_does_not_wrap_for_long_title() {
        use crate::app::BlockCache;

        let tc = ToolCallInfo {
            id: "tc-1".into(),
            title: "echo very long command title with markdown **bold** and path /a/b/c/d/e/f"
                .into(),
            kind: acp::ToolKind::Execute,
            status: acp::ToolCallStatus::Pending,
            content: Vec::new(),
            collapsed: false,
            claude_tool_name: Some("Bash".into()),
            hidden: false,
            terminal_id: None,
            terminal_command: None,
            terminal_output: None,
            terminal_output_len: 0,
            cache: BlockCache::default(),
            pending_permission: None,
        };

        let rendered = render_execute_with_borders(&tc, &[], 80, 0);
        let top = rendered.first().expect("top border line");
        assert!(spans_width(&top.spans) <= 80);
    }

    #[test]
    fn internal_error_detection_accepts_xml_payload() {
        let payload =
            "<error><code>-32603</code><message>Adapter process crashed</message></error>";
        assert!(looks_like_internal_error(payload));
    }

    #[test]
    fn internal_error_detection_rejects_plain_bash_failure() {
        let payload = "bash: unknown_command: command not found";
        assert!(!looks_like_internal_error(payload));
    }

    #[test]
    fn summarize_internal_error_prefers_xml_message() {
        let payload =
            "<error><code>-32603</code><message>Adapter process crashed</message></error>";
        assert_eq!(summarize_internal_error(payload), "Adapter process crashed");
    }

    #[test]
    fn summarize_internal_error_reads_json_rpc_message() {
        let payload = r#"{"jsonrpc":"2.0","error":{"code":-32603,"message":"internal rpc fault"}}"#;
        assert_eq!(summarize_internal_error(payload), "internal rpc fault");
    }

    #[test]
    fn extract_tool_use_error_message_reads_inner_text() {
        let payload = "<tool_use_error>Sibling tool call errored</tool_use_error>";
        assert_eq!(
            extract_tool_use_error_message(payload).as_deref(),
            Some("Sibling tool call errored")
        );
    }

    #[test]
    fn render_tool_use_error_content_shows_only_inner_text_lines() {
        let lines = render_tool_use_error_content("Line A\nLine B");
        let rendered: Vec<String> = lines
            .iter()
            .map(|line| line.spans.iter().map(|s| s.content.as_ref()).collect())
            .collect();
        assert_eq!(rendered, vec!["Line A", "Line B"]);
    }

    #[test]
    fn content_summary_only_extracts_tool_use_error_for_failed_execute() {
        let tc = ToolCallInfo {
            id: "tc-1".into(),
            title: "Bash".into(),
            kind: acp::ToolKind::Execute,
            status: acp::ToolCallStatus::Completed,
            content: Vec::new(),
            collapsed: true,
            claude_tool_name: Some("Bash".into()),
            hidden: false,
            terminal_id: Some("term-1".into()),
            terminal_command: Some("echo done".into()),
            terminal_output: Some("<tool_use_error>bad</tool_use_error>\ndone".into()),
            terminal_output_len: 0,
            cache: BlockCache::default(),
            pending_permission: None,
        };
        assert_eq!(content_summary(&tc), "done");
    }

    #[test]
    fn content_summary_extracts_tool_use_error_for_failed_execute() {
        let tc = ToolCallInfo {
            id: "tc-1".into(),
            title: "Bash".into(),
            kind: acp::ToolKind::Execute,
            status: acp::ToolCallStatus::Failed,
            content: Vec::new(),
            collapsed: true,
            claude_tool_name: Some("Bash".into()),
            hidden: false,
            terminal_id: Some("term-1".into()),
            terminal_command: Some("echo done".into()),
            terminal_output: Some("<tool_use_error>bad</tool_use_error>\ndone".into()),
            terminal_output_len: 0,
            cache: BlockCache::default(),
            pending_permission: None,
        };
        assert_eq!(content_summary(&tc), "bad");
    }
}