travelagent 1.10.2

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
//! Remote-review + commit-selection panel rendering (H9 part 2).
//!
//! Extracted from `ui/app_layout.rs` so it and the two diff renderers
//! stay under the ROADMAP's 1kLOC target. This module owns:
//!
//! - `render_commit_select` — the full-screen commit picker shown on
//!   startup (local mode only).
//! - `render_remote_right_panel` + `render_remote_tab_bar` — the
//!   tabbed right-hand area in remote PR/MR review (Files |
//!   Description | Conversation | Commits).
//! - `render_inline_commit_selector` — the inline picker shown inside
//!   a running session (e.g. `:commits`).
//!
//! The free helper `truncate_str` also lives here because only these
//! functions consume it. If another caller shows up it can move back
//! to `app_layout.rs`.

use ratatui::{
    Frame,
    layout::{Constraint, Direction, Layout, Rect},
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Paragraph},
};

use crate::app::{App, FocusedPanel, RemotePanel};
use crate::ui::{commits_panel, conversation_panel, description_panel, status_bar, styles};

pub(super) fn render_commit_select(frame: &mut Frame, app: &mut App) {
    let area = frame.area();

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // Header
            Constraint::Min(0),    // Commit list
            Constraint::Length(1), // Footer hints
        ])
        .split(area);

    // Header
    let header = Paragraph::new(" Select commits to review ")
        .style(styles::header_style(&app.theme))
        .block(Block::default().style(styles::panel_style(&app.theme)));
    frame.render_widget(header, chunks[0]);

    // Commit list
    let block = Block::default()
        .title(" Recent Commits ")
        .borders(Borders::ALL)
        .style(styles::panel_style(&app.theme))
        .border_style(styles::border_style(&app.theme, true));

    let inner = block.inner(chunks[1]);
    frame.render_widget(block, chunks[1]);

    // Update viewport height for scroll calculations
    app.commit_select.viewport_height = inner.height as usize;

    // Get range info for visual indicators
    let range = app.commit_select.selection_range;

    // Determine commits to show
    let total_commits = app.commit_select.list.len();
    let visible_count = app.commit_select.visible_count.min(total_commits);

    let mut items: Vec<Line> = app
        .commit_select
        .list
        .iter()
        .take(visible_count)
        .enumerate()
        .map(|(i, commit)| {
            let is_selected = app.is_commit_selected(i);
            let is_cursor = i == app.commit_select.cursor;

            // Range boundary indicators
            let range_marker = match range {
                Some((start, end)) if i == start && i == end => "",
                Some((start, _)) if i == start => "",
                Some((_, end)) if i == end => "",
                Some((start, end)) if i > start && i < end => "",
                _ => " ",
            };

            let checkbox = if is_selected { "[x]" } else { "[ ]" };
            let pointer = if is_cursor { ">" } else { " " };

            let style = if is_cursor {
                styles::selected_style(&app.theme)
            } else if is_selected {
                Style::default().fg(app.theme.fg_secondary)
            } else {
                Style::default()
            };

            let checkbox_style = if is_selected {
                styles::reviewed_style(&app.theme)
            } else {
                styles::pending_style(&app.theme)
            };

            let range_style = if is_selected {
                styles::reviewed_style(&app.theme)
            } else {
                Style::default().fg(app.theme.fg_secondary)
            };

            // Format: > ┌ [x] abc1234  Commit message (author, date)
            let time_str = commit.time.format("%Y-%m-%d").to_string();
            let mut spans = vec![
                Span::styled(format!("{pointer} "), style),
                Span::styled(format!("{range_marker} "), range_style),
                Span::styled(format!("{checkbox} "), checkbox_style),
                Span::styled(
                    format!("{} ", commit.short_id),
                    styles::hash_style(&app.theme),
                ),
            ];

            if commit.id == crate::app::STAGED_SELECTION_ID
                || commit.id == crate::app::UNSTAGED_SELECTION_ID
            {
                spans.push(Span::styled(&commit.summary, style));
                return Line::from(spans);
            }

            if let Some(branch_name) = &commit.branch_name {
                spans.push(Span::styled(
                    format!("[{}] ", truncate_str(branch_name, 20)),
                    styles::branch_style(&app.theme),
                ));
            }

            spans.push(Span::styled(truncate_str(&commit.summary, 50), style));
            spans.push(Span::styled(
                format!(" ({}, {})", commit.author, time_str),
                Style::default().fg(app.theme.fg_secondary),
            ));

            Line::from(spans)
        })
        .collect();

    // Show an expand row when commits are collapsed
    if app.can_show_more_commits() {
        let is_cursor = app.commit_select.cursor == visible_count;

        let style = if is_cursor {
            styles::selected_style(&app.theme)
        } else {
            Style::default().fg(app.theme.fg_secondary)
        };

        items.push(Line::from(vec![
            Span::styled(if is_cursor { "> " } else { "  " }, style),
            Span::styled("       ... show more commits ...", style),
        ]));
    }

    // Apply scroll offset and take only visible items
    let visible_items: Vec<Line> = items
        .into_iter()
        .skip(app.commit_select.scroll_offset)
        .take(inner.height as usize)
        .collect();

    let list = Paragraph::new(visible_items).style(styles::panel_style(&app.theme));
    frame.render_widget(list, inner);

    // Footer with mode, hints, and right-aligned message
    let theme = &app.theme;
    let mode_span = Span::styled(" SELECT ", styles::mode_style(theme));

    let selected_count = match app.commit_select.selection_range {
        Some((start, end)) => end - start + 1,
        None => 0,
    };
    let selection_info = if selected_count > 0 {
        format!(" ({selected_count} selected)")
    } else {
        String::new()
    };
    let hints = format!(" j/k:navigate  Space:select range  Enter:confirm  q:quit{selection_info}");
    let hints_span = Span::styled(hints, Style::default().fg(theme.fg_secondary));

    let left_spans = vec![mode_span, hints_span];

    let (message_span, message_width) = status_bar::build_message_span(app.message.as_ref(), theme);
    let spans = status_bar::build_right_aligned_spans(
        left_spans,
        message_span,
        message_width,
        chunks[2].width as usize,
    );

    let footer = Paragraph::new(Line::from(spans))
        .style(styles::status_bar_style(theme))
        .block(Block::default());
    frame.render_widget(footer, chunks[2]);
}

