travelagent 1.11.1

Agent-first TUI code review tool
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
use ratatui::{
    Frame,
    layout::{Constraint, Flex, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, Paragraph},
};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};

use crate::app::App;
use crate::theme::Theme;
use crate::ui::styles;
use travelagent_core::model::LineRange;

/// Maximum display width (in columns) for wrapped comment body content.
///
/// The annotation bottom border is `"     ╰"` (6 display cols) followed by
/// `"─".repeat(38)` (38 display cols) for a total box width of 44 columns.
/// The content prefix `"     │ "` occupies the first 7 columns, leaving
/// `44 - 7 = 37` columns for body text before it overflows the box.
pub(crate) const CONTENT_WIDTH: usize = 37;

/// Wrap a single logical line (no embedded `\n`) to `width` display columns,
/// respecting char boundaries and unicode display widths. If `width` is 0 or
/// the input already fits, returns a single-element Vec with the original.
///
/// This is a greedy word-wrap: it breaks on whitespace when possible, and falls
/// back to mid-token breaks on character boundaries when a single token exceeds
/// the width (so wide CJK or long URLs don't overflow).
pub(crate) fn wrap_line_to_width(text: &str, width: usize) -> Vec<String> {
    if width == 0 || text.width() <= width {
        return vec![text.to_string()];
    }

    let mut lines: Vec<String> = Vec::new();
    let mut current = String::new();
    let mut current_w: usize = 0;
    // Index (in bytes) of the last whitespace char added to `current`, if any.
    let mut last_ws_byte: Option<usize> = None;

    for ch in text.chars() {
        let ch_w = ch.width().unwrap_or(0);
        // If adding this char would overflow, flush the current line.
        if current_w + ch_w > width && !current.is_empty() {
            if let Some(ws_idx) = last_ws_byte {
                // Break at last whitespace: content before ws goes out, after ws is carry.
                // If the whitespace char can't be decoded (shouldn't happen since we
                // only record valid char boundaries), fall back to a hard break.
                if let Some(ws_char) = current[ws_idx..].chars().next() {
                    let carry: String = current[ws_idx + ws_char.len_utf8()..].to_string();
                    let head: String = current[..ws_idx].to_string();
                    lines.push(head);
                    current = carry;
                    current_w = current.width();
                    last_ws_byte = None;
                } else {
                    lines.push(std::mem::take(&mut current));
                    current_w = 0;
                    last_ws_byte = None;
                }
            } else {
                // No whitespace to break on: hard-break at char boundary.
                lines.push(std::mem::take(&mut current));
                current_w = 0;
            }
        }
        if ch.is_whitespace() {
            last_ws_byte = Some(current.len());
        }
        current.push(ch);
        current_w += ch_w;
    }
    lines.push(current);
    if lines.is_empty() {
        lines.push(String::new());
    }
    lines
}

/// Information about where the cursor should be positioned within comment input
#[derive(Debug, Clone)]
pub struct CommentCursorInfo {
    /// Which line within the formatted output contains the cursor (0-indexed).
    /// This is the line index within the `Vec<Line>` returned by
    /// `format_comment_input_lines`. The output has this shape:
    ///
    ///   0       = top border with `Add [TYPE] Ln` header
    ///   1..=N-3 = content lines (cursor lives here)
    ///   N-2     = bottom border (`╰───…`)
    ///   N-1     = key-hint footer line (dim text, not part of the box)
    pub line_offset: usize,
    /// Column offset (display width) from start of line where cursor should be
    pub column: u16,
}

#[derive(Debug, Clone)]
pub struct CommentTypePresentation {
    pub label: String,
    pub color: Color,
}

