jjj 0.4.1

Distributed project management and code review for Jujutsu
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
use super::app::{App, InputMode};
use crate::display::short_id;
use crate::models::Priority;
use ratatui::{
    layout::{Constraint, Direction, Layout, Rect},
    style::{Color, Modifier, Style},
    text::{Line, Span},
    widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph},
    Frame,
};

pub fn draw(f: &mut Frame, app: &App) {
    let size = f.area();

    // Vertical split: main content and footer
    let vertical_chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Min(0),    // Main content
            Constraint::Length(2), // Footer (2 lines)
        ])
        .split(size);

    // Main layout: two columns
    let main_chunks = Layout::default()
        .direction(Direction::Horizontal)
        .constraints([
            Constraint::Percentage(40), // Project Tree
            Constraint::Percentage(60), // Detail Pane
        ])
        .split(vertical_chunks[0]);

    draw_project_tree(f, app, main_chunks[0]);
    draw_detail(f, app, main_chunks[1]);

    // Draw footer or input line
    match &app.ui.input_mode {
        InputMode::Input {
            prompt,
            buffer,
            cursor_pos,
            ..
        } => {
            draw_input_line(f, prompt, buffer, *cursor_pos, vertical_chunks[1]);
        }
        _ => {
            draw_footer(f, app, vertical_chunks[1]);
        }
    }

    // Draw overlays last (on top)
    if matches!(app.ui.input_mode, InputMode::Help) {
        draw_help_overlay(f, app);
    }
}

pub(super) fn status_color_problem(status: &crate::models::ProblemStatus) -> Color {
    use crate::models::ProblemStatus;
    match status {
        ProblemStatus::Solved => Color::Green,
        ProblemStatus::InProgress => Color::Yellow,
        ProblemStatus::Dissolved => Color::DarkGray,
        ProblemStatus::Open => Color::White,
    }
}

pub(super) fn status_color_solution(status: &crate::models::SolutionStatus) -> Color {
    use crate::models::SolutionStatus;
    match status {
        SolutionStatus::Approved => Color::Green,
        SolutionStatus::Withdrawn => Color::Red,
        SolutionStatus::Submitted => Color::Yellow,
        SolutionStatus::Proposed => Color::Cyan,
    }
}

pub(super) fn status_color_critique(status: &crate::models::CritiqueStatus) -> Color {
    use crate::models::CritiqueStatus;
    match status {
        CritiqueStatus::Addressed | CritiqueStatus::Dismissed => Color::Green,
        CritiqueStatus::Valid => Color::Red,
        CritiqueStatus::Open => Color::Yellow,
    }
}

pub(super) fn status_color_milestone(status: &crate::models::MilestoneStatus) -> Color {
    use crate::models::MilestoneStatus;
    match status {
        MilestoneStatus::Completed => Color::Green,
        MilestoneStatus::Active => Color::Yellow,
        MilestoneStatus::Cancelled => Color::Red,
        MilestoneStatus::Planning => Color::Cyan,
    }
}

pub(super) fn severity_color(severity: &crate::models::CritiqueSeverity) -> Color {
    use crate::models::CritiqueSeverity;
    match severity {
        CritiqueSeverity::Critical => Color::Red,
        CritiqueSeverity::High => Color::Yellow,
        CritiqueSeverity::Medium => Color::White,
        CritiqueSeverity::Low => Color::DarkGray,
    }
}

/// Color a rank number by tier: top third green, middle yellow, bottom red.
pub(super) fn tier_color_for_rank(rank: usize, total: usize) -> Color {
    if total == 0 {
        return Color::DarkGray;
    }
    let third = total.div_ceil(3);
    if rank <= third {
        Color::Green
    } else if rank <= third * 2 {
        Color::Yellow
    } else {
        Color::Red
    }
}

pub(super) fn priority_prefix(priority: &Priority) -> &'static str {
    match priority {
        Priority::Critical => "🔴 ",
        Priority::High => "🟡 ",
        Priority::Medium | Priority::Low => "",
    }
}

pub(super) fn priority_color(priority: &Priority) -> Color {
    match priority {
        Priority::Critical => Color::Red,
        Priority::High => Color::Yellow,
        Priority::Medium => Color::White,
        Priority::Low => Color::DarkGray,
    }
}

