omni-dev 0.46.0

AI-powered git commit rewriter, PR generator, and MCP server for Jira, Confluence, Datadog, Gmail, and Drive.
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
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
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
//! Phase 1's tree-pane renderer: a plain, read-only listing of every
//! repo/worktree from the merged [`WorktreesViewModel`]. Superseded by the
//! full glyph-table/mouse-aware tree widget in later phases (issue #1585
//! §2/§4) — this exists so `omni-dev worktrees ui` is a real, useful,
//! live-updating view from the moment the data layer lands, matching the
//! plan's "Phase 1: tree only ... supersedes `worktrees tree`" scope.

use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, List, ListItem, ListState, Paragraph};
use ratatui::Frame;

use super::glyph::{self, Glyph, GlyphMode};
use super::tree::TreeState;
use super::view_model::{
    AheadBehindState, FeedStatus, GlyphCue, RowEmphasis, SessionBadge, SessionSourceRow, Severity,
    WorktreeRow, WorktreesViewModel,
};
use crate::pr_status::PrCheckState;
use crate::sessions::SessionState;

/// Draws the tree pane into `area`. The border is highlighted while the
/// pane has keyboard focus (Phase 3 splits focus between the tree and a
/// terminal tab). Writes the list's settled scroll offset back into `tree`
/// so mouse rows can be mapped to tree rows (Phase 4's `mouse.rs`).
pub fn draw_tree_pane(
    frame: &mut Frame<'_>,
    area: Rect,
    view: &WorktreesViewModel,
    tree: &mut TreeState,
    focused: bool,
    glyphs: GlyphMode,
) {
    let mut items: Vec<ListItem> = Vec::new();
    if view.repos.is_empty() {
        items.push(ListItem::new("No repositories open."));
    }
    // The branch column gets whatever the pane can spare after the fixed
    // columns, within sane bounds — so a narrow pane elides rather than
    // pushing the path and badges off the edge.
    let branch_width = usize::from(area.width.saturating_sub(FIXED_COLUMNS)).clamp(8, 32);
    for repo in &view.repos {
        let mut header = repo.main_repo.clone();
        if let Some(gh) = &repo.github {
            header.push_str(&format!("  (github: {}/{})", gh.owner, gh.name));
        }
        if repo.polling_enabled {
            header.push_str("  [polling]");
        }
        if let Some(tag) = &repo.row_color {
            header.push_str(&format!("  ({tag})"));
        }
        header.push_str(&format!("  {}", repo.root.display()));
        let header_line = Line::from(Span::styled(
            header,
            Style::default().add_modifier(Modifier::BOLD),
        ));
        items.push(gutter_item(
            header_line,
            tree.marked.contains(&repo.root),
            glyphs,
        ));
        for wt in &repo.worktrees {
            items.push(gutter_item(
                worktree_line(wt, glyphs, branch_width),
                tree.marked.contains(&wt.path),
                glyphs,
            ));
        }
    }
    let mut state = ListState::default().with_offset(tree.offset);
    if !items.is_empty() {
        state.select(Some(tree.cursor.min(items.len() - 1)));
    }
    let border_style = if focused {
        Style::default().fg(Color::Cyan)
    } else {
        Style::default()
    };
    let list = List::new(items)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(border_style)
                .title("WORKTREES"),
        )
        .highlight_style(Style::default().add_modifier(Modifier::REVERSED));
    frame.render_stateful_widget(list, area, &mut state);
    tree.offset = state.offset();
}

