travelagent 1.11.0

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
//! Smoke tests for the TUI renderer paths.
//!
//! These tests build a minimal `App` against an in-memory `StubVcs`, render
//! the UI to a `ratatui::backend::TestBackend`, and assert that the resulting
//! buffer is non-empty and contains a few load-bearing substrings (file path,
//! `@@` hunk header, `+`/`-` markers, panel titles, etc.).
//!
//! The intent is regression detection on "did the renderer crash or produce
//! nothing", not pixel-exact output — no `insta` snapshots, no full screen
//! grids, just substring contains and shape assertions. Each test runs in
//! well under 100ms because the work is bounded by an 80x24 buffer and a
//! single-file fixture.
//!
//! This module lives inside `crate::ui` because `render_unified_diff` and
//! `render_side_by_side_diff` are `pub(super)` — only visible to `mod ui`.

#![cfg(test)]

use std::path::PathBuf;

use ratatui::Terminal;
use ratatui::backend::TestBackend;
use ratatui::buffer::Buffer;

use crate::app::{App, AppMode, DiffSource, DiffViewMode, InputMode, LocalState};
use crate::theme::Theme;
use travelagent_core::error::{Result as CoreResult, TrvError};
use travelagent_core::model::{
    DiffFile, DiffHunk, DiffLine, FileStatus, LineOrigin, ReviewSession, SessionDiffSource,
};
use travelagent_core::vcs::{VcsBackend, VcsInfo, VcsType};

/// Smallest possible VCS backend that satisfies the trait. All operations
/// either return empty results or `UnsupportedOperation` — we never exercise
/// VCS code paths from these tests.
struct StubVcs {
    info: VcsInfo,
}

impl VcsBackend for StubVcs {
    fn info(&self) -> &VcsInfo {
        &self.info
    }

    fn get_working_tree_diff(&self) -> CoreResult<Vec<DiffFile>> {
        Err(TrvError::NoChanges)
    }

    fn fetch_context_lines(
        &self,
        _file_path: &std::path::Path,
        _file_status: FileStatus,
        _start_line: u32,
        _end_line: u32,
    ) -> CoreResult<Vec<DiffLine>> {
        Ok(Vec::new())
    }
}

/// Build a single-file diff with one hunk: 1 context line, 1 deletion, 1
/// addition. Mirrors what a tiny real-world diff looks like so the renderer
/// hits both `+`/`-` paint paths plus an `@@` hunk header.
fn make_test_diff_file() -> DiffFile {
    DiffFile {
        old_path: Some(PathBuf::from("src/foo.rs")),
        new_path: Some(PathBuf::from("src/foo.rs")),
        status: FileStatus::Modified,
        hunks: vec![DiffHunk {
            header: "@@ -1,2 +1,2 @@".to_string(),
            lines: vec![
                DiffLine {
                    origin: LineOrigin::Context,
                    content: "fn hello() {".to_string(),
                    old_lineno: Some(1),
                    new_lineno: Some(1),
                    highlighted_spans: None,
                },
                DiffLine {
                    origin: LineOrigin::Deletion,
                    content: "    println!(\"old\");".to_string(),
                    old_lineno: Some(2),
                    new_lineno: None,
                    highlighted_spans: None,
                },
                DiffLine {
                    origin: LineOrigin::Addition,
                    content: "    println!(\"new\");".to_string(),
                    old_lineno: None,
                    new_lineno: Some(2),
                    highlighted_spans: None,
                },
            ],
            old_start: 1,
            old_count: 2,
            new_start: 1,
            new_count: 2,
        }],
        is_binary: false,
        is_too_large: false,
        is_commit_message: false,
    }
}

/// Construct a minimal `App` with the given diff files. No remote, no tour,
/// no commit selector — the simplest viable state for exercising the render
/// path. Falls through `App::build` to share the production constructor.
fn build_render_test_app(files: Vec<DiffFile>) -> App {
    let vcs_info = VcsInfo {
        root_path: PathBuf::from("/tmp/trv-render-test"),
        head_commit: "head".to_string(),
        branch_name: Some("main".to_string()),
        vcs_type: VcsType::Git,
    };
    let session = ReviewSession::new(
        vcs_info.root_path.clone(),
        vcs_info.head_commit.clone(),
        vcs_info.branch_name.clone(),
        SessionDiffSource::WorkingTree,
    );

    App::build(
        Box::new(StubVcs {
            info: vcs_info.clone(),
        }),
        vcs_info,
        Theme::dark(),
        None,
        false,
        files,
        session,
        DiffSource::WorkingTree,
        InputMode::Normal,
        Vec::new(),
        None,
        crate::test_support::runtime_handle(),
        AppMode::Local(LocalState::default()),
    )
    .expect("failed to build render-test app")
}

