claude-history 0.1.51

Fuzzy-search Claude Code conversation history from the terminal.
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
use crate::claude::{AssistantMessage, ContentBlock, LogEntry, UserContent};
use crate::cli::DebugLevel;
use crate::debug;
use crate::debug_log;
use crate::error::Result;
use crate::markdown::render_markdown;
use crate::pager;
use crate::tool_format;
use crate::tui::theme;
use colored::{ColoredString, Colorize, CustomColor};
use crossterm::terminal;
use std::fs::File;
use std::io::{self, BufRead, BufReader, Write};
use std::path::Path;

/// Configuration options for displaying conversations
#[derive(Debug, Clone, Default)]
pub struct DisplayOptions {
    /// Hide tool calls and results
    pub no_tools: bool,
    /// Show thinking/reasoning blocks
    pub show_thinking: bool,
    /// Debug level for error logging
    pub debug_level: Option<DebugLevel>,
    /// Use a pager for output (less/more)
    pub use_pager: bool,
    /// Disable colored output
    pub no_color: bool,
}

const NAME_WIDTH: usize = 9;
const SEPARATOR: &str = "";
const SEPARATOR_WIDTH: usize = 3; // Display width of " │ "

/// Convert a theme RGB tuple to a colored CustomColor
fn cc(rgb: (u8, u8, u8)) -> CustomColor {
    CustomColor {
        r: rgb.0,
        g: rgb.1,
        b: rgb.2,
    }
}

fn teal() -> CustomColor {
    cc(theme::detect_theme().accent)
}
fn dim_teal() -> CustomColor {
    cc(theme::detect_theme().accent_dim)
}
fn separator_color() -> CustomColor {
    cc(theme::detect_theme().border)
}
fn tool_text() -> CustomColor {
    cc(theme::detect_theme().tool_text)
}
fn diff_add() -> CustomColor {
    cc(theme::detect_theme().diff_add)
}
fn diff_remove() -> CustomColor {
    cc(theme::detect_theme().diff_remove)
}

/// Trait for formatting conversation output
///
/// Implementors handle the actual rendering of conversation elements,
/// allowing the same processing logic to output in different formats
/// (ledger-style with markdown, plain text, etc.)
trait OutputFormatter {
    /// Format and output user text content
    fn format_user_text(&mut self, text: &str);

    /// Format and output assistant text content
    fn format_assistant_text(&mut self, text: &str);

    /// Format and output a tool call
    fn format_tool_call(&mut self, name: &str, input: &serde_json::Value);

    /// Format and output a tool result
    fn format_tool_result(&mut self, content: Option<&serde_json::Value>);

    /// Format and output a thinking/reasoning block
    fn format_thinking(&mut self, thought: &str);

    /// End the current message block (add spacing)
    fn end_message(&mut self);

    /// Format and output agent (subagent) user text content
    fn format_agent_user_text(&mut self, agent_id: &str, text: &str);

    /// Format and output agent (subagent) assistant text content
    fn format_agent_assistant_text(&mut self, agent_id: &str, text: &str);

    /// Format and output an agent tool call
    fn format_agent_tool_call(&mut self, agent_id: &str, name: &str, input: &serde_json::Value);

    /// Format and output an agent tool result
    fn format_agent_tool_result(&mut self, agent_id: &str, content: Option<&serde_json::Value>);
}

/// Ledger-style formatter with markdown rendering and aligned columns
struct LedgerFormatter<'a, W: Write + ?Sized> {
    writer: &'a mut W,
    content_width: usize,
}

impl<'a, W: Write + ?Sized> LedgerFormatter<'a, W> {
    fn new(writer: &'a mut W, content_width: usize) -> Self {
        Self {
            writer,
            content_width,
        }
    }

