frame 0.1.7

A markdown task tracker with a terminal UI for humans and a CLI for agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
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
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;

use crate::tui::app::{App, StateFilter, View};
use crate::util::unicode;

/// Result of tab layout computation: labels and layout mode
#[derive(Debug, Clone, PartialEq)]
pub(crate) struct TabLayout {
    /// Display label per track (same length as input names)
    pub labels: Vec<String>,
    /// Whether the project name fits
    pub show_project_name: bool,
    /// Whether scrolling is needed (too many tabs even after shrinking)
    pub scroll_mode: bool,
}

/// Width of a single track tab given its label and whether it has cc-focus star
fn track_tab_width(label: &str, is_cc: bool) -> usize {
    // " label " = display_width(label) + 2, plus "|" separator = +1
    // cc-focus adds "★ " = +2
    let base = unicode::display_width(label) + 2 + 1;
    if is_cc { base + 2 } else { base }
}

/// Compute the total width of fixed elements (leading icon + special tabs)
fn fixed_width(inbox_count: usize) -> usize {
    let leading = 3; // " ▶ "
    let tracks_tab = 4; // " ▶ " + "|"
    let board_tab = 4; // " ≡ " + "|"
    let inbox_tab = if inbox_count > 0 {
        // " *N " + "|"
        3 + digit_count(inbox_count) + 1
    } else {
        // " * " + "|"
        4
    };
    let recent_tab = 4; // " ✓ " + "|"
    leading + tracks_tab + board_tab + inbox_tab + recent_tab
}

fn digit_count(n: usize) -> usize {
    if n == 0 {
        return 1;
    }
    let mut count = 0;
    let mut val = n;
    while val > 0 {
        count += 1;
        val /= 10;
    }
    count
}

/// Check if a set of labels fits within the available width
fn fits(labels: &[String], cc_focus_idx: Option<usize>, fixed: usize, available: usize) -> bool {
    let track_total: usize = labels
        .iter()
        .enumerate()
        .map(|(i, l)| track_tab_width(l, Some(i) == cc_focus_idx))
        .sum();
    track_total + fixed <= available
}

/// Truncate a string to at most `n` display-width cells (no ellipsis)
fn truncate_display(s: &str, n: usize) -> String {
    if unicode::display_width(s) <= n {
        return s.to_string();
    }
    let mut width = 0;
    let mut result = String::new();
    for c in s.chars() {
        let cw = unicode::char_display_width(c);
        if width + cw > n {
            break;
        }
        width += cw;
        result.push(c);
    }
    result
}

/// Compute tab layout with progressive shrinking and optional scroll mode.
///
/// This is a pure function for testability.
pub(crate) fn compute_tab_layout(
    names: &[String],
    prefixes: &[Option<String>],
    cc_focus_idx: Option<usize>,
    available_width: usize,
    project_name_len: usize,
    inbox_count: usize,
) -> TabLayout {
    let fixed = fixed_width(inbox_count);
    let project_name_width = if project_name_len > 0 {
        project_name_len + 2 // " name "
    } else {
        0
    };

    if names.is_empty() {
        return TabLayout {
            labels: Vec::new(),
            show_project_name: fixed + project_name_width <= available_width,
            scroll_mode: false,
        };
    }

    let full_names: Vec<String> = names.to_vec();

    // Phase 0: Try with project name
    if fits(
        &full_names,
        cc_focus_idx,
        fixed + project_name_width,
        available_width,
    ) {
        return TabLayout {
            labels: full_names,
            show_project_name: true,
            scroll_mode: false,
        };
    }

    // Phase 0b: Try without project name
    if fits(&full_names, cc_focus_idx, fixed, available_width) {
        return TabLayout {
            labels: full_names,
            show_project_name: false,
            scroll_mode: false,
        };
    }

    // Incremental shrink: each iteration, find the single longest label and
    // shrink it by one char. Rightmost wins ties, so shrinking is balanced.
    // When a label reaches exactly its prefix length, swap to the prefix.
    // Each label has a per-label floor: prefix length if it has one, else 3.
    // Once all labels are at their floor, switch to scroll mode.
    let mut labels = full_names;
    let mut using_prefix = vec![false; labels.len()];
    let default_floor = 3usize;
    let label_floors: Vec<usize> = prefixes
        .iter()
        .map(|p| {
            p.as_ref().map_or(default_floor, |s| {
                unicode::display_width(s).min(default_floor)
            })
        })
        .collect();

    loop {
        // Find the longest label above its floor (rightmost among ties)
        let mut best_idx: Option<usize> = None;
        let mut best_len: usize = 0;
        for (i, label) in labels.iter().enumerate() {
            let len = unicode::display_width(label);
            if len > label_floors[i] && len >= best_len {
                best_len = len;
                best_idx = Some(i);
            }
        }

        let idx = match best_idx {
            Some(i) => i,
            None => break, // all labels at min_len — need scroll mode
        };

        // Truncate by one display-width cell
        let current_width = unicode::display_width(&labels[idx]);
        labels[idx] = truncate_display(&labels[idx], current_width - 1);

        // When the label reaches exactly the prefix length, swap to the
        // prefix (a purpose-built short identifier) instead of a truncated
        // name. This is a zero-width swap so it doesn't skip any sizes.
        let new_len = unicode::display_width(&labels[idx]);
        if !using_prefix[idx]
            && let Some(ref prefix) = prefixes[idx]
            && unicode::display_width(prefix) == new_len
        {
            labels[idx] = prefix.clone();
            using_prefix[idx] = true;
        }

        if fits(&labels, cc_focus_idx, fixed, available_width) {
            return TabLayout {
                labels,
                show_project_name: false,
                scroll_mode: false,
            };
        }
    }

    // Phase 4: Scrolling mode
    TabLayout {
        labels,
        show_project_name: false,
        scroll_mode: true,
    }
}