/// Collect the entire `Buffer` into one `String` so callers can use simple
/// `contains` checks. Lines are separated by `\n` so multi-row substrings
/// (which never wrap across lines in practice for our assertions) won't
/// accidentally match.
fn buffer_to_string(buffer: &Buffer) -> String {
    let mut out =
        String::with_capacity((buffer.area.width as usize + 1) * buffer.area.height as usize);
    for y in 0..buffer.area.height {
        for x in 0..buffer.area.width {
            out.push_str(buffer.cell((x, y)).map(|c| c.symbol()).unwrap_or(" "));
        }
        out.push('\n');
    }
    out
}

/// Returns true when at least one cell in the buffer holds a non-space
/// printable glyph — i.e. the renderer drew something.
fn buffer_has_content(buffer: &Buffer) -> bool {
    for y in 0..buffer.area.height {
        for x in 0..buffer.area.width {
            if let Some(cell) = buffer.cell((x, y))
                && !cell.symbol().trim().is_empty()
            {
                return true;
            }
        }
    }
    false
}

#[test]
fn app_layout_render_unified_smoke() {
    // Top-level render entry from `app_layout::render`. The default mode is
    // Unified, so this exercises render -> render_main_content -> render_diff_view
    // -> render_unified_diff and the header/status_bar.
    let mut app = build_render_test_app(vec![make_test_diff_file()]);
    let backend = TestBackend::new(80, 24);
    let mut terminal = Terminal::new(backend).unwrap();

    terminal.draw(|f| crate::ui::render(f, &mut app)).unwrap();

    let buf = terminal.backend().buffer().clone();
    assert!(buffer_has_content(&buf), "render produced an empty buffer");
    let text = buffer_to_string(&buf);
    // Header shows the binary name.
    assert!(
        text.contains("trv"),
        "expected 'trv' header in buffer: {text}"
    );
    // Diff title must appear above the unified diff body.
    assert!(
        text.contains("Diff (Unified)"),
        "expected 'Diff (Unified)' panel title: {text}"
    );
}

#[test]
fn diff_unified_renders_hunk_and_diff_markers() {
    // Force the cursor into the file body so the diff lines are in-viewport
    // even though the default Overview position would also paint them — we
    // want this assertion stable regardless of the default cursor.
    let mut app = build_render_test_app(vec![make_test_diff_file()]);
    app.nav.diff_view_mode = DiffViewMode::Unified;
    let backend = TestBackend::new(80, 24);
    let mut terminal = Terminal::new(backend).unwrap();

    terminal.draw(|f| crate::ui::render(f, &mut app)).unwrap();

    let buf = terminal.backend().buffer().clone();
    let text = buffer_to_string(&buf);
    assert!(buffer_has_content(&buf), "buffer was empty");
    // File path appears in the header / file list.
    assert!(
        text.contains("foo.rs"),
        "expected file path 'foo.rs' in render: {text}"
    );
    // Hunk header characters render literally.
    assert!(
        text.contains("@@"),
        "expected '@@' hunk header marker in render: {text}"
    );
    // At least one of the diff add/del marker rows is present. Markers are
    // rendered as `+ ` / `- ` (prefix span), so check for a column with the
    // marker followed by content from our fixture.
    assert!(
        text.contains("println!"),
        "expected diff line content 'println!' in render: {text}"
    );
}

#[test]
fn diff_side_by_side_renders_two_panes() {
    // Side-by-side mode splits the diff area; rendering must not panic on
    // a small (80-col) buffer where the per-pane content_width is tight.
    let mut app = build_render_test_app(vec![make_test_diff_file()]);
    app.nav.diff_view_mode = DiffViewMode::SideBySide;
    let backend = TestBackend::new(80, 24);
    let mut terminal = Terminal::new(backend).unwrap();

    terminal.draw(|f| crate::ui::render(f, &mut app)).unwrap();

    let buf = terminal.backend().buffer().clone();
    let text = buffer_to_string(&buf);
    assert!(buffer_has_content(&buf), "buffer was empty");
    assert!(
        text.contains("Diff (Side-by-Side)"),
        "expected 'Diff (Side-by-Side)' panel title: {text}"
    );
    // Hunk markers still render in side-by-side view.
    assert!(
        text.contains("@@"),
        "expected '@@' hunk header marker in SBS render: {text}"
    );
    // The file path is shown in the file list panel on the left.
    assert!(
        text.contains("foo.rs"),
        "expected file path 'foo.rs' in SBS render: {text}"
    );
}