/// Prepends the multi-select gutter (one cell of marker plus a space) to a
/// row's existing styled line, preserving that line's own per-span styling.
fn gutter_item(line: Line<'static>, marked: bool, glyphs: GlyphMode) -> ListItem<'static> {
    let marker = if marked {
        Glyph::MarkedGutter
    } else {
        Glyph::UnmarkedGutter
    };
    let mut spans = vec![Span::raw(format!("{} ", marker.as_str(glyphs)))];
    spans.extend(line.spans);
    ListItem::new(Line::from(spans))
}

/// Columns a row spends outside the branch name: the gutter, the two cue
/// glyphs and their spacing, the badge column, and the divergence field.
const FIXED_COLUMNS: u16 = 34;

fn worktree_line(wt: &WorktreeRow, glyphs: GlyphMode, branch_width: usize) -> Line<'static> {
    let glyph = match wt.glyph_cue() {
        GlyphCue::Here => Glyph::Here,
        GlyphCue::Pushing | GlyphCue::Rebasing => Glyph::InFlight,
        GlyphCue::Operation => Glyph::Operation,
        GlyphCue::Open => Glyph::Open,
        GlyphCue::Closed => Glyph::Closed,
    }
    .as_str(glyphs);
    let main_marker = if wt.is_main {
        Glyph::MainMarker
    } else {
        Glyph::NotMain
    }
    .as_str(glyphs);
    let branch = glyph::truncate_middle(
        wt.branch.as_deref().unwrap_or("(detached)"),
        branch_width,
        glyphs,
    );

    let mut fields = Vec::new();
    match wt.ahead_behind {
        AheadBehindState::Known {
            ahead,
            behind,
            main_behind,
        } => {
            let mut s = format!("+{ahead} -{behind}");
            if let Some(mb) = main_behind {
                s.push_str(&format!(" main-{mb}"));
            }
            fields.push(s);
        }
        // No upstream to count against, so no `+a -b` — only the default-branch gap,
        // as `worktrees tree` prints it.
        AheadBehindState::MainOnly { main_behind } => fields.push(format!("main-{main_behind}")),
        AheadBehindState::Loading => fields.push("...".to_string()),
        AheadBehindState::Unknown | AheadBehindState::Unavailable => {}
    }
    if let Some(pr) = &wt.pr {
        let draft = if pr.is_draft { " draft" } else { "" };
        fields.push(format!("#{}{draft}", pr.number));
    }
    if !wt.sessions.is_empty() {
        fields.push(sessions_summary(&wt.sessions));
    }

    // The badge column: PR checks then session state, one cell each, in
    // fixed positions so the column reads down the pane. Unlike the VS Code
    // companion — which negotiates two characters of `FileDecoration`
    // between the two providers (#1406) — a TUI owns every cell, so the two
    // dimensions simply get a cell each and never compete.
    let badges = format!("{}{}", check_glyph(wt, glyphs), session_glyph(wt, glyphs));

    let mut text = format!(" {main_marker}{glyph} {badges} {branch:<branch_width$}");
    if !fields.is_empty() {
        text.push_str("  ");
        text.push_str(&fields.join("  "));
    }
    text.push_str("  ");
    text.push_str(&wt.path.display().to_string());

    let color = match wt.emphasis() {
        RowEmphasis::Operation => Color::Yellow,
        RowEmphasis::UserTag(tag) => color_for_tag(&tag),
        // Neither an in-flight operation nor a user tag overrides the row:
        // fall through to the automatic PR-check/session severity colour
        // (`tree.ts::rowColorId`'s red > yellow > green ranking), and only
        // then to the plain "open" green / reset defaults.
        RowEmphasis::Open | RowEmphasis::Default => match wt.badge_severity() {
            Severity::Red => Color::Red,
            Severity::Yellow => Color::Yellow,
            Severity::Green => Color::Green,
            Severity::Muted if wt.open => Color::Green,
            Severity::Muted => Color::Reset,
        },
    };
    Line::from(Span::styled(text, Style::default().fg(color)))
}

/// The PR-check cell: one glyph, or a blank when the row has no PR.
/// Pending is `…` rather than a bare dot because colour alone no longer
/// separates it from a passing run (the tree view's own #1406 lesson).
fn check_glyph(wt: &WorktreeRow, glyphs: GlyphMode) -> &'static str {
    let Some(pr) = &wt.pr else {
        return " ";
    };
    match pr.checks {
        PrCheckState::Success => Glyph::ChecksPass,
        PrCheckState::Failure => Glyph::ChecksFail,
        PrCheckState::Pending => Glyph::ChecksPending,
        PrCheckState::None => return " ",
    }
    .as_str(glyphs)
}