pub(super) fn confidence_color(confidence: &crate::models::Confidence) -> Color {
    use crate::models::Confidence;
    match confidence {
        Confidence::Red => Color::Red,
        Confidence::Amber => Color::Yellow,
        Confidence::Green => Color::Green,
        Confidence::Unknown => Color::DarkGray,
    }
}

fn draw_project_tree(f: &mut Frame, app: &App, area: ratatui::layout::Rect) {
    use super::tree::TreeNode;

    // Apply filter if enabled
    let mut display_items: Vec<_> = if app.ui.filter_actions_only {
        super::filter_tree_to_actions(&app.cache.tree_items)
    } else {
        app.cache.tree_items.clone()
    };

    // When tier drill is active, only show the drilled milestone and its children.
    // Problems from other milestones and the backlog are hidden.
    if let Some((drill_ms, _, _)) = app.ui.tier_drill.last() {
        // Collect problem IDs belonging to the drilled milestone
        let drilled_problem_ids: std::collections::HashSet<&str> = app
            .data
            .problems
            .iter()
            .filter(|p| p.milestone_id.as_deref() == Some(drill_ms.as_str()))
            .map(|p| p.id.as_str())
            .collect();

        display_items.retain(|item| match &item.node {
            TreeNode::Milestone { id, .. } => id == drill_ms,
            TreeNode::Problem { id, .. } => drilled_problem_ids.contains(id.as_str()),
            TreeNode::Solution { id, .. } => {
                // Keep solutions whose parent problem is in the drilled milestone
                app.data
                    .solutions
                    .iter()
                    .find(|s| s.id == *id)
                    .map(|s| drilled_problem_ids.contains(s.problem_id.as_str()))
                    .unwrap_or(false)
            }
            TreeNode::Critique { id, .. } => {
                // Keep critiques whose parent solution's problem is in the drilled milestone
                app.data
                    .critiques
                    .iter()
                    .find(|c| c.id == *id)
                    .and_then(|c| app.data.solutions.iter().find(|s| s.id == c.solution_id))
                    .map(|s| drilled_problem_ids.contains(s.problem_id.as_str()))
                    .unwrap_or(false)
            }
            TreeNode::TierSeparator { .. } => true, // separators already scoped by tree builder
            TreeNode::ProjectRoot { .. } | TreeNode::Backlog { .. } => false,
        });
    }

    let border_color = if app.ui.focused_pane == super::app::FocusedPane::Tree {
        Color::Cyan
    } else {
        Color::DarkGray
    };
    let border_style = Style::default().fg(border_color);

    // Build title with tier breadcrumbs when drilling
    let title: String = if !app.ui.tier_drill.is_empty() {
        let (_, start, end) = app.ui.tier_drill.last().unwrap();
        let depth = app.ui.tier_drill.len();
        format!(
            "Tier Drill [{} deep] items {}-{} [S+\u{2190} to zoom out]",
            depth,
            start + 1,
            end
        )
    } else if app.ui.filter_actions_only {
        "Project Tree [Actions]".to_string()
    } else {
        "Project Tree".to_string()
    };

    let cursor_id = app
        .cache
        .tree_items
        .get(app.ui.tree_index)
        .map(|i| i.node.id().to_string());

    let items: Vec<ListItem> = display_items
        .iter()
        .map(|item| {
            let is_selected = app.ui.selected_ids.contains(item.node.id());
            let is_cursor = cursor_id.as_deref() == Some(item.node.id());
            let indent = "  ".repeat(item.depth);

            // Action symbol (if any)
            let action_sym = item.action_symbol.as_deref().unwrap_or("");

            let (label, color, dim) = match &item.node {
                TreeNode::ProjectRoot { .. } => (format!("{}Root", indent), Color::White, false),
                TreeNode::Milestone { title, .. } => {
                    (format!("{}{}", indent, title), Color::White, false)
                }
                TreeNode::Backlog { .. } => (format!("{}Backlog", indent), Color::DarkGray, false),
                TreeNode::Problem {
                    title,
                    status,
                    assignee,
                    ..
                } => {
                    let assignee_suffix = assignee
                        .as_deref()
                        .map(|a| {
                            // Extract name from "Name <email>" format
                            let name = a.split('<').next().unwrap_or(a).trim();
                            let name = name.char_indices().nth(12).map_or(name, |(i, _)| &name[..i]);
                            format!(" @{}", name)
                        })
                        .unwrap_or_default();
                    // Build label without rank prefix (rank is rendered as a colored span)
                    (
                        format!("{}{}{}{}", indent, action_sym, title, assignee_suffix),
                        status_color_problem(status),
                        false,
                    )
                }
                TreeNode::Solution {
                    title,
                    status,
                    assignee,
                    ..
                } => {
                    let assignee_suffix = assignee
                        .as_deref()
                        .map(|a| {
                            let name = a.split('<').next().unwrap_or(a).trim();
                            let name = name.char_indices().nth(12).map_or(name, |(i, _)| &name[..i]);
                            format!(" @{}", name)
                        })
                        .unwrap_or_default();
                    (
                        format!("{}{}{}{}", indent, action_sym, title, assignee_suffix),
                        status_color_solution(status),
                        false,
                    )
                }
                TreeNode::Critique {
                    title,
                    status,
                    severity,
                    ..
                } => (
                    format!("{}{}{} [{}]", indent, action_sym, title, severity),
                    status_color_critique(status),
                    false,
                ),
                TreeNode::TierSeparator { label } => {
                    (format!("{}{}", indent, label), Color::DarkGray, true)
                }
            };

            let style = if dim {
                Style::default().fg(Color::DarkGray)
            } else {
                Style::default().fg(color)
            };

            // Add bold modifier for selected items
            let style = if is_selected {
                style.add_modifier(Modifier::BOLD)
            } else {
                style
            };

            // Gutter: cursor "> ", selected "✓ ", both ">✓", else "  "
            let gutter = if is_cursor && is_selected {
                ">✓"
            } else if is_cursor {
                "> "
            } else if is_selected {
                ""
            } else {
                "  "
            };
            let gutter_style = if is_cursor {
                Style::default()
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD)
            } else if is_selected {
                Style::default().fg(Color::Yellow)
            } else {
                Style::default()
            };
            let mut spans = vec![Span::styled(gutter, gutter_style)];
            // Add colored rank prefix for problems
            if let TreeNode::Problem {
                rank: Some(r),
                problem_count,
                ..
            } = &item.node
            {
                let tier_color = tier_color_for_rank(*r, *problem_count);
                spans.push(Span::styled(
                    format!("#{} ", r),
                    Style::default().fg(tier_color),
                ));
            }
            spans.push(Span::styled(label, style));
            if let TreeNode::Problem {
                votes, confidence, ..
            } = &item.node
            {
                // RAG confidence dot
                let rag_color = match confidence {
                    crate::models::Confidence::Red => Some(Color::Red),
                    crate::models::Confidence::Amber => Some(Color::Yellow),
                    crate::models::Confidence::Green => Some(Color::Green),
                    crate::models::Confidence::Unknown => None,
                };
                if let Some(c) = rag_color {
                    spans.push(Span::styled("", Style::default().fg(c)));
                }
                // Vote arrows
                if *votes > 0 {
                    spans.push(Span::styled(
                        format!(" {}", "".repeat((*votes).min(10) as usize)),
                        Style::default().fg(Color::Green),
                    ));
                } else if *votes < 0 {
                    spans.push(Span::styled(
                        format!(" {}", "".repeat((votes.unsigned_abs()).min(10) as usize)),
                        Style::default().fg(Color::Red),
                    ));
                }
            }
            // Section headers (milestones, backlog) get a separator rule above
            let is_section_header = matches!(
                &item.node,
                TreeNode::Milestone { .. } | TreeNode::Backlog { .. }
            );
            if is_section_header {
                let rule = Line::from(Span::styled(
                    "".repeat(80),
                    Style::default().fg(Color::DarkGray),
                ));
                ListItem::new(vec![rule, Line::from(spans)])
            } else {
                ListItem::new(Line::from(spans))
            }
        })
        .collect();

    let list = List::new(items)
        .block(
            Block::default()
                .title(title)
                .borders(Borders::ALL)
                .border_style(border_style),
        )
        .highlight_style(Style::default().add_modifier(Modifier::REVERSED));

    // Find selection in display items by matching ID
    let selected_id = app
        .cache
        .tree_items
        .get(app.ui.tree_index)
        .map(|i| i.node.id());

    let display_index =
        selected_id.and_then(|id| display_items.iter().position(|i| i.node.id() == id));

    let mut state = ListState::default();
    if let Some(idx) = display_index {
        state.select(Some(idx));
    } else if !display_items.is_empty() {
        state.select(Some(0));
    }

    f.render_stateful_widget(list, area, &mut state);
}