fn truncate_str(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else {
        let truncate_at = max_len.saturating_sub(3);
        let end = s
            .char_indices()
            .map(|(i, _)| i)
            .take_while(|&i| i <= truncate_at)
            .last()
            .unwrap_or(0);
        format!("{}...", &s[..end])
    }
}

/// Render the right panel area for remote PR review: tab bar + active panel content.
pub(super) fn render_remote_right_panel(frame: &mut Frame, app: &mut App, area: Rect) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(1), Constraint::Min(0)])
        .split(area);

    render_remote_tab_bar(frame, app, chunks[0]);

    // In local mode (e.g. tour mode) the right panel falls back to the
    // diff view; we should never reach the non-Files arms without a
    // `RemoteSessionState` to drive them.
    let panel = app
        .remote()
        .map(|r| r.remote_panel)
        .unwrap_or(RemotePanel::Files);

    match panel {
        RemotePanel::Files => {
            app.ui_layout.diff_area = Some(chunks[1]);
            super::app_layout::render_diff_view(frame, app, chunks[1]);
        }
        RemotePanel::Description => {
            description_panel::render(frame, app, chunks[1]);
        }
        RemotePanel::Conversation => {
            conversation_panel::render(frame, app, chunks[1]);
        }
        RemotePanel::Commits => {
            commits_panel::render(frame, app, chunks[1]);
        }
        RemotePanel::Sparring => {
            super::sparring_panel::render(frame, app, chunks[1]);
        }
    }
}

/// Render the tab bar showing 1:Files | 2:Description | 3:Conversation | 4:Commits
fn render_remote_tab_bar(frame: &mut Frame, app: &App, area: Rect) {
    let active = app
        .remote()
        .map(|r| r.remote_panel)
        .unwrap_or(RemotePanel::Files);
    let theme = &app.theme;

    let active_style = Style::default()
        .fg(theme.fg_primary)
        .add_modifier(Modifier::BOLD);
    let inactive_style = Style::default().fg(theme.fg_dim);
    let sep_style = Style::default().fg(theme.fg_dim);

    let mut tabs: Vec<(RemotePanel, &'static str)> = vec![
        (RemotePanel::Files, "1:Files"),
        (RemotePanel::Description, "2:Description"),
        (RemotePanel::Conversation, "3:Conversation"),
        (RemotePanel::Commits, "4:Commits"),
    ];
    // Phase I5-1: expose the Sparring tab only while `spar_mode` is
    // active so non-sparring reviews don't show an empty reconciliation
    // label. Matches the `5` digit-key gate in `main.rs`.
    if app.spar_mode {
        tabs.push((RemotePanel::Sparring, "5:Sparring"));
    }

    let mut spans = vec![Span::raw(" ")];
    for (i, (panel, label)) in tabs.iter().enumerate() {
        if i > 0 {
            spans.push(Span::styled(" | ", sep_style));
        }
        let style = if *panel == active {
            active_style
        } else {
            inactive_style
        };
        spans.push(Span::styled(*label, style));
    }

    let line = Line::from(spans);
    let paragraph = Paragraph::new(line).style(styles::header_style(theme));
    frame.render_widget(paragraph, area);
}

