diffler 0.5.0

Terminal code review for AI coding agents
Documentation
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
//! Rendering. `draw` never computes review state; it reads `App` (the diff
//! view additionally fills its lazy highlight cache and follows the cursor
//! with its scroll offset, which is why it takes `&mut App`).

pub mod ci_log;
pub mod diff;
pub mod diff_render;
pub mod graph;
pub mod log;
pub mod popup;
mod prs;
mod runs;
pub mod status;

use diffler_core::model::FileStatus;
use ratatui::Frame;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Paragraph};

use crate::app::{App, BranchAction, Modal, Screen, Severity};
use crate::keymap::{Action, render_chord};
use crate::theme::Theme;
use crate::transient::TransientKind;

/// Split `text` into spans, painting `/`-search match byte ranges with the
/// search background (the active match stronger). Shared by every searchable
/// pane so highlight looks the same everywhere; `ranges` are byte offsets into
/// `text`, paired with whether each is the active match.
pub(super) fn highlight_spans(
    text: &str,
    base: Style,
    ranges: &[(std::ops::Range<usize>, bool)],
    theme: &Theme,
) -> Vec<Span<'static>> {
    if ranges.is_empty() {
        return vec![Span::styled(text.to_owned(), base)];
    }
    let snap = |i: usize| {
        let mut i = i.min(text.len());
        while !text.is_char_boundary(i) {
            i -= 1;
        }
        i
    };
    let mut bounds = vec![0, text.len()];
    for (range, _) in ranges {
        bounds.push(snap(range.start));
        bounds.push(snap(range.end));
    }
    bounds.sort_unstable();
    bounds.dedup();
    let bg_at = |at: usize| {
        ranges
            .iter()
            .find(|(range, _)| snap(range.start) <= at && at < snap(range.end))
            .map(|(_, current)| {
                if *current {
                    theme.search_current
                } else {
                    theme.search
                }
            })
    };
    let mut spans = Vec::new();
    for pair in bounds.windows(2) {
        let &[start, end] = pair else { continue };
        let Some(segment) = text.get(start..end) else {
            continue;
        };
        if segment.is_empty() {
            continue;
        }
        let style = bg_at(start).map_or(base, |bg| base.bg(bg));
        spans.push(Span::styled(segment.to_owned(), style));
    }
    spans
}

/// Shared chrome for the `[hint, body, bar]` screens: paints the full-area
/// background, splits off the hint row and renders it, and hands back the
/// body and bar rects. The bar's own paragraph (content and style both vary
/// per screen) stays with the caller.
pub(super) fn screen_chrome(frame: &mut Frame<'_>, app: &App, hints: &[Hint]) -> (Rect, Rect) {
    let area = frame.area();
    frame.render_widget(Block::new().style(app.theme.base()), area);
    let [hint, body, bar] = Layout::vertical([
        Constraint::Length(1),
        Constraint::Min(0),
        Constraint::Length(1),
    ])
    .areas(area);
    frame.render_widget(Paragraph::new(hint_line(app, hints)), hint);
    (body, bar)
}

/// Like [`screen_chrome`], for screens that carve an extra header row (a
/// provenance/summary line) out from under the hint line.
pub(super) fn screen_chrome_with_header(
    frame: &mut Frame<'_>,
    app: &App,
    hints: &[Hint],
) -> (Rect, Rect, Rect) {
    let area = frame.area();
    frame.render_widget(Block::new().style(app.theme.base()), area);
    let [hint, header, body, bar] = Layout::vertical([
        Constraint::Length(1),
        Constraint::Length(1),
        Constraint::Min(0),
        Constraint::Length(1),
    ])
    .areas(area);
    frame.render_widget(Paragraph::new(hint_line(app, hints)), hint);
    (header, body, bar)
}

pub fn draw(frame: &mut Frame<'_>, app: &mut App) {
    match app.screen() {
        Screen::Status => {
            // enrichment (emphasis/highlight) runs on the blocking pool; this
            // only queues work, and expanded inline diffs render plain until
            // the result lands
            app.queue_enrich_status_expanded();
            status::draw(frame, app);
        }
        Screen::Log => log::draw(frame, app),
        Screen::Diff => diff::draw(frame, app),
        Screen::Graph => graph::draw(frame, app),
        Screen::Runs => runs::draw(frame, app),
        Screen::Prs => prs::draw(frame, app),
        Screen::CiLog => ci_log::draw(frame, app),
    }
    draw_modal(frame, app);
    // the which-key panel is a transient overlay, not a modal: it draws only
    // once the reveal timer has elapsed and never over a modal
    if app.modal.is_none()
        && let Some(transient) = app.which_key_panel()
    {
        popup::WhichKeyPanel { transient }.render(frame, &app.theme);
    }
}