/// Format a comment input as multiple lines with a box border for inline editing.
/// This mimics the normal comment display but shows it's being edited.
///
/// Returns a tuple of (lines, cursor_info) where cursor_info contains the position
/// of the cursor within the formatted output for IME positioning.
pub fn format_comment_input_lines(
    theme: &Theme,
    comment_type: CommentTypePresentation,
    buffer: &str,
    cursor_pos: usize,
    line_range: Option<LineRange>,
    is_editing: bool,
    supports_keyboard_enhancement: bool,
) -> (Vec<Line<'static>>, CommentCursorInfo) {
    let type_style = styles::comment_type_style(theme, comment_type.color);
    let border_style = styles::comment_border_style(theme, comment_type.color);
    let cursor_style = Style::default()
        .fg(theme.cursor_color)
        .add_modifier(Modifier::UNDERLINED);

    let action = if is_editing { "Edit" } else { "Add" };
    let line_info = match line_range {
        Some(range) if range.is_single() => format!("L{} ", range.start),
        Some(range) => format!("L{}-L{} ", range.start, range.end),
        None => String::new(),
    };

    let newline_hint = if supports_keyboard_enhancement {
        "Shift-Enter"
    } else {
        "Ctrl-J"
    };

    let mut result = Vec::new();
    // Track cursor position: line offset within result, column (display width)
    // Default to first content line (index 1) with cursor at start of content (after border)
    let border_prefix = "";
    let border_width = border_prefix.width() as u16;
    let mut cursor_line_offset: usize = 1; // First content line (after header)
    let mut cursor_column: u16 = border_width; // After the border prefix

    // Top border with type label. The key-hints moved to a footer row
    // below the bottom border so the box header stays legible and the
    // hint line reads as a grouped cheat-sheet rather than noise next
    // to the comment kind.
    result.push(Line::from(vec![
        Span::styled("     ╭─ ", border_style),
        Span::styled(format!("{action} "), styles::dim_style(theme)),
        Span::styled(format!("[{}] ", comment_type.label), type_style),
        Span::styled(line_info, styles::dim_style(theme)),
    ]));

    // Content lines with cursor
    if buffer.is_empty() {
        // Show placeholder with cursor at start
        result.push(Line::from(vec![
            Span::styled(border_prefix, border_style),
            Span::styled(" ", cursor_style),
            Span::styled("Type your comment...", styles::dim_style(theme)),
        ]));
        // cursor_line_offset is already 1 (first content line)
        // cursor_column is already border_width (cursor at start of content)
    } else {
        // Split buffer into lines and render with cursor.
        // Each logical line is further wrapped to CONTENT_WIDTH so long text
        // doesn't overflow the annotation box horizontally.
        let buffer_lines: Vec<&str> = buffer.split('\n').collect();
        let mut char_offset = 0;
        // Running count of wrapped sub-lines emitted so far (used to compute
        // the cursor's line_offset relative to the start of the block).
        let mut emitted_content_lines: usize = 0;

        for (line_idx, text) in buffer_lines.iter().enumerate() {
            let line_start = char_offset;
            let line_end = char_offset + text.len();

            // Check if cursor is on this logical line.
            let cursor_on_this_line = cursor_pos >= line_start
                && (cursor_pos <= line_end
                    || (line_idx == buffer_lines.len() - 1 && cursor_pos == buffer.len()));

            let wrapped = wrap_line_to_width(text, CONTENT_WIDTH);

            if cursor_on_this_line {
                // Locate which wrapped sub-line the cursor falls on by walking
                // wrapped segments and consuming bytes of the original `text`.
                let cursor_byte_in_line = (cursor_pos - line_start).min(text.len());
                // Walk sub-lines; for each, advance through `text` until the
                // sub-line's chars are matched, then skip any whitespace that
                // was dropped at the wrap boundary. Because
                // `wrap_line_to_width` drops at most one whitespace char at each
                // wrap boundary, we can map sub-line byte offsets back to
                // offsets in the original logical line.
                let mut consumed_bytes: usize = 0;
                for (sub_idx, sub) in wrapped.iter().enumerate() {
                    let sub_byte_len = sub.len();
                    let sub_end_in_text = consumed_bytes + sub_byte_len;

                    // Is the cursor within this sub-line (or at its end)?
                    let is_last_sub = sub_idx == wrapped.len() - 1;
                    let cursor_in_sub = cursor_byte_in_line >= consumed_bytes
                        && (cursor_byte_in_line <= sub_end_in_text || is_last_sub);

                    // Emit this sub-line's spans.
                    let mut line_spans = vec![Span::styled(border_prefix, border_style)];
                    if cursor_in_sub {
                        let cursor_in_sub_byte = cursor_byte_in_line
                            .saturating_sub(consumed_bytes)
                            .min(sub.len());
                        let (before_cursor, after_cursor) = sub.split_at(cursor_in_sub_byte);

                        cursor_line_offset = 1 + emitted_content_lines + sub_idx;
                        cursor_column = border_width + before_cursor.width() as u16;

                        if after_cursor.is_empty() {
                            line_spans.push(Span::raw(before_cursor.to_string()));
                            line_spans.push(Span::styled(" ", cursor_style));
                        } else {
                            let mut chars = after_cursor.chars();
                            let cursor_char = chars.next().unwrap();
                            let remaining = chars.as_str();
                            line_spans.push(Span::raw(before_cursor.to_string()));
                            line_spans.push(Span::styled(cursor_char.to_string(), cursor_style));
                            line_spans.push(Span::raw(remaining.to_string()));
                        }
                    } else {
                        line_spans.push(Span::raw(sub.clone()));
                    }
                    result.push(Line::from(line_spans));

                    consumed_bytes = sub_end_in_text;
                    // Skip one dropped whitespace char, if any (wrap_line_to_width
                    // drops at most one whitespace at each wrap boundary). If the
                    // slice doesn't start on a char boundary (shouldn't happen —
                    // sub-line lengths are exact char-boundary splits), leave it
                    // alone rather than panicking.
                    if !is_last_sub
                        && consumed_bytes < text.len()
                        && let Some(next_char) = text[consumed_bytes..].chars().next()
                        && next_char.is_whitespace()
                    {
                        consumed_bytes += next_char.len_utf8();
                    }
                }
            } else {
                for sub in &wrapped {
                    result.push(Line::from(vec![
                        Span::styled(border_prefix, border_style),
                        Span::raw(sub.clone()),
                    ]));
                }
            }

            emitted_content_lines += wrapped.len();

            // Account for newline character (except for last line)
            char_offset = line_end + 1;
        }
    }

    // Bottom border
    result.push(Line::from(vec![Span::styled(
        "".to_string() + &"".repeat(38),
        border_style,
    )]));

    // Key-hint footer row — rendered below the border as a cheat-sheet
    // cue so the top header stays terse. Indented to align with the box
    // body, dim style so it doesn't steal the reader's attention from
    // the comment content.
    result.push(Line::from(vec![Span::styled(
        format!("       (Tab/S-Tab:type  Enter:save  {newline_hint}:newline  Esc:cancel)"),
        styles::dim_style(theme),
    )]));

    let cursor_info = CommentCursorInfo {
        line_offset: cursor_line_offset,
        column: cursor_column,
    };

    (result, cursor_info)
}

