nomograph-muxr 1.1.1

Tmux session manager for AI coding workflows
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
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
use anyhow::{Context, Result};
use crossterm::event::{self, Event, KeyCode, KeyEventKind};
use crossterm::terminal::{self, EnterAlternateScreen, LeaveAlternateScreen};
use ratatui::backend::CrosstermBackend;
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Borders, Cell, Paragraph, Row, Table, TableState};
use ratatui::Terminal;
use std::io;

use crate::claude_status::{self, SessionHealth};
use crate::config::Config;
use crate::tmux::Tmux;

struct Entry {
    vertical: String,
    context: String,
    name: String,
    color: Color,
    activity: u64,
    health: Option<SessionHealth>,
    is_separator: bool, // true = visual group separator, not selectable
}

fn parse_hex_color(hex: &str) -> Color {
    let hex = hex.trim_start_matches('#');
    if hex.len() != 6 {
        return Color::Gray;
    }
    let r = u8::from_str_radix(&hex[0..2], 16).unwrap_or(128);
    let g = u8::from_str_radix(&hex[2..4], 16).unwrap_or(128);
    let b = u8::from_str_radix(&hex[4..6], 16).unwrap_or(128);
    Color::Rgb(r, g, b)
}

/// Build entries sorted by activity (most recent first), with muxr control plane pinned to top.
/// Inserts separator rows between vertical groups.
fn build_entries(config: &Config, tmux: &Tmux) -> Result<Vec<Entry>> {
    let sessions = tmux.list_sessions_detailed()?;

    // Build raw entries
    let raw: Vec<Entry> = sessions
        .into_iter()
        .map(|s| {
            let (vertical, context) = match s.name.split_once('/') {
                Some((v, c)) => (v.to_string(), c.to_string()),
                None => (s.name.clone(), String::new()),
            };
            let color = parse_hex_color(config.color_for(&vertical));
            // Only show health for sessions that have a harness with status support
            let tool = config.resolve_tool(&vertical, None);
            let has_harness = s.name != "muxr" && config.tool_for(&tool).is_some();
            let health = if has_harness {
                claude_status::read_health(&s.name)
            } else {
                None
            };

            Entry {
                vertical,
                context,
                name: s.name,
                color,
                activity: s.activity,
                health,
                is_separator: false,
            }
        })
        .collect();

    // Group by vertical, sort groups by most recent activity,
    // sort sessions within each group by most recent activity.
    // muxr control plane is always pinned to top (ungrouped).
    let mut muxr_entry: Option<Entry> = None;
    let mut groups: std::collections::HashMap<String, Vec<Entry>> =
        std::collections::HashMap::new();

    for entry in raw {
        if entry.name == "muxr" {
            muxr_entry = Some(entry);
        } else {
            groups
                .entry(entry.vertical.clone())
                .or_default()
                .push(entry);
        }
    }

    // Sort sessions within each group by most recent activity
    for group in groups.values_mut() {
        group.sort_by(|a, b| b.activity.cmp(&a.activity));
    }

    // Sort groups by their most recent session's activity
    let mut group_order: Vec<(String, u64)> = groups
        .iter()
        .map(|(name, entries)| {
            let max_activity = entries.iter().map(|e| e.activity).max().unwrap_or(0);
            (name.clone(), max_activity)
        })
        .collect();
    group_order.sort_by(|a, b| b.1.cmp(&a.1));

    // Build final list: muxr first, then groups with separators
    let mut entries: Vec<Entry> = Vec::with_capacity(groups.values().map(|g| g.len()).sum::<usize>() + group_order.len() + 1);

    if let Some(muxr) = muxr_entry {
        entries.push(muxr);
    }

    for (group_name, _) in &group_order {
        if !entries.is_empty() {
            entries.push(Entry {
                vertical: String::new(),
                context: String::new(),
                name: String::new(),
                color: Color::DarkGray,
                activity: 0,
                health: None,
                is_separator: true,
            });
        }
        if let Some(group_entries) = groups.remove(group_name) {
            entries.extend(group_entries);
        }
    }

    Ok(entries)
}