fn draw_detail(f: &mut Frame, app: &App, area: ratatui::layout::Rect) {
    // Show related panel when there are results or a load is in-flight
    let show_related =
        app.ui.show_related && (!app.ui.related_items.is_empty() || app.ui.related_rx.is_some());

    // Split area if showing related panel
    let (detail_area, related_area) = if show_related {
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([
                Constraint::Min(5),    // Detail content
                Constraint::Length(7), // Related panel (5 items + 2 for border)
            ])
            .split(area);
        (chunks[0], Some(chunks[1]))
    } else {
        (area, None)
    };

    let lines = app.cache.selected_detail.to_styled_lines();
    let border_color = if app.ui.focused_pane == super::app::FocusedPane::Detail {
        Color::Cyan
    } else {
        app.cache.selected_detail.border_color()
    };
    let title = app.cache.selected_detail.block_title();

    let text: Vec<Line> = lines
        .into_iter()
        .skip(app.ui.detail_scroll as usize)
        .collect();

    let detail = Paragraph::new(text)
        .block(
            Block::default()
                .title(title)
                .borders(Borders::ALL)
                .border_style(Style::default().fg(border_color)),
        )
        .wrap(ratatui::widgets::Wrap { trim: false });

    f.render_widget(detail, detail_area);

    // Draw related panel if enabled
    if let Some(related_area) = related_area {
        draw_related_panel(f, app, related_area);
    }
}