/// Format a comment as multiple lines with a box border (themed version)
pub fn format_comment_lines(
    theme: &Theme,
    comment_type: CommentTypePresentation,
    content: &str,
    line_range: Option<LineRange>,
) -> Vec<Line<'static>> {
    let type_style = styles::comment_type_style(theme, comment_type.color);
    let border_style = styles::comment_border_style(theme, comment_type.color);

    let line_info = match line_range {
        Some(range) if range.is_single() => format!("L{} ", range.start),
        Some(range) => format!("L{}-L{} ", range.start, range.end),
        None => String::new(),
    };
    let content_lines: Vec<&str> = content.split('\n').collect();

    let mut result = Vec::new();

    // Top border with type label
    result.push(Line::from(vec![
        Span::styled("     ╭─ ", border_style),
        Span::styled(format!("[{}] ", comment_type.label), type_style),
        Span::styled(line_info, styles::dim_style(theme)),
        Span::styled("".repeat(30), border_style),
    ]));

    // Content lines (wrapped to CONTENT_WIDTH so long lines don't overflow the box)
    for line in &content_lines {
        for wrapped in wrap_line_to_width(line, CONTENT_WIDTH) {
            result.push(Line::from(vec![
                Span::styled("", border_style),
                Span::raw(wrapped),
            ]));
        }
    }

    // Bottom border
    result.push(Line::from(vec![Span::styled(
        "".to_string() + &"".repeat(38),
        border_style,
    )]));

    result
}

pub fn render_confirm_dialog(frame: &mut Frame, app: &App, message: &str) {
    let theme = &app.theme;
    let area = centered_rect(50, 20, frame.area());

    frame.render_widget(Clear, area);

    let block = Block::default()
        .title(" Confirm ")
        .borders(Borders::ALL)
        .style(styles::popup_style(theme))
        .border_style(styles::border_style(theme, true));

    let inner = block.inner(area);
    frame.render_widget(block, area);

    let lines = vec![
        Line::from(""),
        Line::from(Span::raw(message)),
        Line::from(""),
        Line::from(vec![
            Span::styled("  [Y]", Style::default().add_modifier(Modifier::BOLD)),
            Span::raw("es    "),
            Span::styled("[N]", Style::default().add_modifier(Modifier::BOLD)),
            Span::raw("o"),
        ]),
    ];

    let paragraph = Paragraph::new(lines)
        .style(styles::popup_style(theme))
        .alignment(ratatui::layout::Alignment::Center);
    frame.render_widget(paragraph, inner);
}

pub fn render_review_submit_dialog(frame: &mut Frame, app: &App) {
    let theme = &app.theme;
    let area = centered_rect(50, 50, frame.area());

    frame.render_widget(Clear, area);

    let block = Block::default()
        .title(" Submit Review ")
        .borders(Borders::ALL)
        .style(styles::popup_style(theme))
        .border_style(styles::border_style(theme, true));

    let inner = block.inner(area);
    frame.render_widget(block, area);

    let verdicts: Vec<&str> = if app.supports_request_changes() {
        vec!["Comment", "Approve", "Request Changes"]
    } else {
        vec!["Comment", "Approve"]
    };
    let mut lines = vec![Line::from("")];

    // Fall back to sensible defaults in local mode so the popup doesn't
    // render nonsense if it ever renders outside remote mode.
    let (verdict_cursor, review_body, review_body_editing) = app
        .remote()
        .map(|r| {
            (
                r.review_verdict_cursor,
                r.review_body.clone(),
                r.review_body_editing,
            )
        })
        .unwrap_or((0, String::new(), false));

    for (i, verdict) in verdicts.iter().enumerate() {
        let marker = if i == verdict_cursor { "> " } else { "  " };
        let style = if i == verdict_cursor {
            Style::default().add_modifier(Modifier::BOLD)
        } else {
            Style::default()
        };
        lines.push(Line::from(Span::styled(
            format!("{marker}{verdict}"),
            style,
        )));
    }

    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "  Body (optional):",
        styles::dim_style(theme),
    )));

    let body_display = if review_body.is_empty() && !review_body_editing {
        "  (press Enter to edit)".to_string()
    } else if review_body.is_empty() {
        "  _".to_string()
    } else {
        format!("  {review_body}")
    };
    let body_style = if review_body_editing {
        Style::default()
    } else {
        styles::dim_style(theme)
    };
    lines.push(Line::from(Span::styled(body_display, body_style)));

    lines.push(Line::from(""));
    lines.push(Line::from(vec![
        Span::styled("  Ctrl+S", Style::default().add_modifier(Modifier::BOLD)),
        Span::raw(": Submit  "),
        Span::styled("Esc", Style::default().add_modifier(Modifier::BOLD)),
        Span::raw(": Cancel"),
    ]));

    let paragraph = Paragraph::new(lines).style(styles::popup_style(theme));
    frame.render_widget(paragraph, inner);
}