#[test]
fn status_bar_and_header_render_branch_and_title() {
    // The header + status bar are drawn from the top-level `render`. Verify
    // that branch info ('main') and the panel title both make it onto the
    // screen — they're produced by `status_bar::render_header` and
    // `status_bar::render_status_bar` respectively.
    let mut app = build_render_test_app(vec![make_test_diff_file()]);
    let backend = TestBackend::new(80, 24);
    let mut terminal = Terminal::new(backend).unwrap();

    terminal.draw(|f| crate::ui::render(f, &mut app)).unwrap();

    let buf = terminal.backend().buffer().clone();
    let text = buffer_to_string(&buf);
    assert!(buffer_has_content(&buf), "buffer was empty");
    assert!(
        text.contains("main"),
        "expected branch 'main' (from VcsInfo) in header: {text}"
    );
    assert!(
        text.contains("trv"),
        "expected 'trv' title in header: {text}"
    );
}

#[test]
fn comment_input_box_renders_with_cursor_marker() {
    // Drive the renderer into Comment input mode on a real diff line. The
    // inline comment box (`comment_panel::format_comment_input_lines`) must
    // produce a visible bordered box with a type label and an empty-buffer
    // placeholder. Cursor positioning is handled in `app_layout::render`.
    let mut app = build_render_test_app(vec![make_test_diff_file()]);
    app.nav.input_mode = InputMode::Comment;
    app.comment.is_file_level = false;
    app.comment.is_review_level = false;
    app.comment.line = Some((2, travelagent_core::model::LineSide::New));
    app.comment.line_range = Some((
        travelagent_core::model::LineRange { start: 2, end: 2 },
        travelagent_core::model::LineSide::New,
    ));
    // Empty buffer triggers the placeholder rendering path.
    app.comment.buffer.clear();
    app.comment.cursor = 0;

    let backend = TestBackend::new(80, 24);
    let mut terminal = Terminal::new(backend).unwrap();
    terminal.draw(|f| crate::ui::render(f, &mut app)).unwrap();

    let buf = terminal.backend().buffer().clone();
    let text = buffer_to_string(&buf);
    assert!(
        buffer_has_content(&buf),
        "comment-mode render produced empty buffer"
    );
    // The "Add [type] Lx" header is rendered at the top of the inline box.
    // The default first comment type id is "note" (resolve_comment_types).
    // The label is rendered uppercased by `comment_type_label` so accept either case.
    assert!(
        text.contains("Add"),
        "expected inline comment header 'Add' in render: {text}"
    );
    let lowered = text.to_lowercase();
    assert!(
        lowered.contains("[note]"),
        "expected '[note]' comment-type label (case-insensitive) in render: {text}"
    );
    // The empty-buffer placeholder path emits this prompt.
    assert!(
        text.contains("Type your comment"),
        "expected placeholder 'Type your comment' in render: {text}"
    );
}

/// Build a render-test `App` rooted at `root` (so the viewer's working-tree
/// read finds real files) with a single modified file at `rel_path`.
fn build_render_test_app_rooted(root: PathBuf, rel_path: &str) -> App {
    let vcs_info = VcsInfo {
        root_path: root,
        head_commit: "head".to_string(),
        branch_name: Some("main".to_string()),
        vcs_type: VcsType::Git,
    };
    let session = ReviewSession::new(
        vcs_info.root_path.clone(),
        vcs_info.head_commit.clone(),
        vcs_info.branch_name.clone(),
        SessionDiffSource::WorkingTree,
    );
    let file = DiffFile {
        old_path: Some(PathBuf::from(rel_path)),
        new_path: Some(PathBuf::from(rel_path)),
        status: FileStatus::Modified,
        hunks: vec![DiffHunk {
            header: "@@ -1,1 +1,1 @@".to_string(),
            lines: vec![DiffLine {
                origin: LineOrigin::Context,
                content: "x".to_string(),
                old_lineno: Some(1),
                new_lineno: Some(1),
                highlighted_spans: None,
            }],
            old_start: 1,
            old_count: 1,
            new_start: 1,
            new_count: 1,
        }],
        is_binary: false,
        is_too_large: false,
        is_commit_message: false,
    };
    App::build(
        Box::new(StubVcs {
            info: vcs_info.clone(),
        }),
        vcs_info,
        Theme::dark(),
        None,
        false,
        vec![file],
        session,
        DiffSource::WorkingTree,
        InputMode::Normal,
        Vec::new(),
        None,
        crate::test_support::runtime_handle(),
        AppMode::Local(LocalState::default()),
    )
    .expect("failed to build rooted render-test app")
}