    /// Print lines in ledger format with a name on the first line
    fn print_lines<F>(&mut self, name: &str, style: F, text: &str)
    where
        F: Fn(&str) -> ColoredString,
    {
        let wrapped_lines = wrap_text(text, self.content_width);

        for (i, line) in wrapped_lines.iter().enumerate() {
            if i == 0 {
                let padded = format!("{:>width$}", name, width = NAME_WIDTH);
                let _ = write!(self.writer, "{}", style(&padded));
            } else {
                let _ = write!(self.writer, "{:>width$}", "", width = NAME_WIDTH);
            }
            let _ = write!(self.writer, "{}", SEPARATOR.custom_color(separator_color()));
            let _ = writeln!(self.writer, "{}", line);
        }
    }

    /// Print continuation lines with dimmed content
    fn print_continuation(&mut self, text: &str) {
        for line in wrap_text(text, self.content_width) {
            let _ = write!(self.writer, "{:>width$}", "", width = NAME_WIDTH);
            let _ = write!(self.writer, "{}", SEPARATOR.custom_color(separator_color()));
            let _ = writeln!(self.writer, "{}", line.dimmed());
        }
    }

    /// Print tool body with diff-aware coloring
    fn print_tool_body(&mut self, text: &str) {
        for line in text.lines() {
            let _ = write!(self.writer, "{:>width$}", "", width = NAME_WIDTH);
            let _ = write!(self.writer, "{}", SEPARATOR.custom_color(separator_color()));
            if line.starts_with("+ ") {
                let _ = writeln!(self.writer, "{}", line.custom_color(diff_add()));
            } else if line.starts_with("- ") {
                let _ = writeln!(self.writer, "{}", line.custom_color(diff_remove()));
            } else {
                let _ = writeln!(self.writer, "{}", line.dimmed());
            }
        }
    }

    /// Print pre-formatted markdown text with ledger layout
    fn print_markdown<F>(&mut self, name: &str, style: F, text: &str)
    where
        F: Fn(&str) -> ColoredString,
    {
        let lines: Vec<&str> = text.lines().collect();

        if lines.is_empty() {
            let padded = format!("{:>width$}", name, width = NAME_WIDTH);
            let _ = write!(self.writer, "{}", style(&padded));
            let _ = write!(self.writer, "{}", SEPARATOR.custom_color(separator_color()));
            let _ = writeln!(self.writer);
            return;
        }

        for (i, line) in lines.iter().enumerate() {
            if i == 0 {
                let padded = format!("{:>width$}", name, width = NAME_WIDTH);
                let _ = write!(self.writer, "{}", style(&padded));
            } else {
                let _ = write!(self.writer, "{:>width$}", "", width = NAME_WIDTH);
            }
            let _ = write!(self.writer, "{}", SEPARATOR.custom_color(separator_color()));
            let _ = writeln!(self.writer, "{}", line);
        }
    }
}