fn draw_modal(frame: &mut Frame<'_>, app: &App) {
    match &app.modal {
        Some(Modal::Confirm { message, .. }) => {
            popup::ConfirmDialog {
                message: message.clone(),
            }
            .render(frame, &app.theme);
        }
        Some(Modal::Input {
            title,
            buffer,
            cursor,
            ..
        }) => {
            popup::InputModal {
                title: title.clone(),
                buffer: buffer.clone(),
                cursor: *cursor,
            }
            .render(frame, &app.theme);
        }
        Some(Modal::Help) => {
            let screen = match app.screen() {
                Screen::Status => "status",
                Screen::Diff => "diff",
                Screen::Log => "log",
                Screen::Graph => "graph",
                Screen::Runs => "runs",
                Screen::Prs => "prs",
                Screen::CiLog => "logs",
            };
            popup::Popup {
                title: format!("Help — {screen} keys"),
                entries: help_entries(app),
            }
            .render(frame, &app.theme);
        }
        Some(Modal::BranchList { .. } | Modal::Comments { .. } | Modal::Palette { .. }) => {
            if let Some(modal) = fuzzy_modal(app) {
                modal.render(frame, &app.theme);
            }
        }
        Some(Modal::ReviewVerdict { number }) => {
            popup::Popup {
                title: format!("Submit review — PR #{number}"),
                entries: vec![
                    ("a".to_owned(), "approve".to_owned()),
                    ("x".to_owned(), "request changes".to_owned()),
                    ("c".to_owned(), "comment only".to_owned()),
                    ("esc".to_owned(), "cancel".to_owned()),
                ],
            }
            .render(frame, &app.theme);
        }
        None => {}
    }
}

fn fuzzy_modal(app: &App) -> Option<popup::FuzzyModal> {
    match &app.modal {
        Some(Modal::BranchList {
            branches,
            list,
            action,
        }) => {
            let title = match action {
                BranchAction::Checkout => "Checkout branch",
                BranchAction::Delete => "Delete branch",
            };
            Some(popup::FuzzyModal {
                title: title.to_owned(),
                query: list.query.clone(),
                cursor: list.cursor,
                items: list
                    .matches
                    .iter()
                    .filter_map(|index| branches.get(*index))
                    .map(|b| {
                        (
                            format!("{} {}", if b.is_head { "*" } else { " " }, b.name),
                            String::new(),
                        )
                    })
                    .collect(),
                selected: list.selected,
                footer: " enter select · tab cycle · esc back ",
            })
        }
        Some(Modal::Comments { entries, list }) => Some(popup::FuzzyModal {
            title: format!("Comments — {}", app.active_review_source().label()),
            query: list.query.clone(),
            cursor: list.cursor,
            items: list
                .matches
                .iter()
                .filter_map(|index| entries.get(*index))
                .map(|e| (e.label.clone(), String::new()))
                .collect(),
            selected: list.selected,
            footer: " enter jump · c-d delete · a-d delete all · esc back ",
        }),
        Some(Modal::Palette { list }) => {
            let commands = app.command_index();
            Some(popup::FuzzyModal {
                title: "Commands".to_owned(),
                query: list.query.clone(),
                cursor: list.cursor,
                items: list
                    .matches
                    .iter()
                    .filter_map(|index| commands.get(*index))
                    .map(|c| (c.label.to_owned(), c.chord.clone()))
                    .collect(),
                selected: list.selected,
                footer: " enter run · tab cycle · esc close ",
            })
        }
        _ => None,
    }
}

