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
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
use ratatui::{
    Frame,
    layout::Rect,
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::Paragraph,
};

use crate::app::App;
use crate::theme::Theme;
use crate::ui::{markdown, styles};
use travelagent_core::forge::{RemoteComment, ReviewThread};

/// Default width used when the caller doesn't know the real panel width yet.
/// Wide enough to read comfortably without forcing pathological wrapping.
const DEFAULT_BODY_WIDTH: usize = 80;

/// Return the indices into the remote comments list of the top-level
/// threads, in the order they are rendered. Returns an empty vec in
/// local mode (no remote comments to enumerate).
pub fn top_level_thread_indices(app: &App) -> Vec<usize> {
    let Some(r) = app.remote() else {
        return Vec::new();
    };
    r.remote_comments
        .iter()
        .enumerate()
        .filter(|(_, c)| c.in_reply_to.is_none())
        .map(|(idx, _)| idx)
        .collect()
}

/// Look up the resolution state for a given top-level comment id.
/// Returns `None` if no matching review thread exists.
pub fn thread_is_resolved(threads: &[ReviewThread], root_comment_id: u64) -> Option<bool> {
    threads
        .iter()
        .find(|t| t.root_comment_id == root_comment_id)
        .map(|t| t.is_resolved)
}

/// Return the thread id for the currently selected top-level comment, if any.
pub fn selected_thread_id(app: &App) -> Option<String> {
    let r = app.remote()?;
    let tops = top_level_thread_indices(app);
    let idx = *tops.get(r.conversation_cursor)?;
    let root = r.remote_comments.get(idx)?;
    r.review_threads
        .iter()
        .find(|t| t.root_comment_id == root.id)
        .map(|t| t.id.clone())
}

/// Return the selected thread's root `RemoteComment` id, if any.
pub fn selected_root_comment_id(app: &App) -> Option<u64> {
    let r = app.remote()?;
    let tops = top_level_thread_indices(app);
    let idx = *tops.get(r.conversation_cursor)?;
    r.remote_comments.get(idx).map(|c| c.id)
}

/// Clamp the cursor to the available threads. No-op in local mode.
pub fn clamp_conversation_cursor(app: &mut App) {
    let tops = top_level_thread_indices(app);
    let Some(r) = app.remote_mut() else {
        return;
    };
    if tops.is_empty() {
        r.conversation_cursor = 0;
    } else if r.conversation_cursor >= tops.len() {
        r.conversation_cursor = tops.len() - 1;
    }
}

/// Build the lines for a single thread header, prefixing with the resolved
/// marker. Returns the styled line.
fn header_line(
    label: String,
    is_resolved: Option<bool>,
    theme_pending: ratatui::style::Color,
    theme_reviewed: ratatui::style::Color,
) -> Line<'static> {
    let (marker, marker_color) = match is_resolved {
        Some(true) => ("[\u{2713}] ", theme_reviewed),
        Some(false) => ("[ ] ", theme_pending),
        None => ("[ ] ", theme_pending),
    };
    Line::from(vec![
        Span::styled(marker.to_string(), Style::default().fg(marker_color)),
        Span::styled(label, Style::default().add_modifier(Modifier::BOLD)),
    ])
}

/// Result of laying out the conversation panel — used by rendering and tests.
#[derive(Debug, Clone)]
pub struct ConversationLayout {
    pub lines: Vec<Line<'static>>,
    /// For each top-level thread (in render order), the index of its header
    /// line within `lines`.
    pub thread_header_indices: Vec<usize>,
}

