dv-review 0.3.0

A terminal diff viewer for reviewing GitHub PRs: Helix keys, rust-analyzer, inline review comments, and Claude Code reviews
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
//! `dv list`: the repo's open PRs, and (`Tab`) the ones with a local worktree; `Enter` reviews
//! one, and quitting that review comes back here.
use crate::gh::{self, Listed};
use crate::theme::{Theme, Ui};
use anyhow::Result;
use ratatui::crossterm::event::{self, Event, KeyCode, KeyEvent, KeyEventKind, KeyModifiers};
use ratatui::layout::{Alignment, Rect};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Clear, Paragraph};
use ratatui::{DefaultTerminal, Frame};
use crate::batch;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::sync::mpsc::{self, Receiver};
use std::time::Duration;

type Checks = anyhow::Result<HashMap<u64, (usize, usize, usize)>>;

const HELP: &str = "\
  j k, Up Down         move
  gg ge                first / last PR
  Ctrl-d Ctrl-u        half a page down / up
  Tab                  open PRs / PRs with a local worktree (<repo>-N, as dv N -w makes)
  Enter                review the PR (with dv list's flags; from the worktrees tab, in its
                       worktree as it was made); q there comes back here
  /                    filter (Enter keeps it, Esc clears it); terms must all match:
                         text            number, title, author, branch, labels
                         author: label: base: branch:   part of that field
                         is:draft  review:approved|changes|required|none
                         ci:pass|fail|pending|none     -term excludes
  Esc                  clear the filter
  o O                  next sort order (updated, created, number, size) / reverse
  m                    mark the PR (again: unmark), for Claude to review
  a a                  Claude reviews the marked PRs (or this one) in the background, two at a
                       time, each in its worktree (<repo>-N, made if need be); cards show how
                       it's going, and claude ✓ once a PR has a review
  D D                  worktrees tab: remove the PR's worktree (not with local changes in it;
                       its branch stays)
  R                    refresh
  ?                    this help
  q, Ctrl-c            quit";

pub struct List {
    prs: Vec<Listed>,
    ui: Ui,
    /// Flags each PR opens with, for the status bar (e.g. "-wb").
    flags: String,
    sel: usize,
    top: usize,
    query: String,
    /// Typing a `/` filter (Enter keeps it, Esc clears it).
    filtering: bool,
    pending_g: bool,
    help: bool,
    order: Order,
    /// Oldest / smallest / lowest first instead.
    rev: bool,
    /// CI check counts, still on their way (they take a few seconds for a busy repo).
    checks: Option<Receiver<Checks>>,
    /// PR worktrees: number → (dir, branch or `None` when detached).
    local: HashMap<u64, (PathBuf, Option<String>)>,
    /// Showing the worktrees tab.
    worktrees: bool,
    /// A key that asks to be pressed again (`D` on this PR's worktree, `a`, `q`): any other
    /// key calls it off.
    confirm: Option<(char, u64)>,
    /// PRs marked (`m`) for Claude to review.
    marked: HashSet<u64>,
    /// Claude's reviews from here (`a`): how each is going, and the news on its way.
    batch: HashMap<u64, batch::Status>,
    batch_rx: Option<Receiver<(u64, batch::Status)>>,
    /// PRs Claude has a review of.
    reviewed: HashSet<u64>,
    /// The repo, for the reviews' worktrees.
    root: PathBuf,
    pub msg: String,
}

/// What was picked: the PR, and for one from the worktrees tab, whether its worktree is on
/// its branch (it opens there, as `dv N -w` / `-wb`).
pub struct Pick {
    pub number: u64,
    pub worktree: Option<bool>,
}

impl List {
    pub fn new(flags: String) -> List {
        let ui = Theme::load().ui();
        let (query, msg) = (String::new(), String::new());
        List {
            prs: vec![],
            ui,
            flags,
            sel: 0,
            top: 0,
            query,
            filtering: false,
            pending_g: false,
            help: false,
            order: Order::Updated,
            rev: false,
            checks: None,
            local: HashMap::new(),
            worktrees: false,
            confirm: None,
            marked: HashSet::new(),
            batch: HashMap::new(),
            batch_rx: None,
            reviewed: HashSet::new(),
            root: std::env::current_dir().unwrap_or_default(),
            msg,
        }
    }