/// Render the tab bar: track tabs + special tabs, with separator line below
pub fn render_tab_bar(frame: &mut Frame, app: &mut App, area: Rect) {
    // Split into tab row and separator row
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // tabs
            Constraint::Length(1), // separator
        ])
        .split(area);

    if app.view == View::Search {
        render_search_tab_bar(frame, app, chunks[0]);
        // Simple separator for search view (no tab columns)
        render_separator(frame, app, chunks[1], &[]);
    } else {
        let sep_cols = render_tabs(frame, app, chunks[0]);
        render_separator(frame, app, chunks[1], &sep_cols);
    }
}

/// Render a special tab bar header for the search results view
fn render_search_tab_bar(frame: &mut Frame, app: &App, area: Rect) {
    let bg = app.theme.background;
    let total_width = area.width as usize;
    let mut spans: Vec<Span> = vec![
        // Leading icon
        Span::styled(" ", Style::default().bg(bg)),
        Span::styled("\u{25B6}", Style::default().fg(app.theme.purple).bg(bg)),
        Span::styled(" ", Style::default().bg(bg)),
        // "Search:" label
        Span::styled(
            "Search: ",
            Style::default()
                .fg(app.theme.text_bright)
                .bg(app.theme.selection_bg)
                .add_modifier(Modifier::BOLD),
        ),
    ];

    // Pattern
    if let Some(ref sr) = app.project_search_results {
        spans.push(Span::styled(
            sr.query.clone(),
            Style::default()
                .fg(app.theme.highlight)
                .bg(app.theme.selection_bg),
        ));

        // Match count
        let total = sr.items.len();
        let group_count = sr.groups.len();
        let source_summary = if group_count == 1 {
            "1 source".to_string()
        } else {
            format!("{} sources", group_count)
        };
        spans.push(Span::styled(
            format!(
                "  {} match{}  \u{2500}  {}",
                total,
                if total == 1 { "" } else { "es" },
                source_summary
            ),
            Style::default()
                .fg(app.theme.text)
                .bg(app.theme.selection_bg),
        ));
    }

    // Pad to full width
    let used: usize = spans
        .iter()
        .map(|s| unicode::display_width(&s.content))
        .sum();
    if used < total_width {
        spans.push(Span::styled(
            " ".repeat(total_width - used),
            Style::default().bg(app.theme.selection_bg),
        ));
    }

    let line = Line::from(spans);
    let widget = Paragraph::new(line).style(Style::default().bg(bg));
    frame.render_widget(widget, area);
}