/// The Claude-session cell: the most demanding state on the row, since a
/// row with one waiting session and three idle ones is a row that wants
/// attention. Blank when the worktree has no sessions.
fn session_glyph(wt: &WorktreeRow, glyphs: GlyphMode) -> &'static str {
    let mut cue: Option<Glyph> = None;
    for session in &wt.sessions {
        let candidate = match session.state {
            SessionState::WaitingForInput | SessionState::WaitingForPermission => {
                Glyph::SessionWaiting
            }
            SessionState::Working => Glyph::SessionWorking,
            // A session that has not been prompted yet is not busy (#1946).
            SessionState::Starting | SessionState::Idle => Glyph::SessionIdle,
            SessionState::Ended => continue,
        };
        // Waiting outranks working outranks idle.
        let rank = |g: Glyph| match g {
            Glyph::SessionWaiting => 3,
            Glyph::SessionWorking => 2,
            _ => 1,
        };
        if cue.is_none_or(|current| rank(candidate) > rank(current)) {
            cue = Some(candidate);
        }
    }
    cue.map_or(" ", |g| g.as_str(glyphs))
}

/// Maps a row-colour id — one of `row_colors::KNOWN_ROW_COLORS`, or an
/// unrecognized future one the store tolerates on read — to a terminal
/// colour. An unrecognized id falls back to the terminal's default
/// foreground rather than erroring, consistent with that same tolerance.
fn color_for_tag(tag: &str) -> Color {
    match tag {
        "charts.red" | "terminal.ansiRed" => Color::Red,
        "charts.orange" => Color::Rgb(0xff, 0xa5, 0x00),
        "charts.yellow" | "terminal.ansiYellow" => Color::Yellow,
        "charts.green" | "terminal.ansiGreen" => Color::Green,
        "charts.blue" | "terminal.ansiBlue" => Color::Blue,
        "charts.purple" | "terminal.ansiMagenta" => Color::Magenta,
        "terminal.ansiCyan" => Color::Cyan,
        "charts.foreground" | "descriptionForeground" => Color::Gray,
        _ => Color::Reset,
    }
}

/// Summarizes a worktree's live agent sessions as `"N session(s) (agent model,
/// source)"` off the most recently active one — a compact stand-in for the
/// full per-session badge layer a later phase adds (issue #1585 §2's
/// `[s o *]` model-family marker and `!`/`⚙`/`◦` state glyphs).
fn sessions_summary(sessions: &[SessionBadge]) -> String {
    let Some(latest) = sessions.iter().max_by_key(|s| s.last_seen) else {
        return String::new();
    };
    let source = match &latest.source {
        SessionSourceRow::Terminal => "terminal",
        SessionSourceRow::VsCode { .. } => "vscode",
    };
    let model = latest.model.as_deref().unwrap_or("?");
    format!(
        "{} session(s) ({} {model}, {source})",
        sessions.len(),
        latest.agent
    )
}

/// Draws the one-line status bar: feed states, mark count, and `hint` —
/// the focus-dependent key help (or a transient notice) the app supplies.
pub fn draw_status_bar(
    frame: &mut Frame<'_>,
    area: Rect,
    view: &WorktreesViewModel,
    tree: &TreeState,
    hint: &str,
) {
    let closed = if view.show_closed { "shown" } else { "hidden" };
    let marked = if tree.marked.is_empty() {
        String::new()
    } else {
        format!("{} marked   ", tree.marked.len())
    };
    let status = format!(
        "{marked}worktrees: {}  sessions: {}  closed {closed}   {hint}",
        feed_status_label(view.worktrees_status),
        feed_status_label(view.sessions_status),
    );
    frame.render_widget(Paragraph::new(status), area);
}