/// Help popup entries: the active keymap's leaves, then — on the status
/// screen — each transient's prefix and its grouped sub-keys, so the popup
/// documents the full two-level map.
fn help_entries(app: &App) -> Vec<(String, String)> {
    let keymap = app.active_keymap();
    let mut entries: Vec<(String, String)> = keymap
        .bindings()
        .iter()
        .map(|(chord, action)| (render_chord(chord), action.label().to_owned()))
        .collect();
    if app.screen() == Screen::Status {
        for kind in TransientKind::ALL {
            let Some(prefix) = keymap.prefix_chord(kind) else {
                continue;
            };
            entries.push((prefix, format!("{} …", kind.title())));
            for (key, entry) in app.transient(kind).flat_entries() {
                entries.push((format!("  {key}"), entry.label.to_owned()));
            }
        }
    }
    entries
}

/// Status accent shared by the diff sidebar and the status screen.
pub(super) fn status_color(theme: &Theme, status: FileStatus) -> Color {
    match status {
        FileStatus::Added | FileStatus::Untracked => theme.added,
        FileStatus::Deleted => theme.error_fg,
        FileStatus::Modified | FileStatus::Renamed => theme.warn_fg,
    }
}

/// Theme color for a CI job/run status, shared by the runs list and the inline
/// status section so the palette stays in one place.
pub(super) fn ci_status_color(theme: &Theme, status: crate::ci::JobStatus) -> Color {
    use crate::ci::JobStatus;
    match status {
        JobStatus::Ok => theme.added,
        JobStatus::Failed => theme.error_fg,
        JobStatus::Running => theme.warn_fg,
        JobStatus::Queued | JobStatus::Skipped | JobStatus::Neutral => theme.dim,
    }
}

/// GitHub-style ` +A -B` diffstat spans over `bg`. A zero side is dimmed so it
/// reads as inactive; both-zero yields no spans.
pub(super) fn diffstat_spans(
    theme: &Theme,
    added: usize,
    deleted: usize,
    bg: Color,
) -> Vec<Span<'static>> {
    if added == 0 && deleted == 0 {
        return Vec::new();
    }
    let side = |count: usize, color: Color| {
        let fg = if count == 0 { theme.dim } else { color };
        Style::new().fg(fg).bg(bg)
    };
    vec![
        Span::styled(format!(" +{added}"), side(added, theme.added)),
        Span::styled(format!(" -{deleted}"), side(deleted, theme.error_fg)),
    ]
}

/// A ~5-cell bar split green:red by the added:deleted ratio over `bg`; at least
/// one cell goes to each non-zero side so neither vanishes. Empty with no
/// changes. Shared by the status total and the diff pane header.
pub(super) fn proportion_bar(
    theme: &Theme,
    added: usize,
    deleted: usize,
    bg: Color,
) -> Vec<Span<'static>> {
    const CELLS: usize = 5;
    let total = added + deleted;
    if total == 0 {
        return Vec::new();
    }
    let mut add_cells = (added * CELLS).div_ceil(total).min(CELLS);
    if added > 0 && add_cells == 0 {
        add_cells = 1;
    }
    if deleted > 0 && add_cells == CELLS {
        add_cells = CELLS - 1;
    }
    let del_cells = CELLS - add_cells;
    let mut spans = Vec::new();
    if add_cells > 0 {
        spans.push(Span::styled(
            "â–ˆ".repeat(add_cells),
            Style::new().fg(theme.added).bg(bg),
        ));
    }
    if del_cells > 0 {
        spans.push(Span::styled(
            "â–ˆ".repeat(del_cells),
            Style::new().fg(theme.error_fg).bg(bg),
        ));
    }
    spans
}

/// One hint entry: either leaf actions sharing a label, or a transient prefix.
/// Prefix entries render only the top-level key, keeping the hint line at the
/// prefix altitude (sub-commands live in the which-key panel and help popup).
pub(super) enum Hint {
    Leaf(&'static [Action], &'static str),
    Prefix(TransientKind, &'static str),
}

/// Hint line built from the active keymap so config remaps show. Leaf items
/// whose action lost its key to a remap are dropped; a prefix without a bound
/// key (a dropped conflict) is dropped too.
pub(super) fn hint_line(app: &App, items: &[Hint]) -> Line<'static> {
    let keymap = app.active_keymap();
    let mut parts = Vec::new();
    for item in items {
        match item {
            Hint::Leaf(actions, label) => {
                let chords: Vec<String> = actions
                    .iter()
                    .filter_map(|action| keymap.chord_for(*action))
                    .collect();
                if chords.len() == actions.len() {
                    parts.push(format!("{} {label}", chords.join("/")));
                }
            }
            Hint::Prefix(kind, label) => {
                if let Some(chord) = keymap.prefix_chord(*kind) {
                    parts.push(format!("{chord} {label}"));
                }
            }
        }
    }
    Line::styled(
        format!(" Hint: {}", parts.join("  ")),
        app.theme.dim_style(),
    )
}