/// Render tabs and return the column positions of each separator character.
fn render_tabs(frame: &mut Frame, app: &mut App, area: Rect) -> Vec<usize> {
    let total_width = area.width as usize;

    // Gather track info
    let cc_focus = app.project.config.agent.cc_focus.as_deref();
    let names: Vec<String> = app
        .active_track_ids
        .iter()
        .map(|id| app.track_name(id).to_string())
        .collect();
    let prefixes: Vec<Option<String>> = app
        .active_track_ids
        .iter()
        .map(|id| app.project.config.ids.prefixes.get(id.as_str()).cloned())
        .collect();
    let cc_focus_idx = cc_focus.and_then(|cf| app.active_track_ids.iter().position(|id| id == cf));
    let inbox_count = app.inbox_count();
    let project_name = app.project.config.project.name.clone();
    let project_name_len = unicode::display_width(&project_name);

    let layout = compute_tab_layout(
        &names,
        &prefixes,
        cc_focus_idx,
        total_width,
        project_name_len,
        inbox_count,
    );

    let mut spans: Vec<Span> = Vec::new();
    let mut sep_cols: Vec<usize> = Vec::new();
    let sep = Span::styled(
        "\u{2502}",
        Style::default().fg(app.theme.dim).bg(app.theme.background),
    );
    let bg_style = Style::default().bg(app.theme.background);

    // Leading icon
    spans.push(Span::styled(" ", bg_style));
    spans.push(Span::styled(
        "\u{25B6}",
        Style::default()
            .fg(app.theme.purple)
            .bg(app.theme.background),
    ));
    spans.push(Span::styled(" ", bg_style));

    if layout.scroll_mode {
        // --- Scrolling mode ---
        let fixed = fixed_width(inbox_count);
        let budget = total_width.saturating_sub(fixed);

        // Determine active track index
        let active_idx = match &app.view {
            View::Track(i) => Some(*i),
            View::Detail { track_id, .. } => {
                app.active_track_ids.iter().position(|id| id == track_id)
            }
            _ => None,
        };

        // Clamp tab_scroll
        let n = layout.labels.len();
        if app.tab_scroll >= n {
            app.tab_scroll = n.saturating_sub(1);
        }

        // Ensure active tab is visible: adjust tab_scroll
        if let Some(aidx) = active_idx {
            if aidx < app.tab_scroll {
                app.tab_scroll = aidx;
            }
            // Scroll right until active tab fits fully
            loop {
                let (vis_end, _) =
                    visible_range(&layout.labels, cc_focus_idx, app.tab_scroll, budget);
                if aidx < vis_end {
                    break;
                }
                if app.tab_scroll >= n.saturating_sub(1) {
                    break;
                }
                app.tab_scroll += 1;
            }
        }

        // Only deduct left indicator from budget; the right indicator (▸)
        // is rendered flush-right within any remaining space, so it doesn't
        // need to be reserved upfront.
        let has_left_initial = app.tab_scroll > 0;
        let left_cost = usize::from(has_left_initial);
        let track_budget = budget.saturating_sub(left_cost);

        // Calculate how many tabs fit fully from tab_scroll
        let (full_end, full_used) =
            visible_range(&layout.labels, cc_focus_idx, app.tab_scroll, track_budget);
        let has_right = full_end < n;

        // Try to fill remaining space on the left with a partial tab
        // (back down tab_scroll by 1, right-truncate the label).
        let mut first_partial: Option<String> = None;
        let mut first_partial_show_cc = false;

        if app.tab_scroll > 0 {
            let prev = app.tab_scroll - 1;
            // Recalculate available space: backing down tab_scroll may
            // remove the ◂ indicator, freeing 1 extra char.
            let prev_has_left = prev > 0;
            let prev_left_cost = usize::from(prev_has_left);
            let prev_track_budget = budget.saturating_sub(prev_left_cost);
            let partial_space = prev_track_budget.saturating_sub(full_used);

            if partial_space >= 4 {
                let is_cc = Some(prev) == cc_focus_idx;
                // For partial cc-focus tabs, show ★ only if 6+ chars available
                let (overhead, show_cc) = if is_cc {
                    if partial_space >= 6 {
                        (5, true)
                    } else {
                        (3, false)
                    }
                } else {
                    (3, false)
                };
                let max_chars = partial_space.saturating_sub(overhead);
                if max_chars > 0 {
                    app.tab_scroll = prev;
                    first_partial = Some(truncate_display(&layout.labels[prev], max_chars));
                    first_partial_show_cc = show_cc;
                }
            }
        }

        // Recalculate left indicator after potential tab_scroll adjustment
        let has_left = app.tab_scroll > 0;

        // Left scroll indicator
        if has_left {
            spans.push(Span::styled(
                "\u{25C2}",
                Style::default().fg(app.theme.dim).bg(app.theme.background),
            ));
        }

        // Render first tab (partial, right-truncated) if we backed down tab_scroll
        let mut tabs_used = full_used;
        let full_start = if let Some(ref label) = first_partial {
            let show_cc = first_partial_show_cc;
            tabs_used += track_tab_width(label, show_cc);
            render_track_tab(
                &mut spans,
                app,
                app.tab_scroll,
                label,
                show_cc,
                &sep,
                &mut sep_cols,
            );
            app.tab_scroll + 1
        } else {
            app.tab_scroll
        };

        // Render fully visible track tabs
        for i in full_start..full_end {
            let label = &layout.labels[i];
            let is_cc = Some(i) == cc_focus_idx;
            render_track_tab(&mut spans, app, i, label, is_cc, &sep, &mut sep_cols);
        }

        // Compute remaining space on the right (for partial tab + ▸ + padding)
        let actual_left_cost = usize::from(has_left);
        let right_avail = budget
            .saturating_sub(actual_left_cost)
            .saturating_sub(tabs_used);

        // Right partial: if there's enough space for a partial tab (4+) plus ▸ (1)
        if has_right && full_end < n && right_avail >= 5 {
            let is_cc = Some(full_end) == cc_focus_idx;
            let partial_budget = right_avail - 1; // reserve 1 for ▸
            let (overhead, show_cc) = if is_cc {
                if partial_budget >= 6 {
                    (5, true)
                } else {
                    (3, false)
                }
            } else {
                (3, false)
            };
            let max_chars = partial_budget.saturating_sub(overhead);
            if max_chars > 0 {
                let trunc_label = truncate_display(&layout.labels[full_end], max_chars);
                let partial_w = track_tab_width(&trunc_label, show_cc);
                tabs_used += partial_w;
                render_track_tab(
                    &mut spans,
                    app,
                    full_end,
                    &trunc_label,
                    show_cc,
                    &sep,
                    &mut sep_cols,
                );
            }
        }

        // Right scroll indicator, flush-right with padding before it
        if has_right {
            let final_right = budget
                .saturating_sub(actual_left_cost)
                .saturating_sub(tabs_used);
            let pad = final_right.saturating_sub(1);
            if pad > 0 {
                spans.push(Span::styled(
                    " ".repeat(pad),
                    Style::default().bg(app.theme.background),
                ));
            }
            spans.push(Span::styled(
                "\u{25B8}",
                Style::default().fg(app.theme.dim).bg(app.theme.background),
            ));
        }
    } else {
        // --- Non-scrolling mode: render all track tabs ---
        app.tab_scroll = 0;
        for (i, label) in layout.labels.iter().enumerate() {
            let is_cc = Some(i) == cc_focus_idx;
            render_track_tab(&mut spans, app, i, label, is_cc, &sep, &mut sep_cols);
        }
    }

    // Tracks view tab (▶)
    let is_tracks = app.view == View::Tracks;
    spans.push(Span::styled(" \u{25B6} ", tab_style(app, is_tracks)));
    sep_cols.push(
        spans
            .iter()
            .map(|s| unicode::display_width(&s.content))
            .sum(),
    );
    spans.push(sep.clone());

    // Board view tab (≡)
    let is_board = app.view == View::Board;
    spans.push(Span::styled(" \u{2261} ", tab_style(app, is_board)));
    sep_cols.push(
        spans
            .iter()
            .map(|s| unicode::display_width(&s.content))
            .sum(),
    );
    spans.push(sep.clone());

    // Inbox tab with count (*N)
    let is_inbox = app.view == View::Inbox;
    let tab_bg = if is_inbox {
        app.theme.selection_bg
    } else {
        app.theme.background
    };
    let style = tab_style(app, is_inbox);
    spans.push(Span::styled(" ", style));
    spans.push(Span::styled(
        "*",
        Style::default().fg(app.theme.purple).bg(tab_bg),
    ));
    if inbox_count > 0 {
        spans.push(Span::styled(format!("{} ", inbox_count), style));
    } else {
        spans.push(Span::styled(" ", style));
    }
    sep_cols.push(
        spans
            .iter()
            .map(|s| unicode::display_width(&s.content))
            .sum(),
    );
    spans.push(sep.clone());

    // Recent tab (✓)
    let is_recent = app.view == View::Recent;
    spans.push(Span::styled(" \u{2713} ", tab_style(app, is_recent)));
    sep_cols.push(
        spans
            .iter()
            .map(|s| unicode::display_width(&s.content))
            .sum(),
    );
    spans.push(sep.clone());

    // Right-justify project name in remaining space (only in non-scroll mode)
    if layout.show_project_name {
        let tabs_width: usize = spans
            .iter()
            .map(|s| unicode::display_width(&s.content))
            .sum();
        let available = total_width.saturating_sub(tabs_width);
        let name_style = Style::default().fg(app.theme.text).bg(app.theme.background);

        if available >= project_name_len + 2 {
            let pad = available - project_name_len - 2;
            if pad > 0 {
                spans.push(Span::styled(" ".repeat(pad), bg_style));
            }
            spans.push(Span::styled(format!(" {} ", project_name), name_style));
        }
    }

    let line = Line::from(spans);
    let tabs = Paragraph::new(line).style(Style::default().bg(app.theme.background));
    frame.render_widget(tabs, area);
    sep_cols
}