impl<W: Write + ?Sized> OutputFormatter for LedgerFormatter<'_, W> {
    fn format_user_text(&mut self, text: &str) {
        let rendered = render_markdown(text, self.content_width);
        self.print_markdown("You", |s| s.white().bold(), &rendered);
    }

    fn format_assistant_text(&mut self, text: &str) {
        let rendered = render_markdown(text, self.content_width);
        self.print_markdown("Claude", |s| s.custom_color(teal()).bold(), &rendered);
    }

    fn format_tool_call(&mut self, name: &str, input: &serde_json::Value) {
        let formatted = tool_format::format_tool_call(name, input, self.content_width);

        // Print the header with appropriate styling
        let padded_name = format!("{:>width$}", "Claude", width = NAME_WIDTH);
        let _ = write!(self.writer, "{}", padded_name.custom_color(dim_teal()));
        let _ = write!(self.writer, "{}", SEPARATOR.custom_color(separator_color()));

        // Print the header in subtle gray
        let _ = writeln!(
            self.writer,
            "{}",
            formatted.header.custom_color(tool_text())
        );

        // Print the body if present, with empty line separator
        if let Some(body) = formatted.body {
            // Empty line between header and body
            let _ = write!(self.writer, "{:>width$}", "", width = NAME_WIDTH);
            let _ = writeln!(self.writer, "{}", SEPARATOR.custom_color(separator_color()));
            self.print_tool_body(&body);
        }
    }

    fn format_tool_result(&mut self, content: Option<&serde_json::Value>) {
        // Render markdown for string content, otherwise format as JSON
        let rendered = match content {
            Some(serde_json::Value::String(s)) => render_markdown(s, self.content_width),
            _ => format_tool_content(content),
        };

        // Print with ↳ Result label
        self.print_markdown("↳ Result", |s| s.custom_color(tool_text()), &rendered);
    }

    fn format_thinking(&mut self, thought: &str) {
        self.print_lines("Thinking", |s| s.custom_color(dim_teal()), thought);
    }

    fn end_message(&mut self) {
        let _ = writeln!(self.writer);
    }

    fn format_agent_user_text(&mut self, agent_id: &str, text: &str) {
        let rendered = render_markdown(text, self.content_width);
        let name = format!("{}", short_agent_id(agent_id));
        self.print_markdown(&name, |s| s.white().dimmed(), &rendered);
    }

    fn format_agent_assistant_text(&mut self, agent_id: &str, text: &str) {
        let rendered = render_markdown(text, self.content_width);
        let name = format!("{}", short_agent_id(agent_id));
        self.print_markdown(&name, |s| s.custom_color(teal()).dimmed(), &rendered);
    }

    fn format_agent_tool_call(&mut self, agent_id: &str, name: &str, input: &serde_json::Value) {
        let formatted = tool_format::format_tool_call(name, input, self.content_width);
        let label = format!("{}", short_agent_id(agent_id));

        // Print the header with appropriate styling (dimmed for subagents)
        let padded_name = format!("{:>width$}", label, width = NAME_WIDTH);
        let _ = write!(
            self.writer,
            "{}",
            padded_name.custom_color(dim_teal()).dimmed()
        );
        let _ = write!(self.writer, "{}", SEPARATOR.custom_color(separator_color()));

        // Print the header - dimmed for subagents
        let _ = writeln!(self.writer, "{}", formatted.header.dimmed());

        // Print the body if present
        if let Some(body) = formatted.body {
            self.print_continuation(&body);
        }
    }

    fn format_agent_tool_result(&mut self, _agent_id: &str, content: Option<&serde_json::Value>) {
        self.print_lines(
            "  ↳ Tool",
            |s| s.custom_color(dim_teal()).dimmed(),
            "<Result>",
        );
        let content_str = format_tool_content(content);
        self.print_continuation(&content_str);
    }
}

/// Plain text formatter without formatting or alignment
struct PlainFormatter<'a, W: Write + ?Sized> {
    writer: &'a mut W,
}

/// Default content width for plain text output
const PLAIN_CONTENT_WIDTH: usize = 80;

impl<'a, W: Write + ?Sized> OutputFormatter for PlainFormatter<'a, W> {
    fn format_user_text(&mut self, text: &str) {
        let _ = writeln!(self.writer, "You: {}", text);
    }

    fn format_assistant_text(&mut self, text: &str) {
        let _ = writeln!(self.writer, "Claude: {}", text);
    }

    fn format_tool_call(&mut self, name: &str, input: &serde_json::Value) {
        let formatted = tool_format::format_tool_call(name, input, PLAIN_CONTENT_WIDTH);
        let _ = writeln!(self.writer, "Claude: {}", formatted.header);
        if let Some(body) = formatted.body {
            for line in body.lines() {
                let _ = writeln!(self.writer, "  {}", line);
            }
        }
    }

    fn format_tool_result(&mut self, content: Option<&serde_json::Value>) {
        let _ = writeln!(self.writer, "Tool: <Result>");
        let content_str = format_tool_content(content);
        let _ = writeln!(self.writer, "{}", content_str);
    }

    fn format_thinking(&mut self, thought: &str) {
        let _ = writeln!(self.writer, "Thinking: {}", thought);
    }

    fn end_message(&mut self) {
        let _ = writeln!(self.writer);
    }

    fn format_agent_user_text(&mut self, agent_id: &str, text: &str) {
        let _ = writeln!(
            self.writer,
            "  [{}] User: {}",
            short_agent_id(agent_id),
            text
        );
    }