    /// Show the list until a PR is picked (`Some`) or the user quits (`None`).
    pub fn run(&mut self, term: &mut DefaultTerminal) -> Result<Option<Pick>> {
        if self.prs.is_empty() {
            self.refresh(term)?;
        }
        loop {
            term.draw(|f| self.draw(f))?;
            self.batch_news();
            if let Some(Ok(res)) = self.checks.as_ref().map(Receiver::try_recv) {
                self.checks = None;
                match res {
                    Ok(by_pr) => self.prs.iter_mut().for_each(|p| p.checks = by_pr.get(&p.number).copied()),
                    Err(e) => self.msg = format!("checks: {e:#}"),
                }
            }
            if !event::poll(Duration::from_millis(100))? {
                continue;
            }
            let k = match event::read()? {
                Event::Key(k) if k.kind == KeyEventKind::Press => k,
                Event::Mouse(m) => match self.mouse(m) {
                    // A click on the selected card opens it, as Enter.
                    true => KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE),
                    false => continue,
                },
                _ => continue,
            };
            match self.key(k) {
                Some(Do::Quit) => return Ok(None),
                Some(Do::Open(n)) => {
                    let worktree = self.worktrees.then(|| self.local.get(&n).is_some_and(|w| w.1.is_some()));
                    return Ok(Some(Pick { number: n, worktree }));
                }
                Some(Do::Refresh) => self.refresh(term)?,
                Some(Do::Review(prs)) => {
                    let on_branch = |n| self.local.get(&n).is_some_and(|w| w.1.is_some());
                    let prs: Vec<(u64, bool)> = prs.into_iter().map(|n| (n, on_branch(n))).collect();
                    self.msg = format!("Claude is reviewing {} PR(s), {} at a time", prs.len(), batch::AT_ONCE);
                    self.marked.clear();
                    self.batch_rx = Some(batch::start(prs, self.root.clone()));
                }
                Some(Do::Remove(n)) => {
                    self.msg = match crate::remove_worktree(n, false) {
                        Ok(m) => {
                            self.local.remove(&n);
                            // Listed only for its worktree (closed, merged): gone with it.
                            self.prs.retain(|p| p.number != n || p.state == "OPEN" || p.state.is_empty());
                            self.sel = self.sel.min(self.shown().len().saturating_sub(1));
                            m
                        }
                        Err(e) => format!("{e:#}"),
                    }
                }
                None => {}
            }
        }
    }

    /// How Claude's reviews are going: each card shows it; one finished counts as reviewed.
    fn batch_news(&mut self) {
        let Some(rx) = &self.batch_rx else { return };
        let news: Vec<(u64, batch::Status)> = rx.try_iter().collect();
        let mut worktrees = false;
        for (n, s) in news {
            match &s {
                batch::Status::Done(took) => {
                    self.reviewed.insert(n);
                    self.msg = format!("Claude reviewed #{n} ({took}): Enter opens it, in its worktree from the worktrees tab");
                }
                batch::Status::Failed(e) => self.msg = format!("Claude's review of #{n}: {e}"),
                batch::Status::Reviewing => worktrees = true, // its worktree is ready
                _ => {}
            }
            self.batch.insert(n, s);
        }
        if worktrees {
            self.local = crate::pr_worktrees().into_iter().map(|(n, dir, b)| (n, (dir, b))).collect();
        }
    }

    fn refresh(&mut self, term: &mut DefaultTerminal) -> Result<()> {
        self.msg = "loading PRs…".into();
        term.draw(|f| self.draw(f))?;
        let keep = self.shown().get(self.sel).map(|p| p.number);
        self.local = crate::pr_worktrees().into_iter().map(|(n, dir, b)| (n, (dir, b))).collect();
        self.reviewed = crate::batch::reviewed();
        match gh::list() {
            Ok(mut prs) => {
                let (tx, rx) = mpsc::channel();
                std::thread::spawn(move || tx.send(gh::list_checks()));
                self.checks = Some(rx);
                self.msg = if prs.is_empty() { "no open PRs".into() } else { String::new() };
                // Worktrees of PRs that aren't open any more (or beyond the list): fetch those few.
                let mut gone: Vec<u64> = self.local.keys().filter(|n| !prs.iter().any(|p| p.number == **n)).copied().collect();
                gone.sort();
                for n in gone {
                    let title = "(couldn't load this PR)".into();
                    prs.push(gh::listed_one(n).unwrap_or(Listed { number: n, title, ..Listed::default() }));
                }
                self.prs = prs;
                self.sel = keep.and_then(|n| self.shown().iter().position(|p| p.number == n)).unwrap_or(0);
            }
            Err(e) => self.msg = format!("{e:#}"),
        }
        Ok(())
    }

    /// The tab's PRs matching every filter term, in the chosen order.
    fn shown(&self) -> Vec<&Listed> {
        let in_tab = |p: &&Listed| match self.worktrees {
            true => self.local.contains_key(&p.number),
            false => p.state == "OPEN" || p.state.is_empty(),
        };
        let mut prs: Vec<&Listed> =
            self.prs.iter().filter(in_tab).filter(|p| self.query.split_whitespace().all(|t| term(p, t))).collect();
        prs.sort_by(|a, b| {
            let o = match self.order {
                Order::Updated => b.updated.cmp(&a.updated), // ISO times sort as text
                Order::Created => b.created.cmp(&a.created),
                Order::Number => b.number.cmp(&a.number),
                Order::Size => (b.additions + b.deletions).cmp(&(a.additions + a.deletions)),
            };
            if self.rev { o.reverse() } else { o }
        });
        prs
    }

    /// Change the order, keeping the selected PR selected.
    fn sort(&mut self, order: Order, rev: bool) {
        let keep = self.shown().get(self.sel).map(|p| p.number);
        (self.order, self.rev) = (order, rev);
        self.sel = keep.and_then(|n| self.shown().iter().position(|p| p.number == n)).unwrap_or(0);
    }

    fn key(&mut self, k: KeyEvent) -> Option<Do> {
        let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
        if ctrl && k.code == KeyCode::Char('c') {
            return Some(Do::Quit);
        }
        let n = self.shown().len();
        self.msg.clear();
        let armed = self.confirm.take();
        if std::mem::take(&mut self.help) {
            return None; // any key closes the help
        }
        if self.filtering {
            match k.code {
                KeyCode::Esc => (self.query.clear(), self.filtering = false).1,
                KeyCode::Enter => self.filtering = false,
                KeyCode::Backspace => _ = self.query.pop(),
                KeyCode::Char(c) => self.query.push(c),
                _ => {}
            }
            self.sel = 0;
            return None;
        }
        let half = (self.height() / 2).max(1);
        let g = std::mem::take(&mut self.pending_g);
        match k.code {
            // A filter that's just a number opens that PR, listed or not (older, or closed).
            KeyCode::Enter => {
                let typed = self.query.trim().trim_start_matches('#').parse().ok();
                return self.shown().get(self.sel).map(|p| p.number).or(typed).map(Do::Open);
            }
            KeyCode::Esc if !self.query.is_empty() => (self.query.clear(), self.sel = 0).1,
            // Reviews running: they'd stop with dv (the ones started finish; queued ones don't start).
            KeyCode::Char('q') | KeyCode::Esc if self.batch.values().any(batch::Status::running) && armed != Some(('q', 0)) => {
                self.msg = "Claude is still reviewing: q again quits (reviews under way finish; queued ones don't start)".into();
                self.confirm = Some(('q', 0));
            }
            KeyCode::Char('q') | KeyCode::Esc => return Some(Do::Quit),
            KeyCode::Char('R') => return Some(Do::Refresh),
            KeyCode::Char('D') if self.worktrees => {
                let p = self.shown().get(self.sel).map(|p| p.number)?;
                let (dir, _) = self.local.get(&p)?;
                if armed == Some(('D', p)) {
                    return Some(Do::Remove(p));
                }
                self.msg = format!("D again removes {} (its branch stays); any other key keeps it", dir.display());
                self.confirm = Some(('D', p));
            }
            KeyCode::Char('m') => {
                let p = self.shown().get(self.sel).map(|p| p.number)?;
                if !self.marked.remove(&p) {
                    self.marked.insert(p);
                }
                self.sel = (self.sel + 1).min(n.saturating_sub(1)); // on to the next, to mark a run
                self.msg = format!("{} marked: a asks Claude to review them", self.marked.len());
            }
            KeyCode::Char('a') => {
                let mut prs: Vec<u64> = match self.marked.is_empty() {
                    true => self.shown().get(self.sel).map(|p| vec![p.number]).unwrap_or_default(),
                    false => self.marked.iter().copied().collect(),
                };
                prs.retain(|n| !self.batch.get(n).is_some_and(batch::Status::running));
                prs.sort();
                if prs.is_empty() {
                    return None;
                }
                if armed == Some(('a', 0)) {
                    return Some(Do::Review(prs));
                }
                let which = prs.iter().map(|n| format!("#{n}")).collect::<Vec<_>>().join(" ");
                self.msg = format!("a again: Claude reviews {which} in the background, each in its worktree (<repo>-N)");
                self.confirm = Some(('a', 0));
            }
            KeyCode::Char('?') => self.help = true,
            KeyCode::Tab | KeyCode::BackTab => (self.worktrees, self.sel, self.top) = (!self.worktrees, 0, 0),
            KeyCode::Char('/') => self.filtering = true, // edits the current filter
            KeyCode::Char('o') => self.sort(self.order.next(), self.rev),
            KeyCode::Char('O') => self.sort(self.order, !self.rev),
            KeyCode::Char('d') if ctrl => self.sel = (self.sel + half).min(n.saturating_sub(1)),
            KeyCode::Char('u') if ctrl => self.sel = self.sel.saturating_sub(half),
            KeyCode::Char('j') | KeyCode::Down => self.sel = (self.sel + 1).min(n.saturating_sub(1)),
            KeyCode::Char('k') | KeyCode::Up => self.sel = self.sel.saturating_sub(1),
            KeyCode::Char('g') if g => self.sel = 0,
            KeyCode::Char('e') if g => self.sel = n.saturating_sub(1),
            KeyCode::Char('g') => self.pending_g = true,
            _ => {}
        }
        None
    }

    /// The wheel moves the selection; a click selects a card, and on the selected one opens it
    /// (`true`: open).
    fn mouse(&mut self, m: event::MouseEvent) -> bool {
        use event::{MouseButton, MouseEventKind};
        let n = self.shown().len();
        match m.kind {
            MouseEventKind::ScrollDown => self.sel = (self.sel + 1).min(n.saturating_sub(1)),
            MouseEventKind::ScrollUp => self.sel = self.sel.saturating_sub(1),
            MouseEventKind::Down(MouseButton::Left) if !self.help && m.row >= 1 => {
                let i = self.top + (m.row as usize - 1) / 2; // cards start under the header, 2 rows each
                if i < n {
                    if i == self.sel {
                        return true;
                    }
                    self.sel = i;
                }
            }
            _ => {}
        }
        false
    }

    /// Cards on screen (2 rows each, between the header and the status bar).
    fn height(&self) -> usize {
        ratatui::crossterm::terminal::size().map_or(10, |(_, h)| h.saturating_sub(2) as usize / 2)
    }

    fn draw(&mut self, f: &mut Frame) {
        let area = f.area();
        let h = area.height.saturating_sub(2) as usize / 2;
        let sel = self.sel.min(self.shown().len().saturating_sub(1));
        // Keep the selection on screen.
        (self.sel, self.top) = (sel, self.top.min(sel).max((sel + 1).saturating_sub(h)));
        let (ui, shown) = (&self.ui, self.shown());
        f.render_widget(Paragraph::new("").style(ui.base), area);

        let head = Rect { height: 1.min(area.height), ..area };
        let hs = ui.base.patch(ui.header);
        let arrow = if self.rev { '↑' } else { '↓' };
        // Tabs: the current one bold, with counts.
        let open = self.prs.iter().filter(|p| p.state == "OPEN" || p.state.is_empty()).count();
        let tab = |name: String, on: bool| Span::styled(name, if on { hs.add_modifier(ratatui::style::Modifier::BOLD | ratatui::style::Modifier::UNDERLINED) } else { hs.patch(ui.stale) });
        let tabs = Line::from(vec![
            Span::styled(" ", hs),
            tab(format!("open {open}{}", if self.prs.len() >= gh::LIST_MAX { "+" } else { "" }), !self.worktrees),
            Span::styled("  ", hs),
            tab(format!("worktrees {}", self.local.len()), self.worktrees),
            Span::styled(format!("   by {} {arrow}  (Tab switches)", self.order.name()), hs.patch(ui.stale)),
        ]);
        f.render_widget(Paragraph::new(tabs).style(hs), head);
        let pos = if shown.is_empty() { "0 / 0 ".into() } else { format!("{} / {} ", sel + 1, shown.len()) };
        f.render_widget(Paragraph::new(pos).alignment(Alignment::Right).style(hs), head);

        // The base most PRs target goes without saying; others show as "base ← branch".
        let mut bases: HashMap<&str, usize> = HashMap::new();
        self.prs.iter().for_each(|p| *bases.entry(p.base.as_str()).or_default() += 1);
        let usual = bases.into_iter().max_by_key(|b| b.1).map(|b| b.0.to_owned()).unwrap_or_default();
        let cx = Cards {
            ui,
            num_w: shown.iter().map(|p| p.number.to_string().len()).max().unwrap_or(1) + 1,
            width: area.width as usize,
            checks_loading: self.checks.is_some(),
            usual: &usual,
        };
        let lines: Vec<Line> = shown
            .iter()
            .enumerate()
            .skip(self.top)
            .take(h)
            .flat_map(|(i, p)| {
                let mark = Mark { marked: self.marked.contains(&p.number), claude: self.claude_state(p.number) };
                card(p, &cx, i == sel, self.local.get(&p.number), mark)
            })
            .collect();
        let typed = self.query.trim().trim_start_matches('#').parse::<u64>().ok();
        let none = match (self.worktrees, self.query.is_empty(), typed) {
            (true, true, _) => " no PR worktrees here yet: `dv N -w` (or dv list -w, then Enter) makes one".into(),
            (_, _, Some(n)) => format!(" #{n} isn't listed: Enter opens it anyway"),
            _ => String::new(),
        };
        if shown.is_empty() {
            f.render_widget(Paragraph::new(none).style(ui.base.patch(ui.stale)), Rect { y: area.y + 2, height: 1, ..area });
        }
        f.render_widget(Paragraph::new(lines), Rect { y: area.y + 1, height: (h * 2) as u16, ..area });

        let status = Rect { y: area.bottom().saturating_sub(1), height: 1.min(area.height), ..area };
        let bar = ui.base.patch(ui.status);
        let left = match (self.filtering, self.query.is_empty(), self.msg.is_empty()) {
            (true, _, _) => format!(" /{}▏  author: label: base: branch: is:draft review: ci:  -x negates", self.query),
            (_, _, false) => format!(" {}", self.msg),
            (_, false, _) => format!(" filter: {}  (Esc clears)", self.query),
            _ => String::new(), // the keys are in the bottom-right popup
        };
        let flags = if self.flags.is_empty() { String::new() } else { format!("opens with {}  ", self.flags) };
        f.render_widget(Paragraph::new(left).style(bar), status);
        f.render_widget(Paragraph::new(flags).alignment(Alignment::Right).style(bar), status);
        if !self.help && !self.filtering {
            // The keys for this tab, bottom right, as dv's diff view shows them.
            let enter = match self.worktrees {
                true => "review, in its worktree".to_owned(),
                false if self.flags.is_empty() => "review".to_owned(),
                false => format!("review (dv N {})", self.flags),
            };
            let tab = if self.worktrees { "open PRs" } else { "PRs with a worktree" };
            let keys = [("Enter", enter.as_str()), ("Tab", tab), ("/", "filter"), ("o O", "sort / reverse"), ("R", "refresh"), ("m", "mark"), ("a a", "Claude reviews marked"), ("D D", "remove worktree"), ("?", "all keys"), ("q", "quit")];
            let lines: Vec<Line> = keys
                .iter()
                .filter(|(k, _)| self.worktrees || *k != "D D")
                .map(|(k, d)| Line::from(vec![Span::styled(format!("{k:<6}"), ui.key), Span::raw(d.to_string())]))
                .collect();
            let w = (lines.iter().map(Line::width).max().unwrap_or(10) as u16 + 4).min(area.width);
            let h = (lines.len() as u16 + 2).min(area.height.saturating_sub(1));
            let r = Rect { x: area.width - w, y: area.height.saturating_sub(1 + h), width: w, height: h };
            f.render_widget(Clear, r);
            f.render_widget(Block::new().style(ui.base.patch(ui.popup)), r);
            f.render_widget(Paragraph::new(" keys").style(ui.base.patch(ui.header)), Rect { height: 1, ..r });
            f.render_widget(Paragraph::new(lines), Rect { x: r.x + 1, y: r.y + 1, width: w.saturating_sub(2), height: h.saturating_sub(1) });
        }
        if self.help {
            // Like dv's popups: no border, the popup background, a header row.
            let lines: Vec<&str> = HELP.lines().collect();
            let w = (lines.iter().map(|l| l.chars().count()).max().unwrap_or(0) as u16 + 4).min(area.width);
            let h = (lines.len() as u16 + 3).min(area.height);
            let r = Rect { x: (area.width - w) / 2, y: (area.height - h) / 2, width: w, height: h };
            f.render_widget(Clear, r);
            f.render_widget(Block::new().style(ui.base.patch(ui.popup)), r);
            let hs = ui.base.patch(ui.header);
            f.render_widget(Paragraph::new(" dv list keys").style(hs), Rect { height: 1, ..r });
            f.render_widget(Paragraph::new("any key closes ").alignment(Alignment::Right).style(hs), Rect { height: 1, ..r });
            let body: Vec<Line> = lines
                .iter()
                .map(|l| {
                    let (k, d) = l.split_at(l.char_indices().nth(23).map_or(l.len(), |(i, _)| i));
                    Line::from(vec![Span::styled(k.to_owned(), ui.key), Span::raw(d.to_owned())])
                })
                .collect();
            f.render_widget(Paragraph::new(body), Rect { x: r.x + 1, y: r.y + 2, width: r.width.saturating_sub(2), height: h.saturating_sub(3) });
        }
    }
}