/// Render the agent-forge-write confirmation modal (Phase E).
///
/// Drawn on top of whatever InputMode the human was in so they can see the
/// underlying review state while deciding. Content is deliberately minimal:
/// what the agent wants to do, highlighted verdict, first few lines of body,
/// countdown to auto-timeout, and the keybinding reminder.
pub fn render_forge_confirmation_modal(frame: &mut Frame, app: &App) {
    use crate::app::{AgentActionKind, PendingAgentAction};
    use travelagent_core::forge::ReviewVerdict;

    let Some(PendingAgentAction {
        kind, proposed_at, ..
    }) = app.agent_action.pending()
    else {
        return;
    };

    let theme = &app.theme;
    let area = centered_rect(60, 50, frame.area());
    frame.render_widget(Clear, area);

    let title = match kind {
        AgentActionKind::SubmitReview { .. } => " Agent Forge Proposal ",
        AgentActionKind::SetMentalModel { .. } => " Agent Mental Model Proposal ",
        AgentActionKind::AcceptGeneratedTest { .. } => " Agent Generated Test Proposal ",
    };
    let block = Block::default()
        .title(title)
        .borders(Borders::ALL)
        .style(styles::popup_style(theme))
        .border_style(styles::border_style(theme, true));
    let inner = block.inner(area);
    frame.render_widget(block, area);

    // Dispatch to the submit-review body below; the non-forge variants
    // each build their own list of lines, render, and return early.
    if let AgentActionKind::SetMentalModel { mental_model } = kind {
        render_mental_model_proposal_body(frame, inner, app, mental_model, *proposed_at);
        return;
    }
    if let AgentActionKind::AcceptGeneratedTest {
        test_path,
        test_body,
        spec_id,
    } = kind
    {
        render_accept_generated_test_body(
            frame,
            inner,
            app,
            test_path,
            test_body,
            spec_id,
            *proposed_at,
        );
        return;
    }
    let AgentActionKind::SubmitReview { verdict, body } = kind else {
        unreachable!(
            "SetMentalModel and AcceptGeneratedTest handled above; SubmitReview is the only \
             remaining variant",
        );
    };

    let verdict_label = match verdict {
        ReviewVerdict::Approve => "APPROVE",
        ReviewVerdict::RequestChanges => "REQUEST CHANGES",
        ReviewVerdict::Comment => "COMMENT",
    };
    let verdict_style = Style::default()
        .fg(match verdict {
            ReviewVerdict::Approve => Color::Green,
            ReviewVerdict::RequestChanges => Color::Red,
            ReviewVerdict::Comment => Color::Yellow,
        })
        .add_modifier(Modifier::BOLD);

    let host = app.forge_host_label();
    let pr_id_desc = app
        .remote()
        .map(|r| format!("{}/{} #{}", r.pr_id.owner, r.pr_id.repo, r.pr_id.number))
        .unwrap_or_else(|| "remote".to_string());

    // Count all pending comments across the session so the human can tell
    // at a glance whether the forge submit will upload anything beyond the
    // review verdict body.
    let comment_count: usize = app.engine.session().review_comments.len()
        + app
            .engine
            .session()
            .files
            .values()
            .map(travelagent_core::model::review::FileReview::comment_count)
            .sum::<usize>();

    // Countdown (seconds) to auto-timeout. Clamp at 0 so we never underflow
    // during the brief window between the last tick and the transition.
    let elapsed = chrono::Utc::now().signed_duration_since(*proposed_at);
    let timeout_secs = crate::app::CONFIRMATION_TIMEOUT.as_secs() as i64;
    let remaining_secs = (timeout_secs - elapsed.num_seconds()).max(0);
    let countdown = format!(
        "expires in {:01}:{:02}",
        remaining_secs / 60,
        remaining_secs % 60,
    );

    // Body preview: first 3 logical lines, trimmed to avoid overflowing the
    // modal width. Empty body yields a dim placeholder.
    let trimmed = body.trim_end();
    let body_preview_lines: Vec<&str> = if trimmed.is_empty() {
        Vec::new()
    } else {
        trimmed.lines().take(3).collect()
    };
    let has_more_lines = trimmed.lines().count() > body_preview_lines.len();

    let mut lines: Vec<Line> = Vec::new();
    lines.push(Line::from(""));
    lines.push(Line::from(vec![
        Span::styled("  Agent proposed: ", styles::dim_style(theme)),
        Span::styled(
            format!("submit review to {host} {pr_id_desc}"),
            Style::default().add_modifier(Modifier::BOLD),
        ),
    ]));
    lines.push(Line::from(""));
    lines.push(Line::from(vec![
        Span::styled("  Verdict: ", styles::dim_style(theme)),
        Span::styled(verdict_label.to_string(), verdict_style),
    ]));
    lines.push(Line::from(vec![
        Span::styled("  Pending comments: ", styles::dim_style(theme)),
        Span::styled(
            format!("{comment_count}"),
            Style::default().add_modifier(Modifier::BOLD),
        ),
    ]));
    lines.push(Line::from(""));
    if body_preview_lines.is_empty() {
        lines.push(Line::from(Span::styled(
            "  (no body)".to_string(),
            styles::dim_style(theme),
        )));
    } else {
        lines.push(Line::from(Span::styled(
            "  Body preview:".to_string(),
            styles::dim_style(theme),
        )));
        for raw_line in body_preview_lines {
            // Hard-truncate each preview line so a single extreme line can't
            // push content out of the modal.
            let display: String = raw_line.chars().take(70).collect();
            lines.push(Line::from(format!("    {display}")));
        }
        if has_more_lines {
            lines.push(Line::from(Span::styled(
                "    ...".to_string(),
                styles::dim_style(theme),
            )));
        }
    }
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        format!("  {countdown}"),
        styles::dim_style(theme),
    )));
    lines.push(Line::from(""));
    lines.push(Line::from(vec![
        Span::styled("  [y]", Style::default().add_modifier(Modifier::BOLD)),
        Span::raw("es  "),
        Span::styled("[n]", Style::default().add_modifier(Modifier::BOLD)),
        Span::raw("o  "),
        Span::styled("[Esc]", Style::default().add_modifier(Modifier::BOLD)),
    ]));

    let paragraph = Paragraph::new(lines).style(styles::popup_style(theme));
    frame.render_widget(paragraph, inner);
}