    fn format_agent_assistant_text(&mut self, agent_id: &str, text: &str) {
        let _ = writeln!(
            self.writer,
            "  [{}] Agent: {}",
            short_agent_id(agent_id),
            text
        );
    }

    fn format_agent_tool_call(&mut self, agent_id: &str, name: &str, input: &serde_json::Value) {
        let formatted = tool_format::format_tool_call(name, input, PLAIN_CONTENT_WIDTH);
        let _ = writeln!(
            self.writer,
            "  [{}] Agent: {}",
            short_agent_id(agent_id),
            formatted.header
        );
        if let Some(body) = formatted.body {
            for line in body.lines() {
                let _ = writeln!(self.writer, "    {}", line);
            }
        }
    }

    fn format_agent_tool_result(&mut self, _agent_id: &str, content: Option<&serde_json::Value>) {
        let _ = writeln!(self.writer, "    Tool: <Result>");
        let content_str = format_tool_content(content);
        for line in content_str.lines() {
            let _ = writeln!(self.writer, "    {}", line);
        }
    }
}

/// Format tool result content to a string
fn format_tool_content(content: Option<&serde_json::Value>) -> String {
    match content {
        Some(value) => {
            if let Some(s) = value.as_str() {
                s.to_string()
            } else if let Ok(formatted) = serde_json::to_string_pretty(value) {
                formatted
            } else {
                "<invalid content>".to_string()
            }
        }
        None => "<no content>".to_string(),
    }
}

/// Create a display ID for subagent entries from a parent_tool_use_id.
fn subagent_display_id(parent_tool_use_id: &str) -> String {
    crate::claude::short_parent_id(parent_tool_use_id)
}

/// Process user message text to handle command-related XML tags
/// Returns None if the message should be skipped entirely (e.g., empty local-command-stdout)
fn process_command_message(text: &str) -> Option<String> {
    let trimmed = text.trim();

    // Check for local-command-caveat - skip these system messages entirely
    if trimmed.starts_with("<local-command-caveat>") && trimmed.ends_with("</local-command-caveat>")
    {
        return None;
    }

    // Check for empty or whitespace-only local-command-stdout - skip these entirely
    if trimmed.starts_with("<local-command-stdout>") && trimmed.ends_with("</local-command-stdout>")
    {
        let tag_start = "<local-command-stdout>".len();
        let tag_end = trimmed.len() - "</local-command-stdout>".len();
        let inner = &trimmed[tag_start..tag_end];
        if inner.trim().is_empty() {
            return None;
        }
        // Non-empty local-command-stdout: show the content without the tags
        return Some(inner.trim().to_string());
    }

    // Check if this is a command message with <command-name> tag
    if let Some(start) = trimmed.find("<command-name>")
        && let Some(end) = trimmed.find("</command-name>")
    {
        let content_start = start + "<command-name>".len();
        if content_start < end {
            let command_name = &trimmed[content_start..end];

            // Skip /clear commands - internal context-clearing, not meaningful to display
            if command_name == "/clear" {
                return None;
            }

            // Also extract command args if present
            if let Some(args_start) = trimmed.find("<command-args>")
                && let Some(args_end) = trimmed.find("</command-args>")
            {
                let args_content_start = args_start + "<command-args>".len();
                if args_content_start < args_end {
                    let args = trimmed[args_content_start..args_end].trim();
                    if !args.is_empty() {
                        return Some(format!("{} {}", command_name, args));
                    }
                }
            }

            return Some(command_name.to_string());
        }
    }

    // Skill invocation expanded prompts - show description instead of full prompt
    if trimmed.starts_with("Base directory for this skill:") {
        let description = trimmed
            .lines()
            .skip(1)
            .find(|l| !l.trim().is_empty())
            .unwrap_or("invoked");
        return Some(format!("*Skill: {}*", description));
    }

    // Return original text for non-command messages
    Some(text.to_string())
}