/// Calculate how many track tabs fit starting from `start` within `budget` chars.
/// Returns (end_exclusive, total_width_used).
fn visible_range(
    labels: &[String],
    cc_focus_idx: Option<usize>,
    start: usize,
    budget: usize,
) -> (usize, usize) {
    let mut used = 0;
    for (i, label) in labels.iter().enumerate().skip(start) {
        let is_cc = Some(i) == cc_focus_idx;
        let w = track_tab_width(label, is_cc);
        if used + w > budget {
            return (i, used);
        }
        used += w;
    }
    (labels.len(), used)
}

/// Render a single track tab, pushing spans and recording separator position
fn render_track_tab(
    spans: &mut Vec<Span<'static>>,
    app: &App,
    track_idx: usize,
    label: &str,
    is_cc: bool,
    sep: &Span<'static>,
    sep_cols: &mut Vec<usize>,
) {
    let track_id = &app.active_track_ids[track_idx];
    let is_current = app.view == View::Track(track_idx)
        || matches!(&app.view, View::Detail { track_id: tid, .. } if tid == track_id.as_str());
    let style = tab_style(app, is_current);

    if is_cc {
        spans.push(Span::styled(format!(" {} ", label), style));
        spans.push(Span::styled(
            "\u{2605}",
            Style::default().fg(app.theme.purple).bg(if is_current {
                app.theme.selection_bg
            } else {
                app.theme.background
            }),
        ));
        spans.push(Span::styled(
            " ",
            Style::default().bg(if is_current {
                app.theme.selection_bg
            } else {
                app.theme.background
            }),
        ));
    } else {
        spans.push(Span::styled(format!(" {} ", label), style));
    }
    sep_cols.push(
        spans
            .iter()
            .map(|s| unicode::display_width(&s.content))
            .sum(),
    );
    spans.push(sep.clone());
}

/// A right-aligned annotation drawn over the rule under the tab bar.
///
/// This row is the only always-rendered chrome with room to spare — the tab row
/// has none, and the status row is a `match` on the mode that shows
/// `status_message` in Navigate and Select only. A save failing while the user is
/// in Edit or Search has to be visible *there*, which rules the status row out.
pub(crate) struct SeparatorBadge {
    spans: Vec<Span<'static>>,
    /// Used when the full form does not fit.
    short: Vec<Span<'static>>,
}