fn feed_status_label(status: FeedStatus) -> String {
    match status {
        FeedStatus::Connecting => "connecting".to_string(),
        FeedStatus::Live => "live".to_string(),
        FeedStatus::Reconnecting { attempt, retry_in } => {
            format!(
                "reconnecting (attempt {attempt}, retry in {}s)",
                retry_in.as_secs()
            )
        }
        FeedStatus::Polling => "polling (daemon predates live updates)".to_string(),
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use std::path::PathBuf;

    use crate::pr_status::PrCheckState;

    use super::super::view_model::PrBadgeRow;
    use super::*;

    fn worktree_row() -> WorktreeRow {
        WorktreeRow {
            path: PathBuf::from("/repo/wt"),
            branch: None,
            head_sha: None,
            upstream_sha: None,
            is_main: false,
            open: false,
            window_key: None,
            pr: None,
            pr_none: false,
            operation: None,
            rebasing: false,
            pushing: false,
            ahead_behind: AheadBehindState::Unknown,
            sessions: Vec::new(),
            row_color: None,
            here: false,
        }
    }

    fn line_color(wt: &WorktreeRow) -> Color {
        match worktree_line(wt, GlyphMode::Unicode, 24).spans.first() {
            Some(span) => span.style.fg.unwrap_or(Color::Reset),
            None => Color::Reset,
        }
    }

    #[test]
    fn color_for_tag_maps_every_known_row_color() {
        for tag in super::super::row_colors::KNOWN_ROW_COLORS {
            // Must not silently fall back to Reset for a colour the store
            // actually accepts on write.
            assert_ne!(color_for_tag(tag), Color::Reset, "tag: {tag}");
        }
    }

    #[test]
    fn color_for_tag_falls_back_to_reset_for_an_unrecognized_id() {
        assert_eq!(color_for_tag("not-a-real-color"), Color::Reset);
    }

    #[test]
    fn a_user_row_tag_is_rendered_in_its_mapped_color() {
        let mut wt = worktree_row();
        wt.row_color = Some("charts.blue".to_string());
        assert_eq!(line_color(&wt), Color::Blue);
    }

    #[test]
    fn failing_pr_checks_color_the_row_red_even_with_no_operation_or_tag() {
        let mut wt = worktree_row();
        wt.pr = Some(PrBadgeRow {
            number: 1,
            is_draft: false,
            checks: PrCheckState::Failure,
            url: String::new(),
        });
        assert_eq!(line_color(&wt), Color::Red);
    }

    #[test]
    fn an_in_flight_operation_still_wins_over_severity() {
        let mut wt = worktree_row();
        wt.rebasing = true;
        wt.pr = Some(PrBadgeRow {
            number: 1,
            is_draft: false,
            checks: PrCheckState::Failure,
            url: String::new(),
        });
        assert_eq!(line_color(&wt), Color::Yellow);
    }

    fn line_text(wt: &WorktreeRow) -> String {
        worktree_line(wt, GlyphMode::Unicode, 24)
            .spans
            .iter()
            .map(|span| span.content.as_ref())
            .collect()
    }

    #[test]
    fn a_main_only_row_renders_main_n_without_the_counts() {
        // A branch with no upstream that is behind the default branch (#1457):
        // the `main-N` the VS Code view shows as `⇊N`, with no `+a -b` beside it.
        let mut wt = worktree_row();
        wt.ahead_behind = AheadBehindState::MainOnly { main_behind: 4 };
        let text = line_text(&wt);
        assert!(text.contains("main-4"), "{text}");
        assert!(!text.contains('+'), "{text}");
        assert!(!text.contains(" -"), "{text}");
    }

    #[test]
    fn a_main_only_row_level_with_the_default_branch_still_renders_main_0() {
        // A fresh branch with no upstream, level with the default branch: the
        // daemon sends `main_behind: 0` and the other surfaces print it too (the
        // VS Code view's `⇊0`, `worktrees tree`'s `main-0`, this view's `Known`).
        // Parity with them is the point, so zero is shown rather than suppressed.
        let mut wt = worktree_row();
        wt.ahead_behind = AheadBehindState::MainOnly { main_behind: 0 };
        assert!(line_text(&wt).contains("main-0"));
    }

    #[test]
    fn a_known_row_still_renders_both_counts_before_main_n() {
        let mut wt = worktree_row();
        wt.ahead_behind = AheadBehindState::Known {
            ahead: 2,
            behind: 1,
            main_behind: Some(3),
        };
        assert!(line_text(&wt).contains("+2 -1 main-3"));
    }

    #[test]
    fn unknown_and_unavailable_rows_render_no_divergence_field() {
        for state in [AheadBehindState::Unknown, AheadBehindState::Unavailable] {
            let mut wt = worktree_row();
            wt.ahead_behind = state;
            let text = line_text(&wt);
            assert!(!text.contains("main-") && !text.contains('+'), "{text}");
        }
    }

    #[test]
    fn open_with_no_severity_or_tag_stays_green() {
        let mut wt = worktree_row();
        wt.open = true;
        assert_eq!(line_color(&wt), Color::Green);
    }

    fn buffer_text(terminal: &ratatui::Terminal<ratatui::backend::TestBackend>) -> String {
        terminal
            .backend()
            .buffer()
            .content
            .iter()
            .map(ratatui::buffer::Cell::symbol)
            .collect()
    }

    fn sample_view() -> WorktreesViewModel {
        use super::super::view_model::{GithubIdentity, RepoRow};
        let mut open = worktree_row();
        open.path = PathBuf::from("/repo/wt-open");
        open.branch = Some("feature/x".to_string());
        open.open = true;
        open.ahead_behind = AheadBehindState::Known {
            ahead: 2,
            behind: 1,
            main_behind: Some(3),
        };
        open.pr = Some(PrBadgeRow {
            number: 42,
            is_draft: true,
            checks: PrCheckState::Pending,
            url: String::new(),
        });
        let mut main = worktree_row();
        main.path = PathBuf::from("/repo");
        main.is_main = true;
        main.branch = Some("main".to_string());
        main.ahead_behind = AheadBehindState::Loading;
        WorktreesViewModel {
            repos: vec![RepoRow {
                main_repo: "repo".to_string(),
                github: Some(GithubIdentity {
                    owner: "acme".to_string(),
                    name: "repo".to_string(),
                }),
                root: PathBuf::from("/repo"),
                polling_enabled: true,
                row_color: Some("charts.blue".to_string()),
                worktrees: vec![main, open],
            }],
            show_closed: false,
            ..Default::default()
        }
    }

    #[test]
    fn draw_tree_pane_renders_rows_gutter_and_focus_border() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let view = sample_view();
        let mut tree = TreeState {
            cursor: 2,
            marked: std::iter::once(PathBuf::from("/repo/wt-open")).collect(),
            offset: 0,
        };
        for focused in [true, false] {
            let mut terminal = Terminal::new(TestBackend::new(90, 12)).unwrap();
            terminal
                .draw(|frame| {
                    draw_tree_pane(
                        frame,
                        frame.area(),
                        &view,
                        &mut tree,
                        focused,
                        GlyphMode::Unicode,
                    );
                })
                .unwrap();
            let text = buffer_text(&terminal);
            assert!(text.contains("WORKTREES"));
            assert!(text.contains("repo  (github: acme/repo)  [polling]  (charts.blue)"));
            // Phase 4c pads the branch to a fixed column and inserts the
            // two-cell badge column before it, so the fields follow the
            // padding rather than the branch directly.
            assert!(text.contains("feature/x"));
            assert!(text.contains("+2 -1 main-3  #42 draft"));
            assert!(
                text.contains('\u{2502}'),
                "the marked row has a gutter: {text}"
            );
            assert!(
                text.contains('\u{2026}'),
                "the pending-checks badge is the ellipsis glyph: {text}"
            );
            assert!(text.contains("main"), "the main worktree's branch");
            assert!(text.contains("..."), "its loading divergence state");
        }
    }

    #[test]
    fn draw_tree_pane_with_no_repos_says_so() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut terminal = Terminal::new(TestBackend::new(40, 5)).unwrap();
        let view = WorktreesViewModel::default();
        let mut tree = TreeState::default();
        terminal
            .draw(|frame| {
                draw_tree_pane(
                    frame,
                    frame.area(),
                    &view,
                    &mut tree,
                    true,
                    GlyphMode::Unicode,
                );
            })
            .unwrap();
        assert!(buffer_text(&terminal).contains("No repositories open."));
    }

    #[test]
    fn draw_tree_pane_reports_the_offset_the_list_scrolled_to() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        // Three rows (header + two worktrees) in a pane with one inner line:
        // a cursor on the last row forces the list to scroll to it.
        let view = sample_view();
        let mut tree = TreeState {
            cursor: 2,
            ..Default::default()
        };
        let mut terminal = Terminal::new(TestBackend::new(60, 3)).unwrap();
        terminal
            .draw(|frame| {
                draw_tree_pane(
                    frame,
                    frame.area(),
                    &view,
                    &mut tree,
                    true,
                    GlyphMode::Unicode,
                );
            })
            .unwrap();
        assert_eq!(tree.offset, 2);
        assert!(buffer_text(&terminal).contains("feature/x"));

        // Moving the cursor back up scrolls the offset back with it.
        tree.cursor = 0;
        terminal
            .draw(|frame| {
                draw_tree_pane(
                    frame,
                    frame.area(),
                    &view,
                    &mut tree,
                    true,
                    GlyphMode::Unicode,
                );
            })
            .unwrap();
        assert_eq!(tree.offset, 0);
    }

    #[test]
    fn draw_status_bar_shows_feed_states_marks_and_the_hint() {
        use ratatui::backend::TestBackend;
        use ratatui::Terminal;

        let mut view = sample_view();
        view.worktrees_status = FeedStatus::Live;
        view.sessions_status = FeedStatus::Reconnecting {
            attempt: 2,
            retry_in: std::time::Duration::from_secs(3),
        };
        let tree = TreeState {
            cursor: 0,
            marked: std::iter::once(PathBuf::from("/repo")).collect(),
            offset: 0,
        };
        let mut terminal = Terminal::new(TestBackend::new(120, 1)).unwrap();
        terminal
            .draw(|frame| draw_status_bar(frame, frame.area(), &view, &tree, "press a"))
            .unwrap();
        let text = buffer_text(&terminal);
        assert!(text.contains("1 marked"));
        assert!(text.contains("worktrees: live"));
        assert!(text.contains("reconnecting (attempt 2, retry in 3s)"));
        assert!(text.contains("closed hidden"));
        assert!(text.contains("press a"));

        view.sessions_status = FeedStatus::Polling;
        view.worktrees_status = FeedStatus::Connecting;
        let mut terminal = Terminal::new(TestBackend::new(120, 1)).unwrap();
        terminal
            .draw(|frame| draw_status_bar(frame, frame.area(), &view, &TreeState::default(), ""))
            .unwrap();
        let text = buffer_text(&terminal);
        assert!(text.contains("polling (daemon predates live updates)"));
        assert!(text.contains("worktrees: connecting"));
    }

    #[test]
    fn the_badge_column_shows_checks_then_session_state() {
        use crate::sessions::SessionState;

        let mut wt = worktree_row();
        // No PR and no sessions: both cells blank, so the column still
        // occupies its two cells and the branch stays aligned.
        assert_eq!(check_glyph(&wt, GlyphMode::Unicode), " ");
        assert_eq!(session_glyph(&wt, GlyphMode::Unicode), " ");

        wt.pr = Some(PrBadgeRow {
            number: 1,
            is_draft: false,
            checks: PrCheckState::Failure,
            url: String::new(),
        });
        assert_eq!(check_glyph(&wt, GlyphMode::Unicode), "\u{2717}");
        assert_eq!(check_glyph(&wt, GlyphMode::Ascii), "x");

        let session = |state| SessionBadge {
            session_id: "s".to_string(),
            state,
            source: SessionSourceRow::Terminal,
            model: None,
            agent: "Claude".to_string(),
            last_seen: chrono::Utc::now(),
        };
        // The most demanding state on the row wins: one waiting session
        // among idle ones still reads as waiting.
        wt.sessions = vec![
            session(SessionState::Idle),
            session(SessionState::WaitingForPermission),
            session(SessionState::Idle),
        ];
        assert_eq!(session_glyph(&wt, GlyphMode::Unicode), "!");
        wt.sessions = vec![session(SessionState::Idle), session(SessionState::Working)];
        assert_eq!(session_glyph(&wt, GlyphMode::Unicode), "\u{25cf}");
        wt.sessions = vec![session(SessionState::Idle)];
        assert_eq!(session_glyph(&wt, GlyphMode::Unicode), "\u{00b7}");
        // An unprompted session is not busy (#1946).
        wt.sessions = vec![session(SessionState::Starting)];
        assert_eq!(session_glyph(&wt, GlyphMode::Unicode), "\u{00b7}");
        // An ended session is not a cue at all.
        wt.sessions = vec![session(SessionState::Ended)];
        assert_eq!(session_glyph(&wt, GlyphMode::Unicode), " ");
    }

    #[test]
    fn the_sessions_summary_names_the_latest_sessions_agent() {
        let now = chrono::Utc::now();
        let badge = |agent: &str, model: Option<&str>, age: i64| SessionBadge {
            session_id: "s".to_string(),
            state: SessionState::Working,
            source: SessionSourceRow::Terminal,
            model: model.map(str::to_string),
            agent: agent.to_string(),
            last_seen: now - chrono::Duration::seconds(age),
        };
        assert_eq!(
            sessions_summary(&[
                badge("Claude", Some("claude-opus-4-8"), 30),
                badge("Codex", Some("gpt-5.5"), 1),
            ]),
            "2 session(s) (Codex gpt-5.5, terminal)"
        );
        assert_eq!(
            sessions_summary(&[badge("pi", None, 0)]),
            "1 session(s) (pi ?, terminal)"
        );
        assert_eq!(sessions_summary(&[]), "");
    }

    #[test]
    fn a_long_branch_is_elided_and_the_row_stays_column_aligned() {
        use unicode_width::UnicodeWidthStr as _;

        let mut short = worktree_row();
        short.branch = Some("main".to_string());
        let mut long = worktree_row();
        long.branch = Some("issue-1585-worktrees-ui-phase-4c-and-then-some".to_string());

        // Both rows put the path at the same column, which is the whole
        // point of padding the branch to a fixed width.
        let width = 20;
        let a = worktree_line(&short, GlyphMode::Unicode, width);
        let b = worktree_line(&long, GlyphMode::Unicode, width);
        let text_a: String = a.spans.iter().map(|s| s.content.as_ref()).collect();
        let text_b: String = b.spans.iter().map(|s| s.content.as_ref()).collect();
        let at_a = text_a.find("/repo/wt").expect("a path in the short row");
        let at_b = text_b.find("/repo/wt").expect("a path in the long row");
        assert_eq!(
            text_a[..at_a].width(),
            text_b[..at_b].width(),
            "paths must start at the same column:\n{text_a}\n{text_b}"
        );
        assert!(text_b.contains('\u{2026}'), "the long branch is elided");
    }

    #[test]
    fn ascii_mode_renders_no_non_ascii_anywhere_in_a_row() {
        let mut wt = worktree_row();
        wt.branch = Some("issue-1585-worktrees-ui-phase-4c-and-then-some".to_string());
        wt.is_main = true;
        wt.open = true;
        wt.pr = Some(PrBadgeRow {
            number: 7,
            is_draft: true,
            checks: PrCheckState::Pending,
            url: String::new(),
        });
        let line = worktree_line(&wt, GlyphMode::Ascii, 16);
        let text: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
        assert!(text.is_ascii(), "ascii mode emitted non-ascii: {text:?}");
        // And the gutter is ASCII too.
        let item = gutter_item(line, true, GlyphMode::Ascii);
        let rendered: String = format!("{item:?}");
        assert!(!rendered.contains('\u{2502}'));
    }

    #[test]
    fn default_row_with_no_signal_is_reset() {
        assert_eq!(line_color(&worktree_row()), Color::Reset);
    }
}