enum Do {
    Quit,
    Open(u64),
    Refresh,
    /// Remove this PR's worktree.
    Remove(u64),
    /// Have Claude review these PRs, in the background.
    Review(Vec<u64>),
}

/// A card's own marks: picked for review (`m`), and how Claude's review of it stands.
struct Mark {
    marked: bool,
    claude: Option<(String, bool)>,
}

impl List {
    /// What a card says about Claude's review: ("claude ✓", good) or ("claude: reviewing…", …).
    fn claude_state(&self, n: u64) -> Option<(String, bool)> {
        match self.batch.get(&n) {
            Some(batch::Status::Queued) => Some(("claude: queued".into(), true)),
            Some(batch::Status::Preparing) => Some(("claude: checking out…".into(), true)),
            Some(batch::Status::Reviewing) => Some(("claude: reviewing…".into(), true)),
            Some(batch::Status::Failed(_)) => Some(("claude: failed".into(), false)),
            _ if self.reviewed.contains(&n) => Some(("claude ✓".into(), true)),
            _ => None,
        }
    }
}

/// What every card on screen shares.
struct Cards<'a> {
    ui: &'a Ui,
    num_w: usize,
    width: usize,
    checks_loading: bool,
    /// The base most PRs target, left unsaid.
    usual: &'a str,
}