/// Filter entries, preserving separators between matched groups.
fn filter_entries(entries: &[Entry], query: &str) -> Vec<usize> {
    if query.is_empty() {
        return (0..entries.len()).collect();
    }
    let q = query.to_lowercase();

    // First pass: find matching real entries
    let matched: Vec<usize> = entries
        .iter()
        .enumerate()
        .filter(|(_, e)| {
            !e.is_separator
                && (e.name.to_lowercase().contains(&q)
                    || e.vertical.to_lowercase().contains(&q)
                    || e.context.to_lowercase().contains(&q))
        })
        .map(|(i, _)| i)
        .collect();

    // When filtering, skip separators -- just show matched entries flat
    matched
}

/// Format a unix timestamp as relative time (e.g., "2m", "1h", "3d").
fn format_age(activity: u64) -> String {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);

    if activity == 0 || activity > now {
        return String::new();
    }

    let age = now - activity;
    if age < 60 {
        format!("{age}s")
    } else if age < 3600 {
        format!("{}m", age / 60)
    } else if age < 86400 {
        format!("{}h", age / 3600)
    } else {
        format!("{}d", age / 86400)
    }
}

/// Action the switcher returns to main.
pub enum Action {
    Switch(String),
    Kill(String),
    Rename(String, String),
    None,
}