pub(super) fn render_inline_commit_selector(frame: &mut Frame, app: &mut App, area: Rect) {
    let focused = app.nav.focused_panel == FocusedPanel::CommitSelector;
    let block = Block::default()
        .title(" Commits ")
        .borders(Borders::ALL)
        .border_style(styles::border_style(&app.theme, focused));

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

    // Update viewport height for scroll
    app.commit_select.viewport_height = inner.height as usize;

    {
        let range = app.commit_select.selection_range;
        let total_commits = app.inline_selector.commits.len();

        let items: Vec<Line> = app
            .inline_selector
            .commits
            .iter()
            .take(total_commits)
            .enumerate()
            .map(|(i, commit)| {
                let is_selected = app.is_commit_selected(i);
                let is_cursor = i == app.commit_select.cursor;

                // Range boundary indicators
                let range_marker = match range {
                    Some((start, end)) if i == start && i == end => "\u{2500}",
                    Some((start, _)) if i == start => "\u{250c}",
                    Some((_, end)) if i == end => "\u{2514}",
                    Some((start, end)) if i > start && i < end => "\u{2502}",
                    _ => " ",
                };

                let checkbox = if is_selected { "[x]" } else { "[ ]" };

                let style = if is_cursor {
                    styles::selected_style(&app.theme)
                } else if is_selected {
                    Style::default().fg(app.theme.fg_secondary)
                } else {
                    Style::default()
                };

                let checkbox_style = if is_selected {
                    styles::reviewed_style(&app.theme)
                } else {
                    styles::pending_style(&app.theme)
                };

                let range_style = if is_selected {
                    styles::reviewed_style(&app.theme)
                } else {
                    Style::default().fg(app.theme.fg_secondary)
                };

                let pointer = if is_cursor { "> " } else { "  " };

                let time_str = commit.time.format("%Y-%m-%d").to_string();
                let mut spans = vec![
                    Span::styled(pointer.to_string(), style),
                    Span::styled(format!("{range_marker} "), range_style),
                    Span::styled(format!("{checkbox} "), checkbox_style),
                    Span::styled(
                        format!("{} ", commit.short_id),
                        styles::hash_style(&app.theme),
                    ),
                ];

                if let Some(branch_name) = &commit.branch_name {
                    spans.push(Span::styled(
                        format!("[{}] ", truncate_str(branch_name, 20)),
                        styles::branch_style(&app.theme),
                    ));
                }

                spans.push(Span::styled(truncate_str(&commit.summary, 50), style));
                spans.push(Span::styled(
                    format!(" ({}, {})", commit.author, time_str),
                    Style::default().fg(app.theme.fg_secondary),
                ));

                Line::from(spans)
            })
            .collect();

        let visible_items: Vec<Line> = items
            .into_iter()
            .skip(app.commit_select.scroll_offset)
            .take(inner.height as usize)
            .collect();

        let paragraph = Paragraph::new(visible_items);
        frame.render_widget(paragraph, inner);
    }
}

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

    #[test]
    fn should_return_string_unchanged_when_within_max_len() {
        // given
        let s = "hello";
        // when
        let result = truncate_str(s, 10);
        // then
        assert_eq!(result, "hello");
    }

    #[test]
    fn should_truncate_ascii_string_with_ellipsis() {
        // given
        let s = "hello world this is long";
        // when
        let result = truncate_str(s, 10);
        // then
        assert_eq!(result, "hello w...");
    }

    #[test]
    fn should_truncate_without_panicking_on_multibyte_chars() {
        // given - the exact string from the bug report
        let s = "Resolve \"SD : Envoi en validation manuelle après 3 rejet de la fiche employé\"";
        // when
        let result = truncate_str(s, 47);
        // then - should not panic and should end with "..."
        assert!(result.ends_with("..."));
        assert!(result.len() <= 47);
    }

    #[test]
    fn should_handle_string_of_only_multibyte_chars() {
        // given
        let s = "ééééééééé";
        // when
        let result = truncate_str(s, 5);
        // then
        assert!(result.ends_with("..."));
        assert!(result.is_char_boundary(result.len()));
    }
}