/// Body renderer for the `SetMentalModel` confirmation variant. Same
/// [y]/[n]/[Esc] keybinds and same timeout countdown as the submit-
/// review variant; the content shows a preview of what the agent wants
/// to write plus whether it would overwrite an existing mental model.
fn render_mental_model_proposal_body(
    frame: &mut Frame,
    inner: Rect,
    app: &App,
    mental_model: &travelagent_core::model::MentalModel,
    proposed_at: chrono::DateTime<chrono::Utc>,
) {
    let theme = &app.theme;

    let has_existing = app.engine.session().mental_model.is_some();
    let overwrite_label = if has_existing {
        "overwrite existing"
    } else {
        "new capture"
    };

    let elapsed = chrono::Utc::now().signed_duration_since(proposed_at);
    let timeout_secs = crate::app::CONFIRMATION_TIMEOUT.as_secs() as i64;
    let remaining_secs = (timeout_secs - elapsed.num_seconds()).max(0);
    let countdown = format!(
        "expires in {:01}:{:02}",
        remaining_secs / 60,
        remaining_secs % 60,
    );

    fn preview(body: &str) -> String {
        let first_line = body.lines().next().unwrap_or("");
        let truncated: String = first_line.chars().take(68).collect();
        if truncated.is_empty() {
            "(empty)".to_string()
        } else if body.lines().count() > 1 || first_line.chars().count() > 68 {
            format!("{truncated}")
        } else {
            truncated
        }
    }

    let mut lines: Vec<Line> = Vec::new();
    lines.push(Line::from(""));
    lines.push(Line::from(vec![
        Span::styled("  Agent proposed: ", styles::dim_style(theme)),
        Span::styled(
            format!("set mental model ({overwrite_label})"),
            Style::default().add_modifier(Modifier::BOLD),
        ),
    ]));
    lines.push(Line::from(""));
    let labels = [
        ("Should do:", &mental_model.should_do),
        ("Shouldn't do:", &mental_model.shouldnt_do),
        ("Could go wrong:", &mental_model.could_go_wrong),
        ("Assumptions:", &mental_model.assumptions),
    ];
    for (label, body) in labels {
        lines.push(Line::from(vec![
            Span::styled(
                format!("  {label:<16}"),
                Style::default().add_modifier(Modifier::BOLD),
            ),
            Span::raw(preview(body)),
        ]));
    }
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        format!("  {countdown}"),
        styles::dim_style(theme),
    )));
    lines.push(Line::from(""));
    lines.push(Line::from(vec![
        Span::styled("  [y]", Style::default().add_modifier(Modifier::BOLD)),
        Span::raw("es  "),
        Span::styled("[n]", Style::default().add_modifier(Modifier::BOLD)),
        Span::raw("o  "),
        Span::styled("[Esc]", Style::default().add_modifier(Modifier::BOLD)),
    ]));

    let paragraph = Paragraph::new(lines).style(styles::popup_style(theme));
    frame.render_widget(paragraph, inner);
}