fn draw_related_panel(f: &mut Frame, app: &App, area: ratatui::layout::Rect) {
    let is_loading = app.ui.related_rx.is_some();

    let items: Vec<ListItem> = if is_loading && app.ui.related_items.is_empty() {
        vec![ListItem::new(Line::from(Span::styled(
            "Loading...",
            Style::default().fg(Color::DarkGray),
        )))]
    } else {
        app.ui
            .related_items
            .iter()
            .enumerate()
            .map(|(i, r)| {
                let style = if i == app.ui.related_selected {
                    Style::default().bg(Color::DarkGray)
                } else {
                    Style::default()
                };
                let type_char = r.entity_type.chars().next().unwrap_or('?');
                ListItem::new(Line::from(Span::styled(
                    format!(
                        "{}/{}  [{:.2}]  {}",
                        type_char,
                        short_id(&r.entity_id),
                        r.similarity,
                        r.title
                    ),
                    style,
                )))
            })
            .collect()
    };

    let title = if is_loading {
        "Related [loading...] [R to toggle]"
    } else {
        "Related [R to toggle]"
    };

    let list = List::new(items).block(
        Block::default()
            .borders(Borders::ALL)
            .title(title)
            .border_style(Style::default().fg(Color::DarkGray)),
    );

    f.render_widget(list, area);
}

fn draw_input_line(f: &mut Frame, prompt: &str, buffer: &str, cursor_pos: usize, area: Rect) {
    // First line: prompt and input with cursor
    let input_area = Rect::new(area.x, area.y, area.width, 1);

    let prompt_span = Span::styled(prompt, Style::default().fg(Color::Yellow));

    // cursor_pos is a char index — convert to byte offset for slicing
    let char_count = buffer.chars().count();
    let clamped_char = cursor_pos.min(char_count);
    let byte_pos = buffer
        .char_indices()
        .nth(clamped_char)
        .map_or(buffer.len(), |(i, _)| i);
    let before_cursor = &buffer[..byte_pos];
    let (cursor_char, after_cursor) = if clamped_char < char_count {
        let ch = buffer[byte_pos..].chars().next().unwrap();
        let next_byte = byte_pos + ch.len_utf8();
        (&buffer[byte_pos..next_byte], &buffer[next_byte..])
    } else {
        ("", "")
    };

    let before_span = Span::styled(
        before_cursor,
        Style::default()
            .fg(Color::White)
            .add_modifier(Modifier::BOLD),
    );
    let cursor_span = Span::styled(
        cursor_char,
        Style::default()
            .fg(Color::Black)
            .bg(Color::Cyan)
            .add_modifier(Modifier::BOLD),
    );
    let after_span = Span::styled(
        after_cursor,
        Style::default()
            .fg(Color::White)
            .add_modifier(Modifier::BOLD),
    );

    let line = Line::from(vec![prompt_span, before_span, cursor_span, after_span]);
    let input = Paragraph::new(line);
    f.render_widget(input, input_area);

    // Second line: hint
    let hint =
        Paragraph::new("[Enter] submit | [Esc] cancel").style(Style::default().fg(Color::DarkGray));
    let hint_area = Rect::new(area.x, area.y + 1, area.width, 1);
    f.render_widget(hint, hint_area);
}