/// Get the terminal width, defaulting to 80 if unavailable
fn get_terminal_width() -> usize {
    terminal::size().map(|(w, _)| w as usize).unwrap_or(80)
}

/// Wrap text using textwrap for proper unicode handling
fn wrap_text(text: &str, max_width: usize) -> Vec<String> {
    if max_width == 0 || text.is_empty() {
        return vec![text.to_string()];
    }
    textwrap::wrap(text, max_width)
        .into_iter()
        .map(|cow| cow.into_owned())
        .collect()
}

/// Display a conversation from a file
pub fn display_conversation(file_path: &Path, options: &DisplayOptions) -> Result<()> {
    let file = File::open(file_path)?;
    let reader = BufReader::new(file);
    let terminal_width = get_terminal_width();
    let content_width = terminal_width.saturating_sub(NAME_WIDTH + SEPARATOR_WIDTH);

    // Spawn pager if requested
    let mut pager_child = if options.use_pager {
        pager::spawn_pager().ok()
    } else {
        None
    };

    // Get writer - either pager stdin or stdout
    let mut stdout_handle = io::stdout().lock();
    let writer: &mut dyn Write = if let Some(ref mut child) = pager_child {
        child.stdin.as_mut().unwrap()
    } else {
        &mut stdout_handle
    };

    let mut formatter = LedgerFormatter::new(writer, content_width);

    for (line_number, line_result) in reader.lines().enumerate() {
        let line = line_result?;
        if line.trim().is_empty() {
            continue;
        }

        match serde_json::from_str::<LogEntry>(&line) {
            Ok(entry) => {
                process_entry(
                    &mut formatter,
                    &entry,
                    options.no_tools,
                    options.show_thinking,
                );
            }
            Err(e) => {
                debug::error(
                    options.debug_level,
                    &format!("Failed to parse line {}: {}", line_number + 1, e),
                );
                if options.debug_level.is_some() {
                    let _ = debug_log::log_display_error(
                        file_path,
                        line_number + 1,
                        &e.to_string(),
                        &line,
                    );
                }
            }
        }
    }

    // Close stdin and wait for pager to finish
    drop(stdout_handle);
    if let Some(mut child) = pager_child {
        let _ = child.wait();
    }

    Ok(())
}

/// Display a conversation in plain text format (no ledger formatting)
pub fn display_conversation_plain(file_path: &Path, options: &DisplayOptions) -> Result<()> {
    let file = File::open(file_path)?;
    let reader = BufReader::new(file);

    // Spawn pager if requested
    let mut pager_child = if options.use_pager {
        pager::spawn_pager().ok()
    } else {
        None
    };

    let mut stdout_handle = io::stdout().lock();
    let writer: &mut dyn Write = if let Some(ref mut child) = pager_child {
        child.stdin.as_mut().unwrap()
    } else {
        &mut stdout_handle
    };

    let mut formatter = PlainFormatter { writer };

    for (line_number, line_result) in reader.lines().enumerate() {
        let line = line_result?;
        if line.trim().is_empty() {
            continue;
        }

        match serde_json::from_str::<LogEntry>(&line) {
            Ok(entry) => {
                process_entry(
                    &mut formatter,
                    &entry,
                    options.no_tools,
                    options.show_thinking,
                );
            }
            Err(e) => {
                debug::error(
                    options.debug_level,
                    &format!("Failed to parse line {}: {}", line_number + 1, e),
                );
                if options.debug_level.is_some() {
                    let _ = debug_log::log_display_error(
                        file_path,
                        line_number + 1,
                        &e.to_string(),
                        &line,
                    );
                }
            }
        }
    }

    // Close stdin and wait for pager to finish
    drop(stdout_handle);
    if let Some(mut child) = pager_child {
        let _ = child.wait();
    }

    Ok(())
}