/// A PR as two lines: number, title, state / draft badge and age; then who, CI, review, size,
/// labels, branches and its worktree, most useful first so a narrow screen cuts the least useful.
fn card(p: &Listed, cx: &Cards, selected: bool, local: Option<&(PathBuf, Option<String>)>, mark: Mark) -> [Line<'static>; 2] {
    let (ui, num_w, width, usual) = (cx.ui, cx.num_w, cx.width, cx.usual);
    let row = if selected { ui.base.patch(ui.menu_selected) } else { ui.base };
    let dim = row.patch(ui.stale);
    let sp = |t: String, st| Span::styled(t, st);
    let age = format!("{} ", gh::ago(&p.updated));
    // Closed / merged (only in the worktrees tab), else draft, as GitHub colors them.
    let badge = match (p.state.as_str(), p.draft) {
        ("MERGED", _) => Some(("MERGED", "8957e5")),
        ("CLOSED", _) => Some(("CLOSED", "da3633")),
        (_, true) => Some(("DRAFT", "6e7681")),
        _ => None,
    };
    let room = width.saturating_sub(num_w + 3 + badge.map_or(0, |b| b.0.len() + 4) + age.len()).max(10);
    let mut top = vec![
        sp(format!("{}{:>num_w$} ", if mark.marked { "●" } else { " " }, format!("#{}", p.number)), row.patch(ui.key)),
        sp(cut(&p.title, room), row),
    ];
    if let Some((text, color)) = badge {
        top.extend([sp("  ".into(), row), sp(format!(" {text} "), crate::view::chip(color))]);
    }
    let used: usize = top.iter().map(Span::width).sum();
    top.push(sp(format!("{age:>w$}", w = width.saturating_sub(used)), dim));

    let sep = || sp(" · ".into(), dim);
    let mut bottom = vec![sp(" ".repeat(num_w + 2), row), sp(format!("@{}", p.author), dim)];
    match p.checks {
        Some((0, 0, 0)) => {}
        Some((pass, fail, pending)) => {
            let counts = [(pass, '✓', ui.plus), (fail, '✗', ui.error), (pending, '●', ui.warning)];
            for (k, &(n, mark, st)) in counts.iter().filter(|c| c.0 > 0).enumerate() {
                bottom.extend([sp(if k == 0 { " · " } else { " " }.into(), dim), sp(format!("{mark}{n}"), row.patch(st))]);
            }
        }
        None if cx.checks_loading => bottom.extend([sep(), sp("checks…".into(), dim)]),
        None => {}
    }
    match p.decision.as_str() {
        "APPROVED" => bottom.extend([sep(), sp("✓ approved".into(), row.patch(ui.plus))]),
        "CHANGES_REQUESTED" => bottom.extend([sep(), sp("✗ changes requested".into(), row.patch(ui.error))]),
        _ => {}
    }
    bottom.extend([
        sep(),
        sp(format!("+{}", p.additions), row.patch(ui.plus)),
        sp(" ".into(), row),
        sp(format!("−{}", p.deletions), row.patch(ui.minus)),
        sp(format!(" in {} file{}", p.files, if p.files == 1 { "" } else { "s" }), dim),
    ]);
    for (name, color) in &p.labels {
        bottom.extend([sp(" ".into(), row), sp(format!(" {name} "), crate::view::chip(color))]);
    }
    let branch = match p.base == usual {
        true => cut(&p.branch, 32),
        false => format!("{} ← {}", p.base, cut(&p.branch, 32)),
    };
    if let Some((text, ok)) = mark.claude {
        bottom.extend([sep(), sp(text, row.patch(if ok { ui.key } else { ui.error }))]);
    }
    bottom.extend([sep(), sp(branch, dim)]);
    if let Some((dir, branch)) = local {
        let name = dir.file_name().map_or(String::new(), |n| n.to_string_lossy().into_owned());
        let on = branch.as_deref().map_or("detached".to_owned(), |b| format!("on {}", cut(b, 24)));
        bottom.extend([sep(), sp(format!("⌂ {name} ({on})"), row.patch(ui.key))]);
    }
    [Line::from(top).style(row), Line::from(bottom).style(row)]
}