fn draw_footer(f: &mut Frame, app: &App, area: ratatui::layout::Rect) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([Constraint::Length(1), Constraint::Length(1)])
        .split(area);

    // Context line (top) - or flash message if present
    let selection_info = if !app.ui.selected_ids.is_empty() {
        format!("[{} selected] ", app.ui.selected_ids.len())
    } else {
        String::new()
    };

    let context_text = if let Some((msg, _)) = &app.ui.flash_message {
        msg.clone()
    } else if let Some(ref filter) = app.ui.search_filter {
        format!("{}[/{}] {}", selection_info, filter, app.context_hints())
    } else {
        format!("{}{}", selection_info, app.context_hints())
    };
    let context_style = if app.ui.flash_message.is_some() {
        Style::default().fg(Color::Green)
    } else {
        Style::default().fg(Color::Yellow)
    };
    let context = Paragraph::new(context_text).style(context_style);
    f.render_widget(context, chunks[0]);

    // Global shortcuts (bottom) — pane-aware
    let global_text = if app.ui.focused_pane == super::app::FocusedPane::Detail {
        "j/k scroll | b/Space page | g/G top/bot | Tab\u{2192}tree | ? help | q quit"
    } else {
        "j/k up/down | h/l collapse/expand | Space select | Tab\u{2192}detail | ? help | q quit"
    };
    let global = Paragraph::new(global_text).style(Style::default().fg(Color::DarkGray));
    f.render_widget(global, chunks[1]);
}

fn draw_help_overlay(f: &mut Frame, app: &App) {
    let area = f.area();

    // Calculate centered popup, clamped to terminal size
    let popup_width = 46u16.min(area.width);
    let popup_height = 30u16.min(area.height);
    let popup_x = area.width.saturating_sub(popup_width) / 2;
    let popup_y = area.height.saturating_sub(popup_height) / 2;
    let popup_area = Rect::new(popup_x, popup_y, popup_width, popup_height);

    // Build help text based on context
    let mut lines = vec![
        Line::from(""),
        Line::from(Span::styled(
            "  Tree Pane",
            Style::default().add_modifier(Modifier::BOLD),
        )),
        Line::from("    j/k ↑/↓ Move selection"),
        Line::from("    h/l ←/→ Collapse/Expand"),
        Line::from("    Tab     Switch to detail pane"),
        Line::from("    /       Search/filter tree"),
        Line::from("    f       Toggle filter (full/actions)"),
        Line::from("    S+K/\u{2191}   Assign to top tier"),
        Line::from("    S+J/\u{2193}   Assign to bottom tier"),
        Line::from("    C+K/\u{2191}   Bubble up one position"),
        Line::from("    C+J/\u{2193}   Bubble down one position"),
        Line::from("    S+L/\u{2192}   Drill into tier"),
        Line::from("    S+H/\u{2190}   Drill out"),
        Line::from("    +/-     Vote (pins to top/bottom zone)"),
        Line::from("    r       Toggle personal/global"),
        Line::from("    C-z     Undo tier/vote change"),
        Line::from("    R       Toggle related"),
        Line::from(""),
        Line::from(Span::styled(
            "  Detail Pane",
            Style::default().add_modifier(Modifier::BOLD),
        )),
        Line::from("    j/k ↑/↓ Scroll"),
        Line::from("    b/Space Page up/down"),
        Line::from("    g/G     Top/bottom"),
        Line::from("    Tab/Esc Back to tree"),
        Line::from(""),
        Line::from(Span::styled(
            "  Selection",
            Style::default().add_modifier(Modifier::BOLD),
        )),
        Line::from("    Space   Toggle select + move down"),
        Line::from("    Ctrl+A  Select all / deselect all"),
        Line::from("    Esc     Clear selection"),
        Line::from(""),
    ];

    // Context-sensitive actions
    let action_lines = get_context_actions(app);
    lines.extend(action_lines);

    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        "  Press any key to close",
        Style::default().fg(Color::DarkGray),
    )));

    // Clear the area and draw popup
    f.render_widget(Clear, popup_area);

    let help = Paragraph::new(lines).block(
        Block::default()
            .title(" Help ")
            .borders(Borders::ALL)
            .border_style(Style::default().fg(Color::Cyan)),
    );

    f.render_widget(help, popup_area);
}