/// Run the interactive switcher.
pub fn run(tmux: &Tmux) -> Result<Action> {
    let config = Config::load()?;
    let entries = build_entries(&config, tmux)?;

    if entries.is_empty() {
        anyhow::bail!("No active tmux sessions");
    }

    let current = tmux
        .display_message("#{session_name}")
        .unwrap_or_default();

    terminal::enable_raw_mode().context("Failed to enable raw mode")?;
    let mut stdout = io::stdout();
    crossterm::execute!(stdout, EnterAlternateScreen).context("Failed to enter alt screen")?;

    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend)?;

    let mut table_state = TableState::default();
    let mut query = String::new();
    let mut filtering = false;
    let mut filtered = filter_entries(&entries, &query);
    let mut confirm_kill: Option<usize> = None; // index into entries if confirming
    // When Some, we're editing a rename buffer for entries[idx].
    let mut renaming: Option<(usize, String)> = None;
    let mut rename_error: Option<String> = None;

    // Select first non-separator
    select_nearest_real(&entries, &filtered, &mut table_state, 0);

    let result = loop {
        terminal.draw(|f| {
            let area = f.area();
            let chunks =
                Layout::vertical([Constraint::Min(3), Constraint::Length(3)]).split(area);

            draw_table(
                f,
                chunks[0],
                &entries,
                &filtered,
                &current,
                &mut table_state,
                confirm_kill,
                renaming.as_ref().map(|(i, _)| *i),
            );
            draw_footer(
                f,
                chunks[1],
                &query,
                filtering,
                confirm_kill.is_some(),
                renaming.as_ref().map(|(_, buf)| buf.as_str()),
                rename_error.as_deref(),
            );
        })?;

        if let Event::Key(key) = event::read()? {
            if key.kind != KeyEventKind::Press {
                continue;
            }

            // Rename mode -- swallows all keys until Enter/Esc
            if let Some((idx, buf)) = renaming.as_mut() {
                match key.code {
                    KeyCode::Esc => {
                        renaming = None;
                        rename_error = None;
                    }
                    KeyCode::Enter => {
                        let old = entries[*idx].name.clone();
                        let new = buf.trim().to_string();
                        if new.is_empty() {
                            rename_error = Some("name cannot be empty".to_string());
                        } else if new == old {
                            renaming = None;
                            rename_error = None;
                        } else if entries.iter().any(|e| !e.is_separator && e.name == new) {
                            rename_error = Some(format!("'{new}' already exists"));
                        } else {
                            terminal::disable_raw_mode()?;
                            crossterm::execute!(
                                terminal.backend_mut(),
                                LeaveAlternateScreen
                            )?;
                            return Ok(Action::Rename(old, new));
                        }
                    }
                    KeyCode::Backspace => {
                        buf.pop();
                        rename_error = None;
                    }
                    KeyCode::Char(c) => {
                        buf.push(c);
                        rename_error = None;
                    }
                    _ => {}
                }
                continue;
            }

            // Kill confirmation mode
            if let Some(kill_idx) = confirm_kill {
                match key.code {
                    KeyCode::Char('y') | KeyCode::Enter => {
                        let name = entries[kill_idx].name.clone();
                        // Restore terminal before killing
                        terminal::disable_raw_mode()?;
                        crossterm::execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
                        return Ok(Action::Kill(name));
                    }
                    _ => {
                        confirm_kill = None;
                        continue;
                    }
                }
            }

            match key.code {
                KeyCode::Esc if filtering => {
                    query.clear();
                    filtering = false;
                    filtered = filter_entries(&entries, &query);
                    select_nearest_real(&entries, &filtered, &mut table_state, 0);
                }
                KeyCode::Esc | KeyCode::Char('q') if !filtering => {
                    break Action::None;
                }
                KeyCode::Enter => {
                    if let Some(selected) = table_state.selected()
                        && let Some(&idx) = filtered.get(selected)
                        && !entries[idx].is_separator
                    {
                        break Action::Switch(entries[idx].name.clone());
                    }
                }
                KeyCode::Char('d') if !filtering => {
                    if let Some(selected) = table_state.selected()
                        && let Some(&idx) = filtered.get(selected)
                        && !entries[idx].is_separator
                        && entries[idx].name != current
                        && entries[idx].name != "muxr"
                    {
                        confirm_kill = Some(idx);
                    }
                }
                KeyCode::Char('r') if !filtering => {
                    if let Some(selected) = table_state.selected()
                        && let Some(&idx) = filtered.get(selected)
                        && !entries[idx].is_separator
                        && entries[idx].name != "muxr"
                    {
                        let prefill = entries[idx].name.clone();
                        renaming = Some((idx, prefill));
                        rename_error = None;
                    }
                }
                KeyCode::Up => {
                    move_selection(&entries, &filtered, &mut table_state, -1);
                }
                KeyCode::Down => {
                    move_selection(&entries, &filtered, &mut table_state, 1);
                }
                KeyCode::Char('k') if !filtering => {
                    move_selection(&entries, &filtered, &mut table_state, -1);
                }
                KeyCode::Char('j') if !filtering => {
                    move_selection(&entries, &filtered, &mut table_state, 1);
                }
                KeyCode::Char('/') if !filtering => {
                    filtering = true;
                }
                KeyCode::Char(c) if filtering => {
                    query.push(c);
                    filtered = filter_entries(&entries, &query);
                    select_nearest_real(&entries, &filtered, &mut table_state, 0);
                }
                KeyCode::Backspace if filtering => {
                    query.pop();
                    if query.is_empty() {
                        filtering = false;
                    }
                    filtered = filter_entries(&entries, &query);
                    select_nearest_real(&entries, &filtered, &mut table_state, 0);
                }
                _ => {}
            }
        }
    };

    terminal::disable_raw_mode()?;
    crossterm::execute!(terminal.backend_mut(), LeaveAlternateScreen)?;

    Ok(result)
}

/// Move selection by delta, skipping separator rows.
fn move_selection(
    entries: &[Entry],
    filtered: &[usize],
    state: &mut TableState,
    delta: i32,
) {
    if filtered.is_empty() {
        return;
    }
    let current = state.selected().unwrap_or(0) as i32;
    let len = filtered.len() as i32;
    let mut next = (current + delta).rem_euclid(len);

    // Skip separators
    for _ in 0..len {
        if let Some(&idx) = filtered.get(next as usize)
            && !entries[idx].is_separator
        {
            break;
        }
        next = (next + delta).rem_euclid(len);
    }

    state.select(Some(next as usize));
}