/// Repaint a row with the cursor-line background, padded to the full width
/// so the highlight spans the whole row.
/// Compact "time ago" for a commit time, neogit-style: `49s`, `6m`, `21h`,
/// `3d`, `2w`, `5mo`, `1y`. Future times (clock skew) clamp to `0s`.
pub(super) fn relative_time(now: i64, then: i64) -> String {
    let secs = (now - then).max(0);
    let (n, unit) = match secs {
        s if s < 60 => (s, "s"),
        s if s < 3600 => (s / 60, "m"),
        s if s < 86_400 => (s / 3600, "h"),
        s if s < 86_400 * 7 => (s / 86_400, "d"),
        s if s < 86_400 * 30 => (s / (86_400 * 7), "w"),
        s if s < 86_400 * 365 => (s / (86_400 * 30), "mo"),
        s => (s / (86_400 * 365), "y"),
    };
    format!("{n}{unit}")
}

/// Right-aligned author + commit age for a commit row, given the width already
/// used by the row's left content. Empty when there is no room, so the left
/// content (oid, subject) is never pushed off-screen.
pub(super) fn commit_meta_spans(
    theme: &Theme,
    author: &str,
    time_unix: i64,
    now: i64,
    used: usize,
    width: usize,
) -> Vec<Span<'static>> {
    let age = relative_time(now, time_unix);
    let meta_width = author.chars().count() + 2 + age.chars().count() + 1;
    if used + meta_width >= width {
        return Vec::new();
    }
    let pad = width - used - meta_width;
    vec![
        Span::styled(" ".repeat(pad), Style::new().bg(theme.bg)),
        Span::styled(
            author.to_owned(),
            Style::new().fg(theme.accent).bg(theme.bg),
        ),
        Span::styled("  ", Style::new().bg(theme.bg)),
        Span::styled(age, theme.dim_style()),
        Span::styled(" ", Style::new().bg(theme.bg)),
    ]
}

/// Scroll offset that keeps `cursor` inside a `height`-row viewport: pull the
/// top down to the cursor when it scrolls above, push it up when below. Shared
/// by every row-list pane so scrolling behaves identically.
pub(super) fn scroll_to_cursor(cursor: usize, scroll: usize, height: usize) -> usize {
    if cursor < scroll {
        cursor
    } else if cursor >= scroll + height {
        cursor + 1 - height
    } else {
        scroll
    }
}

/// Truncate to `max` graphemes with an ellipsis. Shared by the runs list and
/// the status screen's inline CI section, which both fit run metadata into
/// fixed-width columns.
pub(super) fn elide(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        s.to_owned()
    } else {
        let kept: String = s.chars().take(max.saturating_sub(1)).collect();
        format!("{kept}…")
    }
}