/// `s` cut to `n` chars, ending in `…` if it was longer.
fn cut(s: &str, n: usize) -> String {
    match s.chars().count() > n {
        true => format!("{}…", s.chars().take(n.saturating_sub(1)).collect::<String>()),
        false => s.to_owned(),
    }
}

#[derive(Clone, Copy)]
enum Order {
    Updated,
    Created,
    Number,
    Size,
}

impl Order {
    fn next(self) -> Order {
        match self {
            Order::Updated => Order::Created,
            Order::Created => Order::Number,
            Order::Number => Order::Size,
            Order::Size => Order::Updated,
        }
    }

    fn name(self) -> &'static str {
        match self {
            Order::Updated => "updated",
            Order::Created => "created",
            Order::Number => "number",
            Order::Size => "size",
        }
    }
}

/// One filter term, GitHub-search style: `author:` `label:` `base:` `branch:` (substring),
/// `is:draft`, `review:approved|changes|required|none`, `ci:pass|fail|pending|none`, else text
/// in the number, title, author, branch or labels. `-` negates. Smart case.
fn term(p: &Listed, t: &str) -> bool {
    let (neg, t) = match t.strip_prefix('-') {
        Some(rest) if !rest.is_empty() => (true, rest),
        _ => (false, t),
    };
    let fold = |s: &str| if t.chars().any(char::is_uppercase) { s.to_owned() } else { s.to_lowercase() };
    let has = |field: &str, v: &str| fold(field).contains(v);
    let labels = || p.labels.iter().map(|l| l.0.as_str()).collect::<Vec<_>>().join(" ");
    let hit = match t.split_once(':') {
        Some(("author", v)) => has(&p.author, v),
        Some(("label", v)) => p.labels.iter().any(|l| has(&l.0, v)),
        Some(("base", v)) => has(&p.base, v),
        Some(("branch", v)) => has(&p.branch, v),
        Some(("is", "draft")) => p.draft,
        Some(("review", v)) => match p.decision.as_str() {
            "APPROVED" => "approved".starts_with(v),
            "CHANGES_REQUESTED" => "changes".starts_with(v),
            "REVIEW_REQUIRED" => "required".starts_with(v),
            _ => v == "none",
        },
        // Unknown until the checks arrive; then a PR can match several (fail and pending).
        Some(("ci", v)) => match p.checks {
            Some((0, 0, 0)) | None => v == "none",
            Some((pass, fail, pending)) => {
                ("pass".starts_with(v) && pass > 0 && fail == 0 && pending == 0)
                    || ("fail".starts_with(v) && fail > 0)
                    || ("pending".starts_with(v) && pending > 0)
            }
        },
        _ => has(&format!("#{} {} @{} {} {}", p.number, p.title, p.author, p.branch, labels()), t),
    };
    hit != neg
}