/// Select the nearest non-separator entry at or after `start`.
fn select_nearest_real(
    entries: &[Entry],
    filtered: &[usize],
    state: &mut TableState,
    start: usize,
) {
    for i in start..filtered.len() {
        if let Some(&idx) = filtered.get(i)
            && !entries[idx].is_separator
        {
            state.select(Some(i));
            return;
        }
    }
    state.select(Some(0));
}

/// Build a context bar as ratatui Spans (8 chars wide).
fn health_bar(pct: u32) -> Vec<Span<'static>> {
    let width = 8usize;
    let filled = (pct as usize * width / 100).min(width);
    let empty = width - filled;

    let bar_color = if pct >= 80 {
        Color::Red
    } else if pct >= 50 {
        Color::Yellow
    } else {
        Color::Green
    };

    let mut spans = Vec::with_capacity(2);
    if filled > 0 {
        spans.push(Span::styled(
            "\u{2588}".repeat(filled),
            Style::default().fg(bar_color),
        ));
    }
    if empty > 0 {
        spans.push(Span::styled(
            "\u{2592}".repeat(empty),
            Style::default().fg(Color::Rgb(60, 60, 65)),
        ));
    }
    spans
}

#[allow(clippy::too_many_arguments)]
fn draw_table(
    f: &mut ratatui::Frame,
    area: Rect,
    entries: &[Entry],
    filtered: &[usize],
    current: &str,
    state: &mut TableState,
    confirm_kill: Option<usize>,
    rename_idx: Option<usize>,
) {
    let dim = Style::default().fg(Color::DarkGray);

    let header = Row::new(vec![
        Cell::from("  Session").style(dim),
        Cell::from("Context").style(dim),
        Cell::from("        ").style(dim),
        Cell::from("     ").style(dim),
        Cell::from("Cache").style(dim),
        Cell::from("  Cost").style(dim),
        Cell::from("  Age").style(dim),
    ])
    .height(1);

    let rows: Vec<Row> = filtered
        .iter()
        .map(|&idx| {
            let e = &entries[idx];

            if e.is_separator {
                let sep = Style::default().fg(Color::Rgb(50, 50, 55));
                return Row::new(vec![
                    Cell::from(Span::styled("────────────────", sep)),
                    Cell::from(Span::styled("──────────────────", sep)),
                    Cell::from(Span::styled("────────", sep)),
                    Cell::from(Span::styled("─────", sep)),
                    Cell::from(Span::styled("─────────", sep)),
                    Cell::from(Span::styled("───────", sep)),
                    Cell::from(Span::styled("──────", sep)),
                ])
                .height(1);
            }

            let is_current = e.name == current;
            let is_kill_target = confirm_kill == Some(idx);
            let is_rename_target = rename_idx == Some(idx);

            let marker = if is_rename_target {
                ""
            } else if is_current {
                ""
            } else {
                "  "
            };

            let kill_style = Style::default().fg(Color::Red).add_modifier(Modifier::BOLD);
            let vs = if is_kill_target {
                kill_style
            } else {
                Style::default().fg(e.color)
            };
            let cs = if is_kill_target {
                kill_style
            } else if is_current {
                Style::default()
                    .fg(Color::White)
                    .add_modifier(Modifier::BOLD)
            } else {
                Style::default().fg(Color::White)
            };
            let info_style = if is_kill_target {
                kill_style
            } else {
                Style::default().fg(Color::Rgb(90, 90, 100))
            };

            // Health columns
            let (bar_cell, pct_cell, cache_cell, cost_cell) = if is_kill_target {
                (
                    Cell::from(Span::styled("kill?   ", kill_style)),
                    Cell::from(Span::styled("y/n  ", kill_style)),
                    Cell::from(Span::styled("         ", kill_style)),
                    Cell::from(Span::styled("       ", kill_style)),
                )
            } else if let Some(ref h) = e.health {
                let bar_spans = health_bar(h.context_pct);
                let pct_text = if h.exceeds_200k {
                    format!("{:>3}% 1M", h.context_pct)
                } else {
                    format!("{:>3}%   ", h.context_pct)
                };
                let pct_color = if h.context_pct >= 80 {
                    Color::Red
                } else if h.context_pct >= 50 {
                    Color::Yellow
                } else {
                    Color::White
                };
                let cache_text = match h.cache_pct {
                    Some(c) => format!("  {:>3}%   ", c),
                    None => "   --    ".to_string(),
                };
                let cost_text = if h.cost_usd > 0.0 {
                    format!(" ${:.2}", h.cost_usd)
                } else {
                    " $0.00".to_string()
                };
                (
                    Cell::from(Line::from(bar_spans)),
                    Cell::from(Span::styled(pct_text, Style::default().fg(pct_color))),
                    Cell::from(Span::styled(cache_text, info_style)),
                    Cell::from(Span::styled(cost_text, info_style)),
                )
            } else {
                (
                    Cell::from(Span::styled("        ", info_style)),
                    Cell::from(Span::styled("       ", info_style)),
                    Cell::from(Span::styled("   --    ", info_style)),
                    Cell::from(Span::styled("  idle", info_style)),
                )
            };

            let age_text = format!("  {}", format_age(e.activity));

            Row::new(vec![
                Cell::from(Line::from(vec![
                    Span::styled(marker, vs),
                    Span::styled(e.vertical.clone(), vs),
                ])),
                Cell::from(Span::styled(e.context.clone(), cs)),
                bar_cell,
                pct_cell,
                cache_cell,
                cost_cell,
                Cell::from(Span::styled(age_text, info_style)),
            ])
        })
        .collect();

    let widths = [
        Constraint::Length(16),  // session (marker + vertical)
        Constraint::Min(12),    // context
        Constraint::Length(8),  // bar
        Constraint::Length(7),  // pct (+ 1M badge)
        Constraint::Length(9),  // cache
        Constraint::Length(7),  // cost
        Constraint::Length(6),  // age
    ];

    let table = Table::new(rows, widths)
        .header(header)
        .block(
            Block::default()
                .borders(Borders::ALL)
                .border_style(Style::default().fg(Color::DarkGray))
                .title(" muxr ")
                .title_style(
                    Style::default()
                        .fg(Color::White)
                        .add_modifier(Modifier::BOLD),
                ),
        )
        .row_highlight_style(
            Style::default()
                .bg(Color::Rgb(58, 58, 68))
                .add_modifier(Modifier::BOLD),
        );

    f.render_stateful_widget(table, area, state);
}