/// Process a log entry using the provided formatter
fn process_entry<F: OutputFormatter>(
    formatter: &mut F,
    entry: &LogEntry,
    no_tools: bool,
    show_thinking: bool,
) {
    match entry {
        LogEntry::Summary { .. }
        | LogEntry::FileHistorySnapshot { .. }
        | LogEntry::System { .. }
        | LogEntry::CustomTitle { .. } => {
            // Skip metadata entries
        }
        LogEntry::Progress { data, .. } => {
            // Handle agent_progress entries (only when show_thinking is enabled)
            if show_thinking && let Some(agent_progress) = crate::claude::parse_agent_progress(data)
            {
                process_agent_message(formatter, &agent_progress, no_tools);
            }
        }
        LogEntry::User {
            message,
            parent_tool_use_id,
            ..
        } => {
            if parent_tool_use_id.is_some() && !show_thinking {
                return;
            }
            process_user_message(formatter, message, no_tools, parent_tool_use_id.as_deref());
        }
        LogEntry::Assistant {
            message,
            parent_tool_use_id,
            ..
        } => {
            if parent_tool_use_id.is_some() && !show_thinking {
                return;
            }
            process_assistant_message(
                formatter,
                message,
                no_tools,
                show_thinking,
                parent_tool_use_id.as_deref(),
            );
        }
    }
}

/// Process a user message using the provided formatter
fn process_user_message<F: OutputFormatter>(
    formatter: &mut F,
    message: &crate::claude::UserMessage,
    no_tools: bool,
    parent_id: Option<&str>,
) {
    let agent_id = parent_id.map(subagent_display_id);

    match &message.content {
        UserContent::String(text) => {
            if let Some(processed) = process_command_message(text) {
                if let Some(ref id) = agent_id {
                    formatter.format_agent_user_text(id, &processed);
                } else {
                    formatter.format_user_text(&processed);
                }
                formatter.end_message();
            }
        }
        UserContent::Blocks(blocks) => {
            let mut printed_content = false;
            for block in blocks {
                match block {
                    ContentBlock::Text { text } => {
                        if let Some(processed) = process_command_message(text) {
                            if let Some(ref id) = agent_id {
                                formatter.format_agent_user_text(id, &processed);
                            } else {
                                formatter.format_user_text(&processed);
                            }
                            printed_content = true;
                        }
                    }
                    ContentBlock::ToolResult { content, .. } => {
                        if !no_tools {
                            if let Some(ref id) = agent_id {
                                formatter.format_agent_tool_result(id, content.as_ref());
                            } else {
                                formatter.format_tool_result(content.as_ref());
                            }
                            printed_content = true;
                        }
                    }
                    _ => {}
                }
            }
            if printed_content {
                formatter.end_message();
            }
        }
    }
}

/// Helper struct to categorize assistant message content
struct FormattedMessage<'a> {
    text_blocks: Vec<&'a str>,
    tool_calls: Vec<(&'a str, &'a serde_json::Value)>,
    thinking_steps: Vec<&'a str>,
}

impl<'a> From<&'a AssistantMessage> for FormattedMessage<'a> {
    fn from(msg: &'a AssistantMessage) -> Self {
        let mut text_blocks = Vec::new();
        let mut tool_calls = Vec::new();
        let mut thinking_steps = Vec::new();

        for block in &msg.content {
            match block {
                ContentBlock::Text { text } => text_blocks.push(text.as_str()),
                ContentBlock::ToolUse { name, input, .. } => {
                    tool_calls.push((name.as_str(), input))
                }
                ContentBlock::Thinking { thinking, .. } => thinking_steps.push(thinking.as_str()),
                _ => {}
            }
        }

        Self {
            text_blocks,
            tool_calls,
            thinking_steps,
        }
    }
}