#[test]
fn filter_and_keys() {
    let pr = |number, title: &str, author: &str, updated: &str| Listed {
        number,
        title: title.into(),
        author: author.into(),
        base: "master".into(),
        branch: "b".into(),
        state: "OPEN".into(),
        updated: updated.into(),
        additions: number,
        files: 1,
        ..Listed::default()
    };
    let mut l = List::new("-wb".into());
    l.prs = vec![pr(1, "Fix CI", "ann", "2026-03"), pr(22, "Add docs", "bo", "2026-01"), pr(333, "fix fees", "cy", "2026-02")];
    (l.prs[1].draft, l.prs[1].decision, l.prs[1].labels) = (true, "APPROVED".into(), vec![("docs".into(), "0075ca".into())]);
    l.prs[2].checks = Some((3, 1, 0));
    let k = |l: &mut List, c| l.key(KeyEvent::new(c, KeyModifiers::NONE));
    let shown = |l: &List| l.shown().iter().map(|p| p.number).collect::<Vec<_>>();
    let filter = |l: &mut List, q: &str| (l.query = q.into(), shown(l)).1;
    assert_eq!(shown(&l), [1, 333, 22]); // most recently updated first
    assert_eq!(filter(&mut l, "fix"), [1, 333]); // smart case
    assert_eq!(filter(&mut l, "Fix"), [1]);
    assert_eq!(filter(&mut l, "is:draft"), [22]);
    assert_eq!(filter(&mut l, "-is:draft review:none"), [1, 333]);
    assert_eq!(filter(&mut l, "review:appr label:doc"), [22]);
    assert_eq!(filter(&mut l, "ci:fail"), [333]);
    assert_eq!(filter(&mut l, "ci:none -author:an"), [22]);
    assert_eq!(filter(&mut l, "docs"), [22]); // labels count as text too
    l.query.clear();
    // `/` types a filter; Enter keeps it, Esc (out of filter mode) clears it.
    k(&mut l, KeyCode::Char('/'));
    "fix".chars().for_each(|c| _ = k(&mut l, KeyCode::Char(c)));
    k(&mut l, KeyCode::Enter);
    assert_eq!(shown(&l), [1, 333]);
    k(&mut l, KeyCode::Char('j'));
    assert!(matches!(k(&mut l, KeyCode::Enter), Some(Do::Open(333))));
    k(&mut l, KeyCode::Esc); // clears the filter, doesn't quit
    assert_eq!(shown(&l), [1, 333, 22]);
    assert_eq!(filter(&mut l, "#4567"), [] as [u64; 0]); // not listed (older, or closed): Enter opens it anyway
    assert!(matches!(k(&mut l, KeyCode::Enter), Some(Do::Open(4567))));
    l.query.clear();
    // Ordering keeps the selected PR selected.
    k(&mut l, KeyCode::Char('j')); // on 333
    k(&mut l, KeyCode::Char('o')); // created: all equal, so stable
    k(&mut l, KeyCode::Char('o')); // number
    assert_eq!(shown(&l), [333, 22, 1]);
    k(&mut l, KeyCode::Char('O'));
    assert_eq!(shown(&l), [1, 22, 333]);
    assert_eq!(l.shown()[l.sel].number, 333);
    // `?` shows the help; the next key only closes it.
    k(&mut l, KeyCode::Char('?'));
    assert!(l.help);
    assert!(k(&mut l, KeyCode::Char('q')).is_none() && !l.help);
    // Tab: the PRs with a worktree, including one that's merged (not in the open tab).
    l.prs.push(Listed { number: 9, state: "MERGED".into(), ..pr(9, "old", "dee", "2025-01") });
    l.local.insert(9, ("/x/r-9".into(), None));
    l.local.insert(22, ("/x/r-22".into(), Some("feat".into())));
    assert_eq!(shown(&l), [1, 22, 333]); // open tab: not the merged one
    k(&mut l, KeyCode::Tab);
    assert_eq!(shown(&l), [9, 22]); // (still by number, ascending)
    k(&mut l, KeyCode::Char('j'));
    assert!(matches!(k(&mut l, KeyCode::Enter), Some(Do::Open(22))));
    // D asks first; D again removes it; anything else in between keeps it.
    assert!(k(&mut l, KeyCode::Char('D')).is_none() && l.msg.starts_with("D again removes /x/r-22"));
    k(&mut l, KeyCode::Char('o'));
    assert!(k(&mut l, KeyCode::Char('D')).is_none());
    assert!(matches!(k(&mut l, KeyCode::Char('D')), Some(Do::Remove(22))));
    // m marks (and moves on); a asks, a again has Claude review the marked ones.
    k(&mut l, KeyCode::Tab); // open PRs: 1, 22, 333
    k(&mut l, KeyCode::Char('g'));
    k(&mut l, KeyCode::Char('g'));
    k(&mut l, KeyCode::Char('m'));
    k(&mut l, KeyCode::Char('j')); // past 22
    k(&mut l, KeyCode::Char('m'));
    assert_eq!(l.marked, HashSet::from([1, 333]));
    assert!(k(&mut l, KeyCode::Char('a')).is_none() && l.msg.starts_with("a again: Claude reviews #1 #333"));
    assert!(matches!(k(&mut l, KeyCode::Char('a')), Some(Do::Review(ref p)) if p == &[1, 333]));
    // While reviews run, cards say so, and q asks before quitting.
    l.batch.insert(333, batch::Status::Reviewing);
    l.reviewed.insert(1);
    assert_eq!(l.claude_state(333), Some(("claude: reviewing…".into(), true)));
    assert_eq!(l.claude_state(1), Some(("claude ✓".into(), true)));
    assert!(k(&mut l, KeyCode::Char('q')).is_none() && l.msg.starts_with("Claude is still reviewing"));
    assert!(matches!(k(&mut l, KeyCode::Char('q')), Some(Do::Quit)));
}