impl SeparatorBadge {
    fn width(spans: &[Span<'static>]) -> usize {
        spans
            .iter()
            .map(|s| unicode::display_width(&s.content))
            .sum()
    }
}

/// The badges to draw, highest priority first.
///
/// Priority decides what survives a narrow terminal: the lowest-priority badge
/// degrades to its short form, then drops, before anything above it is touched.
/// Unsaved work outranks a filter because the filter is a thing the user just
/// chose and can see the effects of, while an unsaved file is neither.
pub(crate) fn separator_badges(app: &App) -> Vec<SeparatorBadge> {
    let bg = app.theme.background;
    let mut badges = Vec::new();

    // Unsaved work — every view, every mode.
    if let Some(ind) = app.unsaved_indicator() {
        let style = Style::default().fg(app.theme.red).bg(bg);
        badges.push(SeparatorBadge {
            spans: vec![Span::styled(ind.full(), style)],
            short: vec![Span::styled(ind.short(), style)],
        });
    } else if app.frame_unwritable {
        // Nothing has failed *yet* — the project was unwritable before the user
        // typed anything. Saying so now beats letting them find out by losing a
        // session's work.
        let style = Style::default().fg(app.theme.red).bg(bg);
        badges.push(SeparatorBadge {
            spans: vec![Span::styled("frame/ not writable".to_string(), style)],
            short: vec![Span::styled("read-only".to_string(), style)],
        });
    }

    // Active filter — track and board views only, where it means something.
    let is_track_view = matches!(app.view, View::Track(_));
    let is_board_view = app.view == View::Board;
    let filter = &app.filter_state;
    if (is_track_view || is_board_view) && filter.is_active() {
        let mut spans: Vec<Span<'static>> = vec![Span::styled(
            "filter: ".to_string(),
            Style::default().fg(app.theme.purple).bg(bg),
        )];

        if let Some(sf) = &filter.state_filter {
            let state_color = match sf {
                StateFilter::Active => app.theme.state_color(crate::model::TaskState::Active),
                StateFilter::Todo => app.theme.state_color(crate::model::TaskState::Todo),
                StateFilter::Blocked => app.theme.state_color(crate::model::TaskState::Blocked),
                StateFilter::Parked => app.theme.state_color(crate::model::TaskState::Parked),
                StateFilter::Ready => app.theme.state_color(crate::model::TaskState::Active),
            };
            spans.push(Span::styled(
                sf.label().to_string(),
                Style::default().fg(state_color).bg(bg),
            ));
        }

        if let Some(ref tag) = filter.tag_filter {
            if filter.state_filter.is_some() {
                spans.push(Span::styled(" ".to_string(), Style::default().bg(bg)));
            }
            let tag_color = app.theme.tag_color(tag);
            spans.push(Span::styled(
                format!("#{}", tag),
                Style::default().fg(tag_color).bg(bg),
            ));
        }

        badges.push(SeparatorBadge {
            short: spans.clone(),
            spans,
        });
    }

    badges
}

/// Choose which badges fit, in priority order, degrading and then dropping from
/// the back.
///
/// Returns the spans to draw, right-aligned, and the column the rule must stop
/// at. Nothing is ever truncated mid-badge — a half-written "unsav" would read
/// as corruption rather than as a message.
fn fit_badges(badges: &[SeparatorBadge], width: usize) -> (Vec<Span<'static>>, usize) {
    // One space before the first badge, one after the last.
    const GAP: usize = 2;
    // At least this much rule has to survive for the row to still read as one.
    const MIN_RULE: usize = 8;

    // Degrade strictly from the back: a badge only loses detail once everything
    // below it has already been dropped. Otherwise a low-priority badge could
    // cost the highest-priority one its detail, which inverts the priority.
    // For two badges the sequence is [full, full], [full, short], [full],
    // [short], [].
    for keep in (0..=badges.len()).rev() {
        for last_short in [false, true] {
            let mut spans: Vec<Span<'static>> = Vec::new();
            for (i, badge) in badges[..keep].iter().enumerate() {
                if i > 0 {
                    spans.push(Span::raw("  "));
                }
                if last_short && i + 1 == keep {
                    spans.extend(badge.short.iter().cloned());
                } else {
                    spans.extend(badge.spans.iter().cloned());
                }
            }
            let used = SeparatorBadge::width(&spans);
            if used == 0 {
                return (spans, width);
            }
            if width >= used + GAP + MIN_RULE {
                return (spans, width - used - GAP);
            }
        }
    }
    (Vec::new(), width)
}

fn render_separator(frame: &mut Frame, app: &App, area: Rect, sep_cols: &[usize]) {
    let width = area.width as usize;
    let bg = app.theme.background;
    let dim = app.theme.dim;

    let badges = separator_badges(app);
    let (badge_spans, rule_end) = fit_badges(&badges, width);

    let mut rule = String::with_capacity(rule_end * 3);
    for col in 0..rule_end {
        if sep_cols.contains(&col) {
            rule.push('\u{2534}');
        } else {
            rule.push('\u{2500}');
        }
    }

    let mut spans: Vec<Span> = vec![Span::styled(rule, Style::default().fg(dim).bg(bg))];
    if !badge_spans.is_empty() {
        spans.push(Span::styled(" ", Style::default().bg(bg)));
        spans.extend(badge_spans);
    }

    let used: usize = spans
        .iter()
        .map(|s| unicode::display_width(&s.content))
        .sum();
    if used < width {
        spans.push(Span::styled(
            " ".repeat(width - used),
            Style::default().bg(bg),
        ));
    }

    let sep_widget = Paragraph::new(Line::from(spans)).style(Style::default().bg(bg));
    frame.render_widget(sep_widget, area);
}