/// Body renderer for the `AcceptGeneratedTest` confirmation variant
/// (Phase I4c-2). Shows the target path, the spec id being addressed,
/// and a preview of the first several lines of the generated test body
/// so the human can sanity-check before approving the file write.
fn render_accept_generated_test_body(
    frame: &mut Frame,
    inner: Rect,
    app: &App,
    test_path: &str,
    test_body: &str,
    spec_id: &str,
    proposed_at: chrono::DateTime<chrono::Utc>,
) {
    let theme = &app.theme;

    let elapsed = chrono::Utc::now().signed_duration_since(proposed_at);
    let timeout_secs = crate::app::CONFIRMATION_TIMEOUT.as_secs() as i64;
    let remaining_secs = (timeout_secs - elapsed.num_seconds()).max(0);
    let countdown = format!(
        "expires in {:01}:{:02}",
        remaining_secs / 60,
        remaining_secs % 60,
    );

    let body_bytes = test_body.len();
    let body_line_count = test_body.lines().count();
    let preview_lines: Vec<&str> = test_body.lines().take(6).collect();
    let has_more = body_line_count > preview_lines.len();

    let mut lines: Vec<Line> = Vec::new();
    lines.push(Line::from(""));
    lines.push(Line::from(vec![
        Span::styled("  Agent proposed: ", styles::dim_style(theme)),
        Span::styled(
            "land generated test".to_string(),
            Style::default().add_modifier(Modifier::BOLD),
        ),
    ]));
    lines.push(Line::from(""));
    lines.push(Line::from(vec![
        Span::styled("  Path: ", styles::dim_style(theme)),
        Span::styled(
            test_path.to_string(),
            Style::default().add_modifier(Modifier::BOLD),
        ),
    ]));
    lines.push(Line::from(vec![
        Span::styled("  Spec id: ", styles::dim_style(theme)),
        Span::raw(spec_id.to_string()),
    ]));
    lines.push(Line::from(vec![
        Span::styled("  Size: ", styles::dim_style(theme)),
        Span::raw(format!("{body_bytes} bytes / {body_line_count} lines")),
    ]));
    lines.push(Line::from(""));
    if preview_lines.is_empty() {
        lines.push(Line::from(Span::styled(
            "  (empty body)".to_string(),
            styles::dim_style(theme),
        )));
    } else {
        lines.push(Line::from(Span::styled(
            "  Preview:".to_string(),
            styles::dim_style(theme),
        )));
        for raw in preview_lines {
            let display: String = raw.chars().take(70).collect();
            lines.push(Line::from(format!("    {display}")));
        }
        if has_more {
            lines.push(Line::from(Span::styled(
                "    ...".to_string(),
                styles::dim_style(theme),
            )));
        }
    }
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        format!("  {countdown}"),
        styles::dim_style(theme),
    )));
    lines.push(Line::from(""));
    lines.push(Line::from(vec![
        Span::styled("  [y]", Style::default().add_modifier(Modifier::BOLD)),
        Span::raw("es  "),
        Span::styled("[n]", Style::default().add_modifier(Modifier::BOLD)),
        Span::raw("o  "),
        Span::styled("[Esc]", Style::default().add_modifier(Modifier::BOLD)),
    ]));

    let paragraph = Paragraph::new(lines).style(styles::popup_style(theme));
    frame.render_widget(paragraph, inner);
}