#[allow(clippy::too_many_arguments)]
fn draw_footer(
    f: &mut ratatui::Frame,
    area: Rect,
    query: &str,
    filtering: bool,
    killing: bool,
    rename_buffer: Option<&str>,
    rename_error: Option<&str>,
) {
    let dim = Style::default().fg(Color::DarkGray);
    let text = if let Some(buf) = rename_buffer {
        let mut spans = vec![
            Span::styled("  rename > ", Style::default().fg(Color::Cyan)),
            Span::styled(buf.to_string(), Style::default().fg(Color::White)),
            Span::styled("_", Style::default().fg(Color::Cyan)),
        ];
        if let Some(err) = rename_error {
            spans.push(Span::styled(
                format!("  {err}"),
                Style::default().fg(Color::Red),
            ));
        } else {
            spans.push(Span::styled("  enter", dim));
            spans.push(Span::styled(" commit  ", dim));
            spans.push(Span::styled("esc", dim));
            spans.push(Span::styled(" cancel", dim));
        }
        Line::from(spans)
    } else if killing {
        Line::from(vec![
            Span::styled("  y", Style::default().fg(Color::Red)),
            Span::styled(" confirm kill  ", dim),
            Span::styled("any", dim),
            Span::styled(" cancel", dim),
        ])
    } else if filtering || !query.is_empty() {
        Line::from(vec![
            Span::styled("  /", Style::default().fg(Color::Yellow)),
            Span::styled(query, Style::default().fg(Color::White)),
            Span::styled("_", Style::default().fg(Color::Yellow)),
            Span::styled("  esc", dim),
            Span::styled(" clear", dim),
        ])
    } else {
        Line::from(vec![
            Span::styled("  /", dim),
            Span::styled("filter  ", dim),
            Span::styled("j/k", dim),
            Span::styled(" move  ", dim),
            Span::styled("enter", dim),
            Span::styled(" select  ", dim),
            Span::styled("r", dim),
            Span::styled(" rename  ", dim),
            Span::styled("d", dim),
            Span::styled(" kill  ", dim),
            Span::styled("q", dim),
            Span::styled(" quit", dim),
        ])
    };

    let block = Block::default()
        .borders(Borders::ALL)
        .border_style(Style::default().fg(Color::DarkGray));

    let paragraph = Paragraph::new(text).block(block);
    f.render_widget(paragraph, area);
}

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

    #[test]
    fn parse_hex_color_valid() {
        assert_eq!(parse_hex_color("#7aa2f7"), Color::Rgb(122, 162, 247));
        assert_eq!(parse_hex_color("#000000"), Color::Rgb(0, 0, 0));
        assert_eq!(parse_hex_color("#FFFFFF"), Color::Rgb(255, 255, 255));
    }

    #[test]
    fn parse_hex_color_without_hash() {
        assert_eq!(parse_hex_color("7aa2f7"), Color::Rgb(122, 162, 247));
    }

    #[test]
    fn parse_hex_color_invalid_falls_back() {
        assert_eq!(parse_hex_color("#FFF"), Color::Gray);
        assert_eq!(parse_hex_color(""), Color::Gray);
    }

    #[test]
    fn format_age_seconds() {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        assert_eq!(format_age(now - 30), "30s");
    }

    #[test]
    fn format_age_minutes() {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        assert_eq!(format_age(now - 120), "2m");
    }

    #[test]
    fn format_age_hours() {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        assert_eq!(format_age(now - 7200), "2h");
    }

    #[test]
    fn format_age_days() {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        assert_eq!(format_age(now - 172800), "2d");
    }

    #[test]
    fn format_age_zero_returns_empty() {
        assert_eq!(format_age(0), "");
    }

    fn make_entry(name: &str, vertical: &str, context: &str, separator: bool) -> Entry {
        Entry {
            vertical: vertical.to_string(),
            context: context.to_string(),
            name: name.to_string(),
            color: Color::Gray,
            activity: 0,
            health: None,
            is_separator: separator,
        }
    }

    #[test]
    fn filter_entries_empty_query_returns_all() {
        let entries = vec![
            make_entry("work/api", "work", "api", false),
            make_entry("", "", "", true),
            make_entry("personal/blog", "personal", "blog", false),
        ];
        assert_eq!(filter_entries(&entries, ""), vec![0, 1, 2]);
    }

    #[test]
    fn filter_entries_matches_name() {
        let entries = vec![
            make_entry("work/api", "work", "api", false),
            make_entry("personal/blog", "personal", "blog", false),
        ];
        assert_eq!(filter_entries(&entries, "api"), vec![0]);
    }

    #[test]
    fn filter_entries_matches_vertical() {
        let entries = vec![
            make_entry("work/api", "work", "api", false),
            make_entry("work/auth", "work", "auth", false),
            make_entry("personal/blog", "personal", "blog", false),
        ];
        assert_eq!(filter_entries(&entries, "work"), vec![0, 1]);
    }

    #[test]
    fn filter_entries_skips_separators() {
        let entries = vec![
            make_entry("work/api", "work", "api", false),
            make_entry("", "", "", true),
            make_entry("personal/blog", "personal", "blog", false),
        ];
        assert_eq!(filter_entries(&entries, "blog"), vec![2]);
    }

    #[test]
    fn filter_entries_case_insensitive() {
        let entries = vec![make_entry("Work/API", "Work", "API", false)];
        assert_eq!(filter_entries(&entries, "api"), vec![0]);
    }
}