#[test]
fn viewer_raw_renders_full_file_with_gutter() {
    // The viewer reads the *whole* file from the working tree, not the diff
    // hunks. Write a real source file with a unique line the diff never
    // contains, activate the viewer, and assert that line plus the viewer
    // title + a line-number gutter show up.
    let dir = tempfile::tempdir().expect("tempdir");
    let rel = "src/lib.rs";
    let abs = dir.path().join(rel);
    std::fs::create_dir_all(abs.parent().unwrap()).unwrap();
    std::fs::write(&abs, "fn only_in_full_file() {}\nfn second() {}\n").unwrap();

    let mut app = build_render_test_app_rooted(dir.path().to_path_buf(), rel);
    app.nav.focused_panel = crate::app::FocusedPanel::Diff;
    app.toggle_viewer(); // probes + activates
    assert!(
        app.viewer.is_active(),
        "viewer should activate for a readable file"
    );

    let backend = TestBackend::new(80, 24);
    let mut terminal = Terminal::new(backend).unwrap();
    terminal.draw(|f| crate::ui::render(f, &mut app)).unwrap();

    let buf = terminal.backend().buffer().clone();
    let text = buffer_to_string(&buf);
    assert!(
        buffer_has_content(&buf),
        "viewer render produced empty buffer"
    );
    assert!(
        text.contains("Viewer (Raw)"),
        "expected 'Viewer (Raw)' panel title: {text}"
    );
    assert!(
        text.contains("only_in_full_file"),
        "expected full-file content (not in the diff) in viewer: {text}"
    );
    // The line-number gutter renders a '1' followed by the box-drawing divider.
    assert!(
        text.contains('\u{2502}'),
        "expected line-number gutter divider in raw viewer: {text}"
    );
}

#[test]
fn viewer_rendered_markdown_shows_heading_text() {
    // For a markdown file, `:render` (here via set_rendered) draws the body
    // through the markdown renderer. The heading text must survive.
    let dir = tempfile::tempdir().expect("tempdir");
    let rel = "README.md";
    let abs = dir.path().join(rel);
    std::fs::write(&abs, "# Welcome Heading\n\nSome body text.\n").unwrap();

    let mut app = build_render_test_app_rooted(dir.path().to_path_buf(), rel);
    app.nav.focused_panel = crate::app::FocusedPanel::Diff;
    app.toggle_viewer();
    assert!(app.viewer.is_active());
    // Markdown → rendered is allowed.
    assert!(
        app.viewer.set_rendered(std::path::Path::new(rel)),
        "markdown must be renderable"
    );

    let backend = TestBackend::new(80, 24);
    let mut terminal = Terminal::new(backend).unwrap();
    terminal.draw(|f| crate::ui::render(f, &mut app)).unwrap();

    let buf = terminal.backend().buffer().clone();
    let text = buffer_to_string(&buf);
    assert!(
        text.contains("Viewer (Rendered)"),
        "expected 'Viewer (Rendered)' panel title: {text}"
    );
    assert!(
        text.contains("Welcome Heading"),
        "expected rendered markdown heading text in viewer: {text}"
    );
}

#[test]
fn viewer_falls_back_to_diff_when_file_missing() {
    // If the working-tree file can't be read (here: it doesn't exist on disk),
    // toggling the viewer must NOT activate — it surfaces a warning and keeps
    // showing the diff. This guards the "never a blank/stuck pane" invariant.
    let dir = tempfile::tempdir().expect("tempdir");
    // Note: we do NOT create the file, so the read fails.
    let mut app = build_render_test_app_rooted(dir.path().to_path_buf(), "ghost.rs");
    app.toggle_viewer();
    assert!(
        !app.viewer.is_active(),
        "viewer must not activate when the file can't be read"
    );

    let backend = TestBackend::new(80, 24);
    let mut terminal = Terminal::new(backend).unwrap();
    terminal.draw(|f| crate::ui::render(f, &mut app)).unwrap();
    let buf = terminal.backend().buffer().clone();
    let text = buffer_to_string(&buf);
    // Still the diff pane, not a viewer.
    assert!(
        text.contains("Diff ("),
        "expected fallback to the diff pane: {text}"
    );
}

#[test]
fn mcp_indicator_survives_narrow_status_bar() {
    // Regression: the status bar is a single non-wrapping line. On a narrow
    // terminal the verbose keybinding hints used to push the `[mcp:<pid>]`
    // indicator off the right edge. State badges now render before the hints,
    // so the indicator stays visible even when the hints are clipped.
    let mut app = build_render_test_app(vec![make_test_diff_file()]);
    app.mcp_listener.request_on(); // pretend a socket listener is active

    // Deliberately narrow — wide enough for the bar to exist, too narrow to
    // fit both the full hint list and the indicator.
    let backend = TestBackend::new(60, 24);
    let mut terminal = Terminal::new(backend).unwrap();
    terminal.draw(|f| crate::ui::render(f, &mut app)).unwrap();

    let buf = terminal.backend().buffer().clone();
    let text = buffer_to_string(&buf);
    assert!(
        text.contains("[mcp:"),
        "MCP indicator must stay visible on a narrow status bar: {text}"
    );
}