/// Build the lines that make up the conversation panel, and record the header
/// index for every top-level thread so the selected thread can be highlighted
/// and scrolled into view.
///
/// `width` is the available rendering width (in columns); the markdown
/// renderer wraps at this width after the 4/6-space reply indent is
/// accounted for.
pub fn layout(app: &App, width: usize) -> ConversationLayout {
    let theme = &app.theme;
    let mut lines: Vec<Line<'static>> = Vec::new();
    let mut thread_header_indices: Vec<usize> = Vec::new();

    // Local mode has no remote comments — fall through to the "empty"
    // render below so the panel still paints.
    let remote_comments: &[RemoteComment] = app
        .remote()
        .map(|r| r.remote_comments.as_slice())
        .unwrap_or(&[]);
    let review_threads: &[ReviewThread] = app
        .remote()
        .map(|r| r.review_threads.as_slice())
        .unwrap_or(&[]);

    if remote_comments.is_empty() {
        lines.push(Line::from(Span::styled(
            "  No comments yet".to_string(),
            styles::dim_style(theme),
        )));
        return ConversationLayout {
            lines,
            thread_header_indices,
        };
    }

    let top_level: Vec<&RemoteComment> = remote_comments
        .iter()
        .filter(|c| c.in_reply_to.is_none())
        .collect();

    for comment in &top_level {
        let timestamp = comment.created_at.format("%Y-%m-%d %H:%M");
        let header_label = format!("  {} ({}):", comment.author, timestamp);
        let is_resolved = thread_is_resolved(review_threads, comment.id);
        let header_idx = lines.len();
        thread_header_indices.push(header_idx);
        lines.push(header_line(
            header_label,
            is_resolved,
            theme.pending,
            theme.reviewed,
        ));

        append_body_lines(
            &mut lines,
            &comment.body,
            theme,
            width,
            4,
            app.markdown_rendering_enabled,
        );

        if let Some(ref path) = comment.path {
            let loc = if let Some(line) = comment.line {
                format!("  [{path}:{line}]")
            } else {
                format!("  [{path}]")
            };
            lines.push(Line::from(Span::styled(loc, styles::dim_style(theme))));
        }

        let replies: Vec<&RemoteComment> = remote_comments
            .iter()
            .filter(|c| c.in_reply_to == Some(comment.id))
            .collect();

        for reply in &replies {
            let reply_ts = reply.created_at.format("%Y-%m-%d %H:%M");
            lines.push(Line::from(vec![Span::styled(
                format!("    \u{21b3} {} ({}):", reply.author, reply_ts),
                Style::default().add_modifier(Modifier::BOLD),
            )]));
            append_body_lines(
                &mut lines,
                &reply.body,
                theme,
                width,
                6,
                app.markdown_rendering_enabled,
            );
        }

        lines.push(Line::from(""));
    }

    ConversationLayout {
        lines,
        thread_header_indices,
    }
}

/// Append the body of a comment or reply, indenting each produced line by
/// `indent` columns. When `markdown_enabled` is true the body is rendered via
/// the markdown pipeline; otherwise each source line is pushed verbatim.
fn append_body_lines(
    lines: &mut Vec<Line<'static>>,
    body: &str,
    theme: &Theme,
    width: usize,
    indent: usize,
    markdown_enabled: bool,
) {
    let available = width.saturating_sub(indent);
    let prefix: String = " ".repeat(indent);
    let file_ref_style = Style::default().fg(theme.file_ref);
    if markdown_enabled {
        let rendered = markdown::render_markdown(body, theme, available);
        // Promote `@path/to/file` tokens to the theme's file-ref colour so
        // humans can visually trace code references within comment bodies.
        // Spans that already carry the markdown code colour are skipped to
        // avoid restyling tokens inside inline code or fenced blocks.
        let rendered = markdown::highlight_file_refs(rendered, file_ref_style, theme.markdown_code);
        for mut rendered_line in rendered {
            let mut spans = Vec::with_capacity(rendered_line.spans.len() + 1);
            spans.push(Span::raw(prefix.clone()));
            spans.append(&mut rendered_line.spans);
            lines.push(Line::from(spans));
        }
    } else {
        for body_line in body.lines() {
            let raw = Line::from(format!("{prefix}{body_line}"));
            let promoted =
                markdown::highlight_file_refs(vec![raw], file_ref_style, theme.markdown_code);
            lines.extend(promoted);
        }
    }
}

/// Auto-scroll so the header of the selected thread (at `thread_header_indices[cursor]`)
/// is visible within `viewport_height` rows starting at `current_scroll`.
pub fn auto_scroll_for_cursor(
    current_scroll: usize,
    total_lines: usize,
    viewport_height: usize,
    thread_header_indices: &[usize],
    cursor: usize,
) -> usize {
    let max_scroll = total_lines.saturating_sub(viewport_height);
    let header = match thread_header_indices.get(cursor) {
        Some(&h) => h,
        None => return current_scroll.min(max_scroll),
    };

    let mut scroll = current_scroll.min(max_scroll);
    // If header is above the viewport, scroll up to it.
    if header < scroll {
        scroll = header;
    } else if viewport_height > 0 && header >= scroll + viewport_height {
        // If header is below the viewport, scroll down so header is the last row.
        scroll = header + 1 - viewport_height;
    }
    scroll.min(max_scroll)
}