fn get_context_actions(app: &App) -> Vec<Line<'static>> {
    use super::next_actions::EntityType;
    use super::tree::TreeNode;

    let mut lines = vec![Line::from(Span::styled(
        "  Actions",
        Style::default().add_modifier(Modifier::BOLD),
    ))];

    // Determine what's selected from tree
    let entity_type = app
        .cache
        .tree_items
        .get(app.ui.tree_index)
        .and_then(|item| match &item.node {
            TreeNode::Problem { .. } => Some(EntityType::Problem),
            TreeNode::Solution { .. } => Some(EntityType::Solution),
            TreeNode::Critique { .. } => Some(EntityType::Critique),
            TreeNode::Milestone { .. } => Some(EntityType::Milestone),
            TreeNode::ProjectRoot { .. }
            | TreeNode::Backlog { .. }
            | TreeNode::TierSeparator { .. } => None,
        });

    match entity_type {
        Some(EntityType::Problem) => {
            lines.push(Line::from("    n       New solution"));
            lines.push(Line::from("    c       Cycle confidence (RAG)"));
            lines.push(Line::from("    s       Mark solved"));
            lines.push(Line::from("    d       Dissolve (with reason)"));
            lines.push(Line::from("    o       Reopen"));
            lines.push(Line::from("    A       Assign to me"));
            lines.push(Line::from("    m       Move to milestone"));
            lines.push(Line::from("    e       Edit title"));
            lines.push(Line::from("    t       Edit tags"));
            lines.push(Line::from("    E       Edit in $EDITOR"));
            lines.push(Line::from("    x       Delete"));
        }
        Some(EntityType::Solution) => {
            lines.push(Line::from("    n       New critique"));
            lines.push(Line::from("    u       Submit for review"));
            lines.push(Line::from("    a       Approve"));
            lines.push(Line::from("    d       Withdraw"));
            lines.push(Line::from("    A       Assign to me"));
            lines.push(Line::from("    g       Go to change"));
            lines.push(Line::from("    e       Edit title"));
            lines.push(Line::from("    t       Edit tags"));
            lines.push(Line::from("    E       Edit in $EDITOR"));
            lines.push(Line::from("    x       Delete"));
        }
        Some(EntityType::Critique) => {
            lines.push(Line::from("    a       Address"));
            lines.push(Line::from("    d       Dismiss"));
            lines.push(Line::from("    v       Validate"));
            lines.push(Line::from("    e       Edit title"));
            lines.push(Line::from("    E       Edit in $EDITOR"));
            lines.push(Line::from("    x       Delete"));
        }
        Some(EntityType::Milestone) => {
            lines.push(Line::from("    n       New problem"));
            lines.push(Line::from("    s       Mark completed"));
            lines.push(Line::from("    d       Cancel"));
            lines.push(Line::from("    o       Activate"));
            lines.push(Line::from("    A       Assign to me"));
            lines.push(Line::from("    e       Edit title"));
            lines.push(Line::from("    E       Edit in $EDITOR"));
            lines.push(Line::from("    x       Delete"));
        }
        None => {
            // ProjectRoot or Backlog
            lines.push(Line::from("    n       New (milestone/problem)"));
        }
    }

    lines
}