/// Style for a tab: highlighted if current, normal otherwise
fn tab_style(app: &App, is_current: bool) -> Style {
    if is_current {
        Style::default()
            .fg(app.theme.text_bright)
            .bg(app.theme.selection_bg)
            .add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(app.theme.text).bg(app.theme.background)
    }
}

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

    // ---- Separator badges ------------------------------------------------

    fn badge(full: &str, short: &str) -> SeparatorBadge {
        SeparatorBadge {
            spans: vec![Span::raw(full.to_string())],
            short: vec![Span::raw(short.to_string())],
        }
    }

    fn rendered(spans: &[Span<'static>]) -> String {
        spans.iter().map(|s| s.content.as_ref()).collect()
    }

    #[test]
    fn no_badges_leaves_the_rule_full_width() {
        let (spans, rule_end) = fit_badges(&[], 80);
        assert!(spans.is_empty());
        assert_eq!(rule_end, 80, "the rule should span the row");
    }

    #[test]
    fn badges_are_laid_out_in_priority_order() {
        let badges = vec![
            badge("unsaved: a.md", "unsaved"),
            badge("filter: todo", "f"),
        ];
        let (spans, rule_end) = fit_badges(&badges, 80);
        assert_eq!(rendered(&spans), "unsaved: a.md  filter: todo");
        assert!(rule_end < 80, "the rule must stop short of the badges");
    }

    /// Under width pressure the *last* badge degrades first, so the most
    /// important annotation is the last thing to lose detail.
    #[test]
    fn the_lowest_priority_badge_shortens_first() {
        let badges = vec![
            badge("unsaved: a.md", "unsaved"),
            badge("filter: todo", "f"),
        ];
        let (spans, _) = fit_badges(&badges, 30);
        assert_eq!(rendered(&spans), "unsaved: a.md  f");
    }

    /// And when shortening is not enough it is dropped entirely, rather than
    /// truncating a badge into something that reads as corruption.
    #[test]
    fn the_lowest_priority_badge_drops_before_the_highest() {
        let badges = vec![
            badge("unsaved: a.md", "unsaved"),
            badge("filter: todo", "f"),
        ];
        let (spans, _) = fit_badges(&badges, 24);
        assert_eq!(rendered(&spans), "unsaved: a.md");
    }

    #[test]
    fn a_row_too_narrow_for_anything_keeps_the_rule_whole() {
        let badges = vec![badge("unsaved: a.md", "unsaved")];
        let (spans, rule_end) = fit_badges(&badges, 10);
        assert!(spans.is_empty(), "nothing fits, so nothing is drawn");
        assert_eq!(rule_end, 10);
    }

    #[test]
    fn a_badge_is_never_cut_in_half() {
        let badges = vec![badge("unsaved: a.md", "unsaved")];
        for width in 0..60usize {
            let (spans, rule_end) = fit_badges(&badges, width);
            let text = rendered(&spans);
            assert!(
                text.is_empty() || text == "unsaved: a.md" || text == "unsaved",
                "width {width} produced a partial badge: {text:?}"
            );
            assert!(rule_end <= width, "the rule overflowed at width {width}");
        }
    }

    #[test]
    fn test_all_fit_with_project_name() {
        let names = vec!["Alpha".to_string(), "Beta".to_string()];
        let prefixes = vec![None, None];
        // "Alpha" tab = 5+2+1 = 8, "Beta" tab = 4+2+1 = 7
        // fixed(0 inbox) = 3+4+4+4 = 15
        // project name "My Project" = 10+2 = 12
        // total = 8+7+15+12 = 42
        let layout = compute_tab_layout(&names, &prefixes, None, 50, 10, 0);
        assert!(layout.show_project_name);
        assert!(!layout.scroll_mode);
        assert_eq!(layout.labels, vec!["Alpha", "Beta"]);
    }

    #[test]
    fn test_project_name_removed() {
        let names = vec!["Alpha".to_string(), "Beta".to_string()];
        let prefixes = vec![None, None];
        // tabs + fixed = 8+7+15 = 30, + project 12 = 42
        // Width 35 < 42 but >= 30
        let layout = compute_tab_layout(&names, &prefixes, None, 35, 10, 0);
        assert!(!layout.show_project_name);
        assert!(!layout.scroll_mode);
        assert_eq!(layout.labels, vec!["Alpha", "Beta"]);
    }

    #[test]
    fn test_shrink_longest_first() {
        let names = vec![
            "Infrastructure".to_string(), // 14
            "Backend".to_string(),        // 7
            "Frontend".to_string(),       // 8
        ];
        let prefixes = vec![None, None, None];
        // Full: 17+10+11 = 38, + fixed 19 = 57
        // Width 49: need to shrink 8 chars of tab width
        let layout = compute_tab_layout(&names, &prefixes, None, 49, 0, 0);
        assert!(!layout.scroll_mode);
        // Longest (Infrastructure) should absorb most shrinking; shorter labels preserved
        let lens: Vec<usize> = layout
            .labels
            .iter()
            .map(|l| unicode::display_width(l))
            .collect();
        assert!(
            lens[0] >= lens[1],
            "longest name should still be >= shorter: {:?}",
            lens
        );
        assert!(
            lens[0] >= lens[2],
            "longest name should still be >= shorter: {:?}",
            lens
        );
        // Backend (7) and Frontend (8) should be mostly intact
        assert_eq!(layout.labels[1], "Backend"); // 7 chars, not touched since Infra absorbs
        let total: usize = layout
            .labels
            .iter()
            .map(|l| unicode::display_width(l) + 2 + 1)
            .sum::<usize>()
            + 19;
        assert!(total <= 49);
    }

    #[test]
    fn test_prefix_swap_at_exact_length() {
        // Prefix swaps in when label is truncated to exactly prefix length
        let names = vec![
            "Infrastructure".to_string(),
            "Backend".to_string(),
            "Frontend".to_string(),
        ];
        let prefixes = vec![
            Some("INF".into()), // 3 chars
            Some("BE".into()),  // 2 chars
            Some("FE".into()),  // 2 chars
        ];
        // Width 36: shrinks all to 3, then FE swaps at 2 → fits at 36.
        // INF swaps at 3 (same-size swap), but Bac(3) stays since BE is 2 chars.
        let layout = compute_tab_layout(&names, &prefixes, None, 36, 0, 0);
        assert!(!layout.scroll_mode);
        // INF swapped at 3, FE swapped at 2, Backend truncated to "Bac"
        assert_eq!(layout.labels[0], "INF");
        assert_eq!(layout.labels[2], "FE");

        // At width 35: Backend also reaches prefix (INF+BE+FE = 6+5+5+19=35)
        let layout2 = compute_tab_layout(&names, &prefixes, None, 35, 0, 0);
        assert!(!layout2.scroll_mode);
        assert_eq!(layout2.labels, vec!["INF", "BE", "FE"]);
    }

    #[test]
    fn test_prefix_swap_is_zero_width() {
        // Prefix swap doesn't cause extra shrinking — rightmost shrinks first
        let names = vec!["Alpha".to_string(), "Bravo".to_string()];
        let prefixes = vec![Some("ALP".into()), Some("BRV".into())];
        // Full: 8+8+19=35. Width 32: need 3 chars removed.
        // Bravo(rightmost) 5→4, Alpha 5→4, Bravo 4→3 (swap BRV) → 7+6+19=32 fits.
        // Alpha stays at "Alph"(4), not over-shrunk.
        let layout = compute_tab_layout(&names, &prefixes, None, 32, 0, 0);
        assert!(!layout.scroll_mode);
        assert_eq!(layout.labels[0], "Alph"); // not shrunk past 4
        assert_eq!(layout.labels[1], "BRV"); // prefix at 3
    }

    #[test]
    fn test_shrink_past_prefix() {
        // 4-char prefix names that need shrinking below 4
        let names = vec![
            "AAAA".to_string(),
            "BBBB".to_string(),
            "CCCC".to_string(),
            "DDDD".to_string(),
        ];
        let prefixes = vec![
            Some("AAAA".into()),
            Some("BBBB".into()),
            Some("CCCC".into()),
            Some("DDDD".into()),
        ];
        // At 4 chars: 7*4=28, +19=47. Width 43: need all at 3 (6*4=24, +19=43).
        let layout = compute_tab_layout(&names, &prefixes, None, 43, 0, 0);
        assert!(!layout.scroll_mode);
        for label in &layout.labels {
            assert_eq!(unicode::display_width(label), 3);
        }
    }

    #[test]
    fn test_scrolling_when_nothing_fits() {
        let names: Vec<String> = (0..20).map(|i| format!("Track{}", i)).collect();
        let prefixes: Vec<Option<String>> = (0..20).map(|i| Some(format!("T{}", i))).collect();
        let layout = compute_tab_layout(&names, &prefixes, None, 60, 0, 0);
        assert!(layout.scroll_mode);
    }

    #[test]
    fn test_no_over_shrink() {
        // Verify that tabs aren't shrunk more than necessary
        let names = vec![
            "TUI Dev".to_string(),  // 7
            "CLI".to_string(),      // 3
            "Another".to_string(),  // 7
            "One More".to_string(), // 8
            "Booyah".to_string(),   // 6
            "Delete".to_string(),   // 6
            "Echo".to_string(),     // 4
            "Further".to_string(),  // 7
        ];
        let prefixes: Vec<Option<String>> = vec![None; 8];
        // Full tab widths: 10+6+10+11+9+9+7+10 = 72, + fixed 19 = 91
        let layout = compute_tab_layout(&names, &prefixes, None, 79, 0, 0);
        assert!(!layout.scroll_mode);
        let total: usize = layout
            .labels
            .iter()
            .map(|l| unicode::display_width(l) + 2 + 1)
            .sum::<usize>()
            + 19;
        assert!(total <= 79, "total {} should be <= 79", total);
        // Should be tight: at most 1 char of slack
        assert!(total >= 78, "total {} shouldn't leave much slack", total);
        // Short labels like "CLI"(3) shouldn't be shrunk when longer ones can absorb
        assert_eq!(layout.labels[1], "CLI");
    }

    #[test]
    fn test_balanced_shrinking_equal_names() {
        // All same-length names: should shrink evenly (rightmost first for ties)
        let names = vec![
            "Alpha".to_string(),
            "Bravo".to_string(),
            "Delta".to_string(),
        ];
        let prefixes = vec![None, None, None];
        // Full: 8*3 = 24, +19 = 43. Width 41: need 2 chars removed.
        let layout = compute_tab_layout(&names, &prefixes, None, 41, 0, 0);
        assert!(!layout.scroll_mode);
        let lens: Vec<usize> = layout
            .labels
            .iter()
            .map(|l| unicode::display_width(l))
            .collect();
        let max = *lens.iter().max().unwrap();
        let min = *lens.iter().min().unwrap();
        assert!(max - min <= 1, "labels should be balanced: {:?}", lens);
    }

    #[test]
    fn test_cc_focus_width_accounting() {
        let names = vec!["Alpha".to_string(), "Beta".to_string()];
        let prefixes = vec![None, None];
        // Without cc: 8+7+19 = 34
        // With cc on Alpha: 8+2+7+19 = 36
        // Width 35: fits without cc, doesn't fit with cc
        let layout_no_cc = compute_tab_layout(&names, &prefixes, None, 35, 0, 0);
        assert!(!layout_no_cc.scroll_mode);

        let layout_cc = compute_tab_layout(&names, &prefixes, Some(0), 35, 0, 0);
        // Should trigger shrinking (project name already hidden)
        assert!(!layout_cc.show_project_name);
    }

    #[test]
    fn test_zero_tracks() {
        let layout = compute_tab_layout(&[], &[], None, 80, 10, 0);
        assert!(layout.labels.is_empty());
        assert!(!layout.scroll_mode);
        assert!(layout.show_project_name); // fixed 19 + project 12 = 31 < 80
    }

    #[test]
    fn test_one_track() {
        let names = vec!["Solo".to_string()];
        let prefixes = vec![None];
        let layout = compute_tab_layout(&names, &prefixes, None, 30, 0, 0);
        assert!(!layout.scroll_mode);
        assert_eq!(layout.labels, vec!["Solo"]);
    }

    #[test]
    fn test_inbox_count_affects_fixed_width() {
        assert!(fixed_width(99) > fixed_width(0));
        assert_eq!(fixed_width(0), 19); // 3+4+4+4+4
        assert_eq!(fixed_width(99), 21); // 3+4+4+6+4

        let names = vec!["A".to_string()];
        let prefixes = vec![None];
        // Track "A" = 1+2+1 = 4
        // fixed(0)=19 + 4 = 23 fits in 24
        let layout_0 = compute_tab_layout(&names, &prefixes, None, 24, 0, 0);
        assert!(!layout_0.scroll_mode);
        // fixed(99)=21 + 4 = 25, doesn't fit in 24 without shrinking
        // But "A" is already 1 char, can't shrink further → scroll
        let layout_99 = compute_tab_layout(&names, &prefixes, None, 25, 0, 99);
        assert!(!layout_99.scroll_mode);
    }

    #[test]
    fn test_digit_count() {
        assert_eq!(digit_count(0), 1);
        assert_eq!(digit_count(1), 1);
        assert_eq!(digit_count(9), 1);
        assert_eq!(digit_count(10), 2);
        assert_eq!(digit_count(99), 2);
        assert_eq!(digit_count(100), 3);
    }

    mod snapshots {
        use super::super::*;
        use crate::tui::render::test_helpers::*;
        use insta::assert_snapshot;

        #[test]
        fn single_track_tab() {
            let mut app = app_with_track(SIMPLE_TRACK_MD);
            let output = render_to_string(TERM_W, 2, |frame, area| {
                render_tab_bar(frame, &mut app, area);
            });
            assert_snapshot!(output);
        }

        #[test]
        fn multiple_tracks() {
            let mut project =
                project_with_track("alpha", "Alpha", "# Alpha\n\n## Backlog\n\n## Done\n");
            let track2 = crate::parse::parse_track("# Beta\n\n## Backlog\n\n## Done\n");
            project.config.tracks.push(crate::model::TrackConfig {
                id: "beta".into(),
                name: "Beta".into(),
                state: "active".into(),
                file: "tracks/beta.md".into(),
            });
            project.tracks.push(("beta".into(), track2));
            let mut app = App::new(project);
            let output = render_to_string(TERM_W, 2, |frame, area| {
                render_tab_bar(frame, &mut app, area);
            });
            assert_snapshot!(output);
        }

        #[test]
        fn inbox_tab_selected() {
            let mut app = app_with_inbox(INBOX_MD);
            app.view = crate::tui::app::View::Inbox;
            let output = render_to_string(TERM_W, 2, |frame, area| {
                render_tab_bar(frame, &mut app, area);
            });
            assert_snapshot!(output);
        }
    }
}