pub(super) fn cursor_line(line: Line<'static>, theme: &Theme, width: u16) -> Line<'static> {
    let pad = (width as usize).saturating_sub(line.width());
    let mut spans: Vec<Span<'static>> = line
        .spans
        .into_iter()
        .map(|span| {
            let style = span.style.bg(theme.cursor_line);
            Span::styled(span.content, style)
        })
        .collect();
    if pad > 0 {
        spans.push(Span::styled(
            " ".repeat(pad),
            Style::new().bg(theme.cursor_line),
        ));
    }
    Line::from(spans)
}

/// Bottom bar shared by every screen: mode chip, repo@branch, MCP state,
/// viewed counts, and the transient message.
pub(super) fn status_bar(app: &App, width: u16) -> Line<'static> {
    let theme = &app.theme;
    let on_panel = |fg| Style::new().fg(fg).bg(theme.panel);
    // the chip is the mode indicator: a forge-backed review must read
    // differently from a local one, so the PR source names itself
    let chip = match app.screen() {
        Screen::Status => " STATUS ".to_owned(),
        Screen::Diff => match app.diff.as_ref().map(|d| &d.source) {
            Some(source @ diffler_core::source::ReviewSource::Pr { number }) => {
                let pending = app
                    .review
                    .session_for(source)
                    .comments
                    .iter()
                    .filter(|c| c.remote_id.is_none())
                    .count();
                if pending == 0 {
                    format!(" PR #{number} ")
                } else {
                    format!(" PR #{number} · {pending} pending ")
                }
            }
            _ => " DIFF ".to_owned(),
        },
        Screen::Log => " LOG ".to_owned(),
        Screen::Graph => " GRAPH ".to_owned(),
        Screen::Runs => " RUNS ".to_owned(),
        Screen::Prs => " PRS ".to_owned(),
        Screen::CiLog => " LOGS ".to_owned(),
    };
    let repo = app
        .review
        .repo_root
        .file_name()
        .map(|name| name.to_string_lossy().into_owned())
        .unwrap_or_default();
    let branch = app.head.branch.clone().unwrap_or_else(|| "?".to_owned());
    let mut spans = vec![
        Span::styled(chip, theme.chip),
        Span::styled(format!(" {repo}@{branch}"), on_panel(theme.fg)),
    ];
    if let Some(port) = app.mcp_port {
        spans.push(Span::styled(format!("  mcp :{port}"), on_panel(theme.dim)));
    } else if app.config.mcp.enabled {
        // server is configured but not yet bound (or failed)
        spans.push(Span::styled("  mcp off", on_panel(theme.dim)));
    }
    if app.refresh_flash > 0 {
        spans.push(Span::styled("  ↻", on_panel(theme.dim)));
    }
    let (files, viewed) = app.viewed_counts();
    if files > 0 {
        // the diff view is the review walk, so its counter reads as progress
        let text = if app.screen() == Screen::Diff {
            format!("  viewed {viewed}/{files} files")
        } else {
            let noun = if files == 1 { "file" } else { "files" };
            format!("  {files} {noun}, {viewed} viewed")
        };
        spans.push(Span::styled(text, on_panel(theme.dim)));
    }
    if let Some(search) = &app.search {
        let (i, n) = search.count();
        let count = if n == 0 {
            "  [no match]".to_owned()
        } else {
            format!("  [{i}/{n}]")
        };
        spans.push(Span::styled(
            format!("  /{}", search.query()),
            on_panel(theme.accent),
        ));
        spans.push(Span::styled(count, on_panel(theme.dim)));
    } else if let Some(message) = &app.message {
        let fg = match message.severity {
            Severity::Info => theme.dim,
            Severity::Warning => theme.warn_fg,
            Severity::Error => theme.error_fg,
        };
        let used: usize = spans.iter().map(Span::width).sum();
        let text = format!("{} ", message.text);
        let pad = (width as usize).saturating_sub(used + text.len());
        if pad > 0 {
            spans.push(Span::styled(" ".repeat(pad), on_panel(theme.fg)));
        } else {
            spans.push(Span::styled("  ", on_panel(theme.fg)));
        }
        spans.push(Span::styled(text, on_panel(fg)));
    }
    Line::from(spans)
}

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

    #[test]
    fn the_chip_names_the_pr_when_reviewing_one() {
        use crate::app::App;
        use crate::config::LoadedConfig;
        use crate::test_support::standard_fixture;

        let fixture = standard_fixture();
        let mut app = App::new(fixture.review(), LoadedConfig::default());
        let head = app.review.vcs.resolve("HEAD").expect("head");
        app.open_pr_diff(7, &head, &head);
        let bar = super::status_bar(&app, 80);
        let text: String = bar.spans.iter().map(|s| s.content.clone()).collect();
        assert!(text.contains(" PR #7 "), "{text}");
    }

    #[test]
    fn relative_time_picks_a_compact_unit() {
        let now = 1_000_000;
        assert_eq!(relative_time(now, now), "0s");
        assert_eq!(relative_time(now, now - 49), "49s");
        assert_eq!(relative_time(now, now - 6 * 60), "6m");
        assert_eq!(relative_time(now, now - 21 * 3600), "21h");
        assert_eq!(relative_time(now, now - 3 * 86_400), "3d");
        assert_eq!(relative_time(now, now - 2 * 7 * 86_400), "2w");
        assert_eq!(relative_time(now, now - 90 * 86_400), "3mo");
        assert_eq!(relative_time(now, now - 800 * 86_400), "2y");
        // future commit times (clock skew) clamp to 0s, never negative
        assert_eq!(relative_time(now, now + 500), "0s");
    }
}