fn centered_rect(percent_x: u16, percent_y: u16, area: Rect) -> Rect {
    let vertical = Layout::vertical([Constraint::Percentage(percent_y)]).flex(Flex::Center);
    let horizontal = Layout::horizontal([Constraint::Percentage(percent_x)]).flex(Flex::Center);
    let [area] = vertical.areas(area);
    let [area] = horizontal.areas(area);
    area
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::theme::Theme;
    use ratatui::style::Color;

    fn test_theme() -> Theme {
        Theme::default()
    }

    #[test]
    fn should_return_cursor_at_start_for_empty_buffer() {
        // given
        let theme = test_theme();

        // when
        let (lines, cursor_info) = format_comment_input_lines(
            &theme,
            CommentTypePresentation {
                label: "NOTE".to_string(),
                color: Color::Blue,
            },
            "",
            0,
            None,
            false,
            false,
        );

        // then
        assert_eq!(lines.len(), 4); // header + content + bottom-border + footer
        assert_eq!(cursor_info.line_offset, 1); // cursor on first content line
        assert_eq!(cursor_info.column, 7); // "     │ " = 7 chars
    }

    #[test]
    fn should_return_cursor_position_for_ascii_text() {
        // given
        let theme = test_theme();
        let buffer = "hello";
        let cursor_pos = 3; // cursor after "hel"

        // when
        let (_, cursor_info) = format_comment_input_lines(
            &theme,
            CommentTypePresentation {
                label: "NOTE".to_string(),
                color: Color::Blue,
            },
            buffer,
            cursor_pos,
            None,
            false,
            false,
        );

        // then
        assert_eq!(cursor_info.line_offset, 1); // first content line
        assert_eq!(cursor_info.column, 7 + 3); // border + "hel"
    }

    #[test]
    fn should_return_cursor_position_for_multibyte_text() {
        // given
        let theme = test_theme();
        let buffer = "안녕"; // 2 multibyte chars, 6 bytes, 4 display columns
        let cursor_pos = 3; // cursor after first multibyte char (after "안")

        // when
        let (_, cursor_info) = format_comment_input_lines(
            &theme,
            CommentTypePresentation {
                label: "NOTE".to_string(),
                color: Color::Blue,
            },
            buffer,
            cursor_pos,
            None,
            false,
            false,
        );

        // then
        assert_eq!(cursor_info.line_offset, 1);
        // "안" has display width 2, so cursor column = border(7) + 2 = 9
        assert_eq!(cursor_info.column, 7 + 2);
    }

    #[test]
    fn should_return_cursor_position_at_end_of_text() {
        // given
        let theme = test_theme();
        let buffer = "test";
        let cursor_pos = 4; // cursor at end

        // when
        let (_, cursor_info) = format_comment_input_lines(
            &theme,
            CommentTypePresentation {
                label: "NOTE".to_string(),
                color: Color::Blue,
            },
            buffer,
            cursor_pos,
            None,
            false,
            false,
        );

        // then
        assert_eq!(cursor_info.line_offset, 1);
        assert_eq!(cursor_info.column, 7 + 4); // border + "test"
    }

    #[test]
    fn should_return_cursor_position_on_second_line() {
        // given
        let theme = test_theme();
        let buffer = "line1\nline2";
        let cursor_pos = 8; // cursor after "li" in "line2"

        // when
        let (lines, cursor_info) = format_comment_input_lines(
            &theme,
            CommentTypePresentation {
                label: "NOTE".to_string(),
                color: Color::Blue,
            },
            buffer,
            cursor_pos,
            None,
            false,
            false,
        );

        // then
        assert_eq!(lines.len(), 5); // header + 2 content lines + bottom-border + footer
        assert_eq!(cursor_info.line_offset, 2); // second content line (0=header, 1=line1, 2=line2)
        assert_eq!(cursor_info.column, 7 + 2); // border + "li"
    }

    #[test]
    fn should_wrap_long_single_line_to_width() {
        // given: a 60-char single line, wrapped to width 30
        let text = "a".repeat(60);

        // when
        let wrapped = wrap_line_to_width(&text, 30);

        // then: expect 2 sub-lines, none exceeding width 30
        assert!(
            wrapped.len() >= 2,
            "expected multiple wrapped lines, got {}",
            wrapped.len()
        );
        for sub in &wrapped {
            assert!(
                sub.width() <= 30,
                "wrapped line exceeded width 30: {:?} (width {})",
                sub,
                sub.width()
            );
        }
        // Sum of widths + dropped whitespace should equal original (no whitespace here => exact match)
        let total: usize = wrapped.iter().map(|s| s.width()).sum();
        assert_eq!(total, 60);
    }

    #[test]
    fn should_wrap_at_word_boundaries_when_possible() {
        // given
        let text = "hello world this is a fairly long sentence for wrapping";

        // when
        let wrapped = wrap_line_to_width(text, 20);

        // then
        assert!(wrapped.len() >= 2);
        for sub in &wrapped {
            assert!(sub.width() <= 20, "line {:?} width {}", sub, sub.width());
            // No sub-line should start with a space (we strip the wrap-point whitespace).
            assert!(
                !sub.starts_with(' '),
                "leading space on wrapped line: {sub:?}"
            );
        }
    }

    #[test]
    fn should_leave_short_lines_unchanged() {
        // given
        let text = "short line";

        // when
        let wrapped = wrap_line_to_width(text, 30);

        // then
        assert_eq!(wrapped, vec!["short line".to_string()]);
    }

    #[test]
    fn should_preserve_explicit_newlines_and_wrap_long_segment() {
        // given: buffer with an explicit '\n' after 5 chars, followed by a long segment
        // that must wrap. format_comment_lines splits on '\n' first, then wraps each piece.
        let theme = test_theme();
        let long = "a".repeat(80);
        let content = format!("short\n{long}");

        // when
        let lines = format_comment_lines(
            &theme,
            CommentTypePresentation {
                label: "NOTE".to_string(),
                color: Color::Blue,
            },
            &content,
            None,
        );

        // then:
        // - 1 header + 1 "short" content line + N wrapped content lines + 1 footer
        // - the explicit break produces at least one content line containing "short"
        // - the long segment wraps into multiple content lines
        assert!(
            lines.len() >= 4,
            "expected header + content + footer, got {}",
            lines.len()
        );

        // Count content lines (exclude header at 0 and footer at last).
        let content_line_count = lines.len().saturating_sub(2);
        assert!(
            content_line_count >= 3,
            "expected at least 3 content lines (explicit break + wrapped segment), got {content_line_count}"
        );

        // First content line should render the "short" literal (pre-newline segment).
        let first_content = &lines[1];
        let first_text: String = first_content
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect();
        assert!(
            first_text.contains("short"),
            "first content line should contain 'short', got {first_text:?}"
        );

        // None of the content lines should have body text wider than CONTENT_WIDTH.
        for line in &lines[1..lines.len() - 1] {
            // Skip the border prefix span (first span) and measure the remaining text.
            let body: String = line
                .spans
                .iter()
                .skip(1)
                .map(|s| s.content.as_ref())
                .collect();
            assert!(
                body.width() <= CONTENT_WIDTH,
                "content body width {} exceeded CONTENT_WIDTH {}: {:?}",
                body.width(),
                CONTENT_WIDTH,
                body
            );
        }
    }

    #[test]
    fn should_return_cursor_position_for_mixed_content() {
        // given
        let theme = test_theme();
        let buffer = "a좋b"; // 1 + 3 + 1 = 5 bytes, 1 + 2 + 1 = 4 display columns
        let cursor_pos = 4; // cursor after "a좋" (1 + 3 bytes)

        // when
        let (_, cursor_info) = format_comment_input_lines(
            &theme,
            CommentTypePresentation {
                label: "NOTE".to_string(),
                color: Color::Blue,
            },
            buffer,
            cursor_pos,
            None,
            false,
            false,
        );

        // then
        assert_eq!(cursor_info.line_offset, 1);
        // "a" = 1 display width, "좋" = 2 display width, total = 3
        assert_eq!(cursor_info.column, 7 + 3);
    }

    // --- Regression tests for wrap_line_to_width's previous `.unwrap()` crash ---

    #[test]
    fn wrap_line_to_width_handles_empty_input() {
        // given: empty string
        // when
        let wrapped = wrap_line_to_width("", 10);
        // then: a single empty string back, no panic
        assert_eq!(wrapped, vec![String::new()]);
    }

    #[test]
    fn wrap_line_to_width_handles_trailing_whitespace() {
        // given: text whose only wrap-candidate whitespace is trailing
        // The previous implementation indexed past the whitespace using
        // `.chars().next().unwrap()` — regression test to ensure no panic.
        let text = "abcdefghij "; // 11 cols, width 10 forces a wrap
        let wrapped = wrap_line_to_width(text, 10);
        // Should produce at least one line and every line must fit.
        assert!(!wrapped.is_empty());
        for sub in &wrapped {
            assert!(sub.width() <= 10, "{sub:?} exceeds width 10");
        }
    }

    #[test]
    fn wrap_line_to_width_handles_cjk_only_no_whitespace() {
        // given: CJK-only text with no whitespace (must hard-break on char boundary)
        // "한" has display width 2, 10 copies = 20 cols, wrapped to 7 forces
        // multiple char-boundary breaks without any whitespace fallback.
        let text = "".repeat(10);
        let wrapped = wrap_line_to_width(&text, 7);
        // Every sub-line must fit within width, none empty (full chars only).
        assert!(wrapped.len() >= 2);
        for sub in &wrapped {
            assert!(sub.width() <= 7, "{sub:?} exceeds width 7");
            assert!(!sub.is_empty());
        }
    }

    #[test]
    fn format_comment_input_lines_handles_cjk_wrap_without_panic() {
        // given: buffer that will wrap and has no ASCII whitespace at boundaries.
        // This exercises the now-defensive cursor-walk that used to `.unwrap()`
        // on `text[consumed_bytes..].chars().next()`.
        let theme = test_theme();
        let buffer = "".repeat(50);
        let cursor_pos = 3; // 1 char in (each "한" is 3 bytes)

        let (_, cursor_info) = format_comment_input_lines(
            &theme,
            CommentTypePresentation {
                label: "NOTE".to_string(),
                color: Color::Blue,
            },
            &buffer,
            cursor_pos,
            None,
            false,
            false,
        );

        // cursor should still land on some content line (not panic)
        assert!(cursor_info.line_offset >= 1);
    }
}