pub fn render(frame: &mut Frame, app: &mut App, area: Rect) {
    let width = (area.width as usize).max(DEFAULT_BODY_WIDTH.min(20));
    let layout = layout(app, width);

    let total_lines = layout.lines.len();
    let viewport_height = area.height as usize;

    // Precompute styles here — we can't borrow both &app.theme and
    // &mut app.mode at once (both live on `App`).
    let panel_style = styles::panel_style(&app.theme);
    let selected = styles::selected_style(&app.theme);

    // Auto-scroll so the selected thread is visible. No-op in local
    // mode (no conversation state to adjust).
    let selected_header = if let Some(r) = app.remote_mut() {
        r.conversation_scroll = auto_scroll_for_cursor(
            r.conversation_scroll,
            total_lines,
            viewport_height,
            &layout.thread_header_indices,
            r.conversation_cursor,
        );
        let scroll = r.conversation_scroll;
        let sel = layout
            .thread_header_indices
            .get(r.conversation_cursor)
            .copied();
        (scroll, sel)
    } else {
        (0, None)
    };
    let (scroll, sel_header) = selected_header;

    let visible: Vec<Line> = layout
        .lines
        .into_iter()
        .enumerate()
        .skip(scroll)
        .take(viewport_height)
        .map(|(idx, line)| {
            if Some(idx) == sel_header {
                line.style(selected)
            } else {
                line
            }
        })
        .collect();

    let paragraph = Paragraph::new(visible).style(panel_style);
    frame.render_widget(paragraph, area);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::App;
    use crate::theme::Theme;
    use chrono::Utc;
    use travelagent_core::forge::{PrId, RemoteComment, ReviewThread};

    /// Build a remote-mode App for conversation tests. Uses `new_remote`
    /// with `forge = None` so the app is in `AppMode::Remote(_)` without
    /// requiring a mock forge backend.
    fn build_test_app() -> App {
        App::new_remote(
            Theme::dark(),
            None,
            false,
            Vec::new(),
            "Test PR".to_string(),
            1,
            "owner",
            "repo",
            crate::test_support::runtime_handle(),
            None,
            PrId {
                owner: "owner".to_string(),
                repo: "repo".to_string(),
                number: 1,
            },
        )
        .expect("new_remote builds in tests")
    }

    fn top_comment(id: u64, body: &str) -> RemoteComment {
        RemoteComment {
            id,
            author: "alice".to_string(),
            body: body.to_string(),
            path: None,
            line: None,
            side: None,
            created_at: Utc::now(),
            in_reply_to: None,
        }
    }

    fn reply(id: u64, parent: u64, body: &str) -> RemoteComment {
        RemoteComment {
            id,
            author: "bob".to_string(),
            body: body.to_string(),
            path: None,
            line: None,
            side: None,
            created_at: Utc::now(),
            in_reply_to: Some(parent),
        }
    }

    fn thread(id: &str, root: u64, resolved: bool) -> ReviewThread {
        ReviewThread {
            id: id.to_string(),
            is_resolved: resolved,
            root_comment_id: root,
        }
    }

    #[test]
    fn top_level_thread_indices_filters_replies() {
        let mut app = build_test_app();
        app.remote_mut().unwrap().remote_comments = vec![
            top_comment(1, "first"),
            reply(2, 1, "reply to first"),
            top_comment(3, "second"),
        ];
        let tops = top_level_thread_indices(&app);
        assert_eq!(tops, vec![0, 2]);
    }

    #[test]
    fn selected_thread_id_returns_matching_thread() {
        let mut app = build_test_app();
        {
            let r = app.remote_mut().unwrap();
            r.remote_comments = vec![top_comment(10, "hi"), top_comment(20, "there")];
            r.review_threads = vec![thread("t10", 10, false), thread("t20", 20, true)];
            r.conversation_cursor = 1;
        }
        assert_eq!(selected_thread_id(&app), Some("t20".to_string()));

        app.remote_mut().unwrap().conversation_cursor = 0;
        assert_eq!(selected_thread_id(&app), Some("t10".to_string()));
    }

    #[test]
    fn selected_thread_id_none_when_empty() {
        let app = build_test_app();
        assert!(selected_thread_id(&app).is_none());
    }

    #[test]
    fn thread_is_resolved_handles_missing() {
        let threads = vec![thread("t1", 1, true), thread("t2", 2, false)];
        assert_eq!(thread_is_resolved(&threads, 1), Some(true));
        assert_eq!(thread_is_resolved(&threads, 2), Some(false));
        assert_eq!(thread_is_resolved(&threads, 3), None);
    }

    #[test]
    fn clamp_conversation_cursor_keeps_in_bounds() {
        let mut app = build_test_app();
        {
            let r = app.remote_mut().unwrap();
            r.remote_comments = vec![top_comment(1, "a"), top_comment(2, "b")];
            r.conversation_cursor = 99;
        }
        clamp_conversation_cursor(&mut app);
        assert_eq!(app.remote().unwrap().conversation_cursor, 1);

        {
            let r = app.remote_mut().unwrap();
            r.remote_comments.clear();
            r.conversation_cursor = 99;
        }
        clamp_conversation_cursor(&mut app);
        assert_eq!(app.remote().unwrap().conversation_cursor, 0);
    }

    #[test]
    fn layout_produces_header_for_each_top_level_thread() {
        let mut app = build_test_app();
        app.remote_mut().unwrap().remote_comments = vec![
            top_comment(1, "first"),
            reply(2, 1, "reply"),
            top_comment(3, "second"),
        ];
        let layout = layout(&app, 80);
        assert_eq!(layout.thread_header_indices.len(), 2);
        // First header is at index 0
        assert_eq!(layout.thread_header_indices[0], 0);
        // Second header should be after the first header, its body, and the reply lines.
        assert!(layout.thread_header_indices[1] > layout.thread_header_indices[0]);
    }

    #[test]
    fn layout_empty_when_no_comments() {
        let app = build_test_app();
        let layout = layout(&app, 80);
        assert_eq!(layout.thread_header_indices.len(), 0);
        assert_eq!(layout.lines.len(), 1); // "No comments yet"
    }

    #[test]
    fn layout_renders_resolved_marker() {
        let mut app = build_test_app();
        {
            let r = app.remote_mut().unwrap();
            r.remote_comments = vec![top_comment(1, "first"), top_comment(2, "second")];
            r.review_threads = vec![thread("t1", 1, true), thread("t2", 2, false)];
        }
        let layout = layout(&app, 80);
        // The resolved thread header should contain the check mark.
        let first_header = &layout.lines[layout.thread_header_indices[0]];
        let first_text: String = first_header
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect();
        assert!(first_text.starts_with("[\u{2713}] "));

        let second_header = &layout.lines[layout.thread_header_indices[1]];
        let second_text: String = second_header
            .spans
            .iter()
            .map(|s| s.content.as_ref())
            .collect();
        assert!(second_text.starts_with("[ ] "));
    }

    #[test]
    fn auto_scroll_keeps_header_in_viewport() {
        let headers = vec![0, 10, 20];
        // Cursor 2 (header at line 20), viewport 5, total 30
        let scroll = auto_scroll_for_cursor(0, 30, 5, &headers, 2);
        // Header 20 must be visible: scroll = 20 + 1 - 5 = 16
        assert_eq!(scroll, 16);

        // Cursor 0 when scrolled down: scroll back up so header 0 is visible.
        let scroll = auto_scroll_for_cursor(18, 30, 5, &headers, 0);
        assert_eq!(scroll, 0);

        // Already visible: scroll stays.
        let scroll = auto_scroll_for_cursor(8, 30, 5, &headers, 1);
        assert_eq!(scroll, 8);
    }

    #[test]
    fn auto_scroll_clamps_at_max() {
        let headers = vec![0];
        let scroll = auto_scroll_for_cursor(100, 10, 5, &headers, 0);
        assert_eq!(scroll, 0);
    }
}