/// Process an assistant message using the provided formatter
fn process_assistant_message<F: OutputFormatter>(
    formatter: &mut F,
    message: &AssistantMessage,
    no_tools: bool,
    show_thinking: bool,
    parent_id: Option<&str>,
) {
    let formatted = FormattedMessage::from(message);
    let mut printed_content = false;
    let agent_id = parent_id.map(subagent_display_id);

    // Print text blocks
    for text in formatted.text_blocks {
        if text.trim().is_empty() {
            continue;
        }
        if let Some(ref id) = agent_id {
            formatter.format_agent_assistant_text(id, text);
        } else {
            formatter.format_assistant_text(text);
        }
        printed_content = true;
    }

    // Print tool calls
    if !no_tools {
        for (tool_name, tool_input) in formatted.tool_calls {
            if let Some(ref id) = agent_id {
                formatter.format_agent_tool_call(id, tool_name, tool_input);
            } else {
                formatter.format_tool_call(tool_name, tool_input);
            }
            printed_content = true;
        }
    }

    // Print thinking blocks (skip for subagents)
    if show_thinking && agent_id.is_none() {
        for thought in formatted.thinking_steps {
            if thought.is_empty() {
                continue;
            }
            formatter.format_thinking(thought);
            printed_content = true;
        }
    }

    // Only add spacing if we printed something
    if printed_content {
        formatter.end_message();
    }
}

/// Get a truncated agent ID for display (max 7 characters)
fn short_agent_id(agent_id: &str) -> &str {
    &agent_id[..agent_id.len().min(7)]
}

/// Process an agent progress message using the provided formatter
fn process_agent_message<F: OutputFormatter>(
    formatter: &mut F,
    agent_progress: &crate::claude::AgentProgressData,
    no_tools: bool,
) {
    use crate::claude::{AgentContent, ContentBlock};

    let agent_id = &agent_progress.agent_id;
    let msg = &agent_progress.message;

    match msg.message_type.as_str() {
        "user" => {
            // User messages in agent context are typically tool results or the initial prompt
            let AgentContent::Blocks(blocks) = &msg.message.content;
            let mut printed = false;

            // Aggregate text blocks and render together
            let texts: Vec<&str> = blocks
                .iter()
                .filter_map(|b| {
                    if let ContentBlock::Text { text } = b {
                        Some(text.as_str())
                    } else {
                        None
                    }
                })
                .collect();

            if !texts.is_empty() {
                let combined = texts.join("\n\n");
                formatter.format_agent_user_text(agent_id, &combined);
                printed = true;
            }

            // Tool results
            for block in blocks {
                if let ContentBlock::ToolResult { content, .. } = block
                    && !no_tools
                {
                    formatter.format_agent_tool_result(agent_id, content.as_ref());
                    printed = true;
                }
            }

            if printed {
                formatter.end_message();
            }
        }
        "assistant" => {
            let AgentContent::Blocks(blocks) = &msg.message.content;
            let mut printed = false;

            // Aggregate text blocks and render together
            let texts: Vec<&str> = blocks
                .iter()
                .filter_map(|b| {
                    if let ContentBlock::Text { text } = b {
                        Some(text.as_str())
                    } else {
                        None
                    }
                })
                .collect();

            if !texts.is_empty() {
                let combined = texts.join("\n\n");
                formatter.format_agent_assistant_text(agent_id, &combined);
                printed = true;
            }

            // Tool calls
            for block in blocks {
                if let ContentBlock::ToolUse { name, input, .. } = block
                    && !no_tools
                {
                    formatter.format_agent_tool_call(agent_id, name, input);
                    printed = true;
                }
            }

            if printed {
                formatter.end_message();
            }
        }
        _ => {}
    }
}

/// Render a conversation in TUI ledger format to terminal (for debugging)
pub fn render_to_terminal(file_path: &Path, options: &DisplayOptions) -> Result<()> {
    use crate::tui::{RenderOptions, render_conversation};

    let terminal_width = get_terminal_width();
    let content_width = terminal_width.saturating_sub(NAME_WIDTH + SEPARATOR_WIDTH);

    let render_options = RenderOptions {
        tool_display: if options.no_tools {
            crate::tui::ToolDisplayMode::Hidden
        } else {
            crate::tui::ToolDisplayMode::Full
        },
        show_thinking: options.show_thinking,
        show_timing: false, // Non-TUI render doesn't support timing toggle
        content_width,
    };

    let rendered = render_conversation(file_path, &render_options)?;
    let rendered_lines = rendered.lines;

    // Spawn pager if requested
    let mut pager_child = if options.use_pager {
        pager::spawn_pager().ok()
    } else {
        None
    };

    // Get writer - either pager stdin or stdout
    let mut stdout_handle = io::stdout().lock();
    let writer: &mut dyn Write = if let Some(ref mut child) = pager_child {
        child.stdin.as_mut().unwrap()
    } else {
        &mut stdout_handle
    };

    // Convert RenderedLine spans to colored terminal output
    'outer: for line in &rendered_lines {
        for (text, style) in &line.spans {
            // Apply styling only if colors are enabled
            let output: Box<dyn std::fmt::Display> = if options.no_color {
                Box::new(text.as_str())
            } else {
                let mut styled = text.as_str().normal();

                if let Some((r, g, b)) = style.fg {
                    styled = styled.custom_color(CustomColor { r, g, b });
                }
                if style.bold {
                    styled = styled.bold();
                }
                if style.dimmed {
                    styled = styled.dimmed();
                }
                if style.italic {
                    styled = styled.italic();
                }

                Box::new(styled)
            };

            // Stop if the output pipe is closed (e.g., pager quit)
            if write!(writer, "{}", output).is_err() {
                break 'outer;
            }
        }
        if writeln!(writer).is_err() {
            break;
        }
    }

    // Close stdin and wait for pager to finish
    drop(stdout_handle);
    if let Some(mut child) = pager_child {
        let _ = child.wait();
    }

    Ok(())
}

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

    #[test]
    fn process_command_message_skips_local_command_caveat() {
        let caveat = "<local-command-caveat>Caveat: The messages below were generated by the user while running local commands. DO NOT respond to these messages or otherwise consider them in your response unless the user explicitly asks you to.</local-command-caveat>";
        assert_eq!(process_command_message(caveat), None);
    }

    #[test]
    fn process_command_message_skips_local_command_caveat_with_whitespace() {
        let caveat = "  <local-command-caveat>Some caveat text</local-command-caveat>  ";
        assert_eq!(process_command_message(caveat), None);
    }

    #[test]
    fn process_command_message_preserves_normal_text() {
        assert_eq!(
            process_command_message("Hello world"),
            Some("Hello world".to_string())
        );
    }

    #[test]
    fn process_command_message_skips_empty_stdout() {
        assert_eq!(
            process_command_message("<local-command-stdout></local-command-stdout>"),
            None
        );
        assert_eq!(
            process_command_message("<local-command-stdout>   </local-command-stdout>"),
            None
        );
    }

    #[test]
    fn process_command_message_extracts_nonempty_stdout() {
        assert_eq!(
            process_command_message("<local-command-stdout>output here</local-command-stdout>"),
            Some("output here".to_string())
        );
    }

    #[test]
    fn process_command_message_skips_clear_command() {
        assert_eq!(
            process_command_message("<command-name>/clear</command-name>"),
            None
        );
        // Also skip clear with command-message and command-args tags
        assert_eq!(
            process_command_message(
                "<command-name>/clear</command-name>\n<command-message>clear</command-message>\n<command-args></command-args>"
            ),
            None
        );
    }

    #[test]
    fn process_command_message_extracts_other_command_names() {
        assert_eq!(
            process_command_message("<command-name>/help</command-name>"),
            Some("/help".to_string())
        );
    }

    #[test]
    fn process_command_message_condenses_skill_invocation() {
        let skill_msg = "Base directory for this skill: /Users/raine/.claude/skills/consult\n\nConsult an external LLM with the user's query.\n\n**Arguments:** `how to add more aliases?`";
        assert_eq!(
            process_command_message(skill_msg),
            Some("*Skill: Consult an external LLM with the user's query.*".to_string())
        );
    }

    #[test]
    fn process_command_message_skill_invocation_fallback() {
        let skill_msg = "Base directory for this skill: /path/to/skill";
        assert_eq!(
            process_command_message(skill_msg),
            Some("*Skill: invoked*".to_string())
        );
    }
}