vibe_coding_tracker 2.1.0

Vibe Coding Tracker - AI coding assistant telemetry/usage parser, aggregate local session data into CodeAnalysis results
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
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
//! Auto-refreshing TUI for the usage view.
//!
//! Runs a render loop that re-aggregates the session directories every
//! `refresh_secs` seconds (from `config.toml`), repriced from a pricing map
//! rebuilt at most every [`PRICING_REFRESH_SECS`], and highlights rows whose
//! tokens changed
//! since the last tick. The loop holds only the small per-model display state
//! between frames so a resize repaints instantly without re-aggregating; memory
//! is trimmed back to the OS after each refresh.

use crate::config::ProvidersConfig;
use crate::display::common::ProviderTotal;
use crate::display::common::table::{
    create_controls, create_provider_row, create_ratatui_table, create_summary,
    init_process_metrics, main_layout, refresh_process_metrics, render_scrollable_table,
    render_too_small, styled_row,
};
use crate::display::common::tui::{
    InputAction, RefreshState, ScrollState, UpdateTracker, handle_input, overlay_repo_hyperlink,
    restore_terminal, setup_terminal,
};
use crate::display::usage::averages::{
    ProviderStats, UsageProviderTotals, UsageRow, UsageTotals, build_provider_total_rows,
    build_usage_summary, merge_rows_by_base_model,
};
use crate::models::{
    ClaudeQuotaSnapshot, CodexQuotaSnapshot, CopilotQuotaSnapshot, CursorQuotaSnapshot,
    PerProviderUsage, ProviderActiveDays, QuotaSource, QuotaWindow, UsageResult,
};
use crate::pricing::{ModelPricingMap, fetch_model_pricing};
use crate::quota::{
    CLAUDE_LOGIN_HINT, CODEX_LOGIN_HINT, COPILOT_LOGIN_HINT, CURSOR_LOGIN_HINT, ClaudeState,
    CodexState, CopilotState, CursorState, load_claude_cache, load_codex_cache, load_copilot_cache,
    load_cursor_cache, save_claude_cache, save_codex_cache, save_copilot_cache, save_cursor_cache,
    spawn_quota_worker,
};
use crate::utils::{
    format_compact, format_cost, format_cost_compact, format_duration_until,
    get_claude_credentials_path, get_copilot_config_path, get_cursor_auth_path, resolve_paths,
};
use ratatui::{
    Frame, Terminal,
    backend::CrosstermBackend,
    layout::{Constraint, Direction, Layout as RatatuiLayout, Rect},
    style::{Color as RatatuiColor, Modifier, Style, Stylize},
    text::{Line, Span},
    widgets::{Block, Borders, Paragraph, Row as RatatuiRow},
};
use std::collections::HashMap;
use std::io;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use sysinfo::{Pid, System};

/// Minimum height for the bottom quota panels. Sized for the common case
/// (Claude: 5h/7d/scoped/balance/staleness; Codex: plan/5h/7d/credits/staleness)
/// plus the border. A rare overlap (extras line + login hint at once) clips the
/// least-critical bottom line, which `Paragraph` handles without panicking.
const QUOTA_PANEL_MIN_HEIGHT: u16 = 8;
/// Claude brand color for the quota panel border.
const CLAUDE_COLOR: RatatuiColor = RatatuiColor::Rgb(190, 116, 87);
/// Codex brand color for the quota panel border.
const CODEX_COLOR: RatatuiColor = RatatuiColor::Rgb(118, 127, 198);
/// Copilot brand color (GitHub green) for the quota panel border.
const COPILOT_COLOR: RatatuiColor = RatatuiColor::Rgb(46, 160, 67);
/// Cursor brand color (teal) for the quota panel border.
const CURSOR_COLOR: RatatuiColor = RatatuiColor::Rgb(64, 180, 180);

/// Minimum readable width for a single quota panel column (label + bar +
/// percent + reset). Below this a panel's gauge tail may clip.
const PANEL_MIN_W: u16 = 28;
/// Minimum width to keep the (slimmed) Provider Usage table inline in the band.
/// Matches the table's own column widths (Provider 9 + Tokens 11 + Cost 11 plus
/// borders/spacing) so it is only kept when it can render without truncating;
/// otherwise the band drops it and the panels take the full width.
const BAND_TABLE_MIN_W: u16 = 38;
/// Terminal height needed to wrap the panels into a two-row grid.
const PANELS_2ROW_MIN_H: u16 = 26;

/// Which provider quota panels have credentials on this machine.
#[derive(Clone, Copy, Default)]
struct QuotaPresence {
    claude: bool,
    codex: bool,
    copilot: bool,
    cursor: bool,
}

impl QuotaPresence {
    /// Detects presence from each provider's credential file (once at launch).
    fn detect() -> Self {
        let claude = get_claude_credentials_path()
            .map(|p| p.exists())
            .unwrap_or(false);
        let codex = resolve_paths()
            .map(|p| p.codex_dir.join("auth.json").exists() || p.codex_session_dir.exists())
            .unwrap_or(false);
        let copilot = get_copilot_config_path()
            .map(|p| p.exists())
            .unwrap_or(false);
        let cursor = get_cursor_auth_path().map(|p| p.exists()).unwrap_or(false);
        Self {
            claude,
            codex,
            copilot,
            cursor,
        }
    }

    /// Number of provider quota panels present.
    fn count(&self) -> usize {
        self.claude as usize + self.codex as usize + self.copilot as usize + self.cursor as usize
    }
}

/// Borrowed quota state passed to the render frame.
struct QuotaView<'a> {
    claude: &'a ClaudeQuotaSnapshot,
    codex: &'a CodexQuotaSnapshot,
    copilot: &'a CopilotQuotaSnapshot,
    cursor: &'a CursorQuotaSnapshot,
    present: QuotaPresence,
    /// Whether the bottom band is shown at all. `false` when `usage.quota.panels`
    /// is empty, which drops the whole band (panels *and* the Provider Usage
    /// table), not just the individual gauges.
    band_enabled: bool,
}

/// How often to rebuild the LiteLLM pricing map. The underlying data only
/// changes when the upstream JSON is updated (daily at most), so rebuilding
/// a fresh ~500 KB `HashMap<Rc<str>, ModelPricing>` every 10 s just churned
/// the allocator and left heap fragmentation behind on long sessions.
const PRICING_REFRESH_SECS: u64 = 300;
/// Upper bound on rows the [`UpdateTracker`] remembers for change highlighting.
const MAX_TRACKED_ROWS: usize = 100;

/// Hard minimum terminal width/height; below this only a notice is drawn.
const USAGE_MIN_W: u16 = 74;
const USAGE_MIN_H: u16 = 14;
/// At or above this height the provider/quota band is shown; below it the band
/// is dropped so the scrollable table keeps a usable height.
const USAGE_PANELS_MIN_H: u16 = 22;
/// Minimum combined height reserved for the model table, summary, and controls.
const USAGE_NON_PANEL_MIN_H: u16 = 10;

/// Displays token usage data in an interactive TUI with auto-refresh.
///
/// Runs until the user quits; `time_range` filters which sessions are scanned.
///
/// Features:
/// - Auto-refresh on a configurable interval (usage + pricing)
/// - Real-time memory monitoring
/// - Provider-grouped totals
/// - Scrollable model table (arrow keys)
/// - Keyboard controls: `q`, `Esc`, or `Ctrl+C` to exit, `r` to refresh, `m` to
///   toggle merging models that share a base name across provider prefixes
///   (e.g. `openai/gpt-5.5` + `azure/gpt-5.5`). `merge_providers` seeds the
///   initial state and the `m` toggle is persisted back to `config.toml`.
///
/// `quota_panels` selects which live quota panels to show (by provider name);
/// an empty list drops the band entirely. `providers` (from the config) selects
/// which providers are aggregated. `refresh_secs` is the TUI re-aggregation
/// cadence; `quota_refresh_secs` is the shared poll cadence for every live quota
/// worker.
///
/// # Errors
///
/// Returns an error if the terminal cannot be set up or restored, if reading a
/// terminal input event fails, or if a frame fails to draw. A failure to
/// aggregate usage or fetch pricing within the loop is logged and the previous
/// data is kept, not propagated.
///
/// # Panics
///
/// Panics if the current process ID cannot be obtained for memory monitoring.
pub fn display_usage_interactive(
    time_range: crate::cli::TimeRange,
    merge_providers: bool,
    quota_panels: Vec<String>,
    providers: ProvidersConfig,
    refresh_secs: u64,
    quota_refresh_secs: u64,
) -> anyhow::Result<()> {
    let mut terminal = setup_terminal()?;
    let mut refresh_state = RefreshState::new(refresh_secs.max(1));

    // Each provider's quota is fetched on its own background thread so a
    // blocking (or slow) HTTP call never stalls the render loop or the other
    // providers. Panels are seeded from the last-known cache so they show
    // immediately on launch, and a worker is spawned only for a provider whose
    // credentials are present. All workers share one HTTP client and shutdown
    // flag. With no panels selected, treat every provider as absent so nothing
    // is probed, no worker spawns, and the band is dropped.
    let panel_on = |name: &str| crate::config::quota_panel_selected(&quota_panels, name);
    // An empty `quota_panels` drops the whole bottom band (panels + the Provider
    // Usage table), not just the gauges — a genuinely quieter dashboard.
    let band_enabled = !quota_panels.is_empty();
    let mut present = if band_enabled {
        QuotaPresence::detect()
    } else {
        QuotaPresence::default()
    };
    // A panel shows only when it is selected in `usage.quota.panels` AND its
    // provider is enabled in `[providers]` — a disabled or unselected provider
    // is skipped entirely (no cache load, no worker, no quota API call).
    present.claude &= providers.claude && panel_on("claude");
    present.codex &= providers.codex && panel_on("codex");
    present.copilot &= providers.copilot && panel_on("copilot");
    present.cursor &= providers.cursor && panel_on("cursor");
    let quota_shutdown = Arc::new(AtomicBool::new(false));
    let claude_shared = Arc::new(Mutex::new(
        present
            .claude
            .then(load_claude_cache)
            .flatten()
            .unwrap_or_default(),
    ));
    let codex_shared = Arc::new(Mutex::new(
        present
            .codex
            .then(load_codex_cache)
            .flatten()
            .unwrap_or_default(),
    ));
    let copilot_shared = Arc::new(Mutex::new(
        present
            .copilot
            .then(load_copilot_cache)
            .flatten()
            .unwrap_or_default(),
    ));
    let cursor_shared = Arc::new(Mutex::new(
        present
            .cursor
            .then(load_cursor_cache)
            .flatten()
            .unwrap_or_default(),
    ));
    if present.claude || present.codex || present.copilot || present.cursor {
        match crate::quota::http::build_client() {
            Ok(client) => {
                if present.claude {
                    let (c, sh, shared) = (
                        client.clone(),
                        Arc::clone(&quota_shutdown),
                        Arc::clone(&claude_shared),
                    );
                    let mut state = ClaudeState::default();
                    spawn_quota_worker(
                        "claude",
                        shared,
                        sh,
                        quota_refresh_secs,
                        move || state.resolve(&c),
                        |s| {
                            let _ = save_claude_cache(s);
                        },
                    );
                }
                if present.codex {
                    let (c, sh, shared) = (
                        client.clone(),
                        Arc::clone(&quota_shutdown),
                        Arc::clone(&codex_shared),
                    );
                    let mut state = CodexState::default();
                    spawn_quota_worker(
                        "codex",
                        shared,
                        sh,
                        quota_refresh_secs,
                        move || state.resolve(&c),
                        |s| {
                            let _ = save_codex_cache(s);
                        },
                    );
                }
                if present.copilot {
                    let (c, sh, shared) = (
                        client.clone(),
                        Arc::clone(&quota_shutdown),
                        Arc::clone(&copilot_shared),
                    );
                    let mut state = CopilotState;
                    spawn_quota_worker(
                        "copilot",
                        shared,
                        sh,
                        quota_refresh_secs,
                        move || state.resolve(&c),
                        |s| {
                            let _ = save_copilot_cache(s);
                        },
                    );
                }
                if present.cursor {
                    let (c, sh, shared) = (
                        client.clone(),
                        Arc::clone(&quota_shutdown),
                        Arc::clone(&cursor_shared),
                    );
                    let mut state = CursorState;
                    spawn_quota_worker(
                        "cursor",
                        shared,
                        sh,
                        quota_refresh_secs,
                        move || state.resolve(&c),
                        |s| {
                            let _ = save_cursor_cache(s);
                        },
                    );
                }
            }
            Err(e) => log::warn!("quota workers disabled: failed to build HTTP client: {e}"),
        }
    }

    let pid =
        sysinfo::get_current_pid().expect("Failed to get current process ID for memory monitoring");
    // `System::new_all` would load every process, disk and network on the
    // machine (tens of MB on a busy host). We only read our own process
    // stats, so start from an empty `System` and populate it with just our
    // pid (CPU + memory only) on every refresh. `remove_dead_processes: true`
    // ensures no stale entries linger across refreshes.
    let mut sys = System::new();
    init_process_metrics(&mut sys, pid);
    // Lightweight CPU/memory sampling runs on its own fast cadence, decoupled
    // from the heavier session re-aggregation below.
    let metrics_interval = Duration::from_millis(crate::constants::refresh::METRICS_REFRESH_MS);
    let mut last_metrics = Instant::now();

    let mut usage_data = UsageResult::default();
    let mut per_provider_usage = PerProviderUsage::default();
    let mut provider_days = ProviderActiveDays::default();
    let mut stored_costs = crate::usage::StoredCosts::default();
    let mut has_usage_data = false;

    // Pricing map is large (~500 KB / ~400 models) but changes at most once
    // per day upstream, so build it once and reuse across refresh cycles.
    // We only rebuild when `PRICING_REFRESH_SECS` has elapsed — otherwise a
    // 10 s refresh interval would allocate and drop a fresh hashmap six
    // times a minute, leaving the glibc heap fragmented on long sessions.
    let mut pricing_map = match fetch_model_pricing() {
        Ok(map) => map,
        Err(e) => {
            log::warn!("Failed to fetch initial pricing: {}", e);
            ModelPricingMap::new(HashMap::new())
        }
    };
    let mut last_pricing_refresh = Instant::now();

    let mut update_tracker = UpdateTracker::new(MAX_TRACKED_ROWS, 1000);

    // Scroll/selection state for the model table (keyboard-driven).
    let mut scroll = ScrollState::new();

    // Latest rendered display state, kept across refresh cycles so a terminal
    // resize can redraw at the new size immediately without re-aggregating the
    // session directories. These are small per-model summaries, not the heavy
    // parse buffers, so holding onto them between refreshes is cheap.
    let mut rows_data: Vec<UsageRow> = Vec::new();
    let mut totals = UsageTotals::default();
    let mut provider_totals = UsageProviderTotals::default();
    // `rows_data` is the un-merged canonical list. `display_rows` holds the
    // provider-prefix-collapsed rows (e.g. `openai/gpt-5.5` + `azure/gpt-5.5` ->
    // `gpt-5.5`) and is materialized **only while merging is on**; when off it
    // stays empty and the table renders `rows_data` directly (see
    // `current_view`), so the default path keeps a single copy of the rows.
    // Toggling `m` re-derives from the cached `rows_data`, never re-scanning disk.
    let mut merge_enabled = merge_providers;
    let mut display_rows: Vec<UsageRow> = Vec::new();
    // Quota panel state, cached across frames so a resize repaints without
    // re-reading the shared snapshots.
    let mut claude_snapshot = ClaudeQuotaSnapshot::default();
    let mut codex_snapshot = CodexQuotaSnapshot::default();
    let mut copilot_snapshot = CopilotQuotaSnapshot::default();
    let mut cursor_snapshot = CursorQuotaSnapshot::default();

    loop {
        if refresh_state.should_refresh() {
            refresh_state.mark_refreshed();

            // Only refresh our own process entry (CPU + memory) and prune any
            // that have died. Per-process CPU usage is updated as part of this
            // refresh, so the former `refresh_cpu_all()` (which scans every CPU
            // system-wide) is not needed here.
            refresh_process_metrics(&mut sys, pid);

            match crate::usage::get_usage_from_directories_with(time_range, providers) {
                Ok(data) => {
                    usage_data = data.models;
                    per_provider_usage = data.per_provider;
                    provider_days = data.provider_days;
                    stored_costs = data.stored_costs;
                    has_usage_data = true;
                }
                Err(e) => {
                    log::warn!("Failed to get usage data: {}", e);
                    if !has_usage_data {
                        usage_data.clear();
                        per_provider_usage = PerProviderUsage::default();
                        stored_costs = Default::default();
                    }
                }
            }

            // Refresh the pricing map at most once every `PRICING_REFRESH_SECS`.
            if last_pricing_refresh.elapsed() >= Duration::from_secs(PRICING_REFRESH_SECS)
                || pricing_map.is_empty()
            {
                match fetch_model_pricing() {
                    Ok(map) => {
                        pricing_map = map;
                        last_pricing_refresh = Instant::now();
                    }
                    Err(e) => log::warn!("Failed to refresh pricing: {}", e),
                }
            }

            let summary = build_usage_summary(
                &usage_data,
                &per_provider_usage,
                &provider_days,
                &pricing_map,
                &stored_costs,
            );

            // Remember which model was selected so the highlight can follow it
            // across a refresh even if rows are reordered or added/removed.
            let prev_model = {
                let view = current_view(merge_enabled, &rows_data, &display_rows);
                scroll
                    .table
                    .selected()
                    .and_then(|i| view.get(i))
                    .map(|row| row.model.clone())
            };

            // Cache the rendered display state so a resize can redraw without
            // re-aggregating. These per-model summaries are small; the heavy
            // raw usage buffers are cleared right below.
            rows_data = summary.rows;
            // Hide models that contributed neither tokens nor cost in this
            // range; they only add noise. A model can have zero tokens but a
            // nonzero cost (Claude per-query web search, or an OpenCode model
            // priced from its stored cost or a credit adjustment), so keep any
            // row that carries cost too. Otherwise it vanishes from the table
            // while its cost still counts toward the grand total, leaving the
            // two inconsistent. A negative (credit) cost counts just as much as
            // a positive one, so match on any nonzero value, not just > 0.
            rows_data.retain(|row| row.total != 0 || row.cost != 0.0);
            totals = summary.totals;
            provider_totals = summary.provider_totals;

            // Materialize the merged view only when merging is on; when off the
            // table renders `rows_data` directly (no clone). Totals stay from
            // `summary` (a row-wise sum is the same merged or not).
            if merge_enabled {
                display_rows = merge_rows_by_base_model(&rows_data);
            }
            let view = current_view(merge_enabled, &rows_data, &display_rows);

            let model_names: Vec<String> = view.iter().map(|row| row.model.clone()).collect();
            scroll.sync(prev_model.as_deref(), &model_names);

            // Refresh quota panels from each background worker's latest snapshot.
            claude_snapshot = claude_shared.lock().map(|g| g.clone()).unwrap_or_default();
            codex_snapshot = codex_shared.lock().map(|g| g.clone()).unwrap_or_default();
            copilot_snapshot = copilot_shared.lock().map(|g| g.clone()).unwrap_or_default();
            cursor_snapshot = cursor_shared.lock().map(|g| g.clone()).unwrap_or_default();

            // Clear raw usage data immediately after processing to free memory.
            // Per-provider map is reset on the next refresh when new data arrives.
            usage_data.clear();
            per_provider_usage = PerProviderUsage::default();

            // NOTE: we intentionally do NOT clear the global file cache or the
            // pricing cache here. The usage path already bypasses the file cache
            // (runs in `ParseMode::UsageOnly` and drops each analysis after
            // extraction), so wiping it would only nuke entries populated by
            // other commands. The pricing cache is a single sub-MB hashmap
            // backed by a dated on-disk file — clearing it just forces another
            // file-parse on the next refresh.

            // Track updates against the displayed rows so highlighting keys off
            // the merged model name when merging is on. See `row_fingerprint`
            // for why a merged base name highlights on any variant's change.
            let current_row_keys: Vec<String> = view.iter().map(|row| row.model.clone()).collect();

            update_tracker.cleanup(current_row_keys);

            for row in view {
                update_tracker.track_update(row.model.clone(), &row_fingerprint(row));
            }

            render_usage_frame(
                &mut terminal,
                view,
                &totals,
                &provider_totals,
                &update_tracker,
                &sys,
                pid,
                &QuotaView {
                    claude: &claude_snapshot,
                    codex: &codex_snapshot,
                    copilot: &copilot_snapshot,
                    cursor: &cursor_snapshot,
                    present,
                    band_enabled,
                },
                &mut scroll,
                merge_enabled,
            )?;

            // Hand any arena-held free pages back to the OS. The refresh cycle
            // just allocated and dropped a lot of small objects (per-file parse
            // buffers, per-model hashmaps, ratatui row vectors); without this
            // call glibc keeps them as internal free lists and RSS climbs by
            // ~6 MB every refresh on a 219-session directory.
            crate::utils::release_freed_heap();

            // This heavy path already repainted with fresh metrics, so restart
            // the light-tick timer to avoid an immediate redundant redraw.
            last_metrics = Instant::now();
        } else if last_metrics.elapsed() >= metrics_interval {
            // Lightweight metrics tick: re-sample only our own process (cheap)
            // and repaint the cached rows so the CPU/memory readout stays live
            // without re-scanning any session directory.
            last_metrics = Instant::now();
            refresh_process_metrics(&mut sys, pid);
            let view = current_view(merge_enabled, &rows_data, &display_rows);
            render_usage_frame(
                &mut terminal,
                view,
                &totals,
                &provider_totals,
                &update_tracker,
                &sys,
                pid,
                &QuotaView {
                    claude: &claude_snapshot,
                    codex: &codex_snapshot,
                    copilot: &copilot_snapshot,
                    cursor: &cursor_snapshot,
                    present,
                    band_enabled,
                },
                &mut scroll,
                merge_enabled,
            )?;
        }

        let action = handle_input()?;
        match action {
            InputAction::Quit => {
                // Signal the detached workers to stop; the OS reclaims them on exit.
                quota_shutdown.store(true, Ordering::Relaxed);
                break;
            }
            InputAction::Refresh => refresh_state.force(),
            // Flip provider-prefix merging and re-derive the displayed rows from
            // the cached canonical list — no directory re-scan. Keep the current
            // model selected across the collapse/expand when it survives.
            InputAction::ToggleMerge => {
                let prev_model = {
                    let view = current_view(merge_enabled, &rows_data, &display_rows);
                    scroll
                        .table
                        .selected()
                        .and_then(|i| view.get(i))
                        .map(|row| row.model.clone())
                };
                merge_enabled = !merge_enabled;
                // Remember the choice for next launch (best-effort; a write
                // failure must not disrupt the TUI).
                let _ = crate::config::save_merge_models(merge_enabled);
                // Materialize the merged rows when turning on; drop them (freeing
                // the copy) when turning off.
                if merge_enabled {
                    display_rows = merge_rows_by_base_model(&rows_data);
                } else {
                    display_rows = Vec::new();
                }
                let view = current_view(merge_enabled, &rows_data, &display_rows);
                let model_names: Vec<String> = view.iter().map(|row| row.model.clone()).collect();
                scroll.sync(prev_model.as_deref(), &model_names);
                // Prime the tracker with the relabeled keys so the next refresh
                // doesn't treat them as first-seen and green-flash the whole
                // table; a row still highlights later if its tokens actually move.
                for row in view {
                    update_tracker.prime(row.model.clone(), &row_fingerprint(row));
                }
                render_usage_frame(
                    &mut terminal,
                    view,
                    &totals,
                    &provider_totals,
                    &update_tracker,
                    &sys,
                    pid,
                    &QuotaView {
                        claude: &claude_snapshot,
                        codex: &codex_snapshot,
                        copilot: &copilot_snapshot,
                        cursor: &cursor_snapshot,
                        present,
                        band_enabled,
                    },
                    &mut scroll,
                    merge_enabled,
                )?;
            }
            // Move the selection / scroll, then repaint the cached frame
            // without re-aggregating.
            InputAction::Navigate(nav) => {
                let view = current_view(merge_enabled, &rows_data, &display_rows);
                scroll.apply(nav, view.len());
                render_usage_frame(
                    &mut terminal,
                    view,
                    &totals,
                    &provider_totals,
                    &update_tracker,
                    &sys,
                    pid,
                    &QuotaView {
                        claude: &claude_snapshot,
                        codex: &codex_snapshot,
                        copilot: &copilot_snapshot,
                        cursor: &cursor_snapshot,
                        present,
                        band_enabled,
                    },
                    &mut scroll,
                    merge_enabled,
                )?;
            }
            // Redraw the cached frame at the new terminal size without
            // re-aggregating, so resize tracks the drag instead of waiting
            // for the next refresh tick.
            InputAction::Resize => {
                let view = current_view(merge_enabled, &rows_data, &display_rows);
                render_usage_frame(
                    &mut terminal,
                    view,
                    &totals,
                    &provider_totals,
                    &update_tracker,
                    &sys,
                    pid,
                    &QuotaView {
                        claude: &claude_snapshot,
                        codex: &codex_snapshot,
                        copilot: &copilot_snapshot,
                        cursor: &cursor_snapshot,
                        present,
                        band_enabled,
                    },
                    &mut scroll,
                    merge_enabled,
                )?;
            }
            InputAction::Continue => {}
        }
    }

    restore_terminal(&mut terminal)?;
    Ok(())
}

/// Returns the rows currently on screen without copying: the canonical
/// `rows_data` when merging is off, or the pre-materialized merged `display_rows`
/// when it is on.
///
/// Keeping `display_rows` empty in the (default) un-merged case means the loop
/// holds a single copy of the rows and skips a per-refresh clone; it is only
/// populated while the merge toggle is on, where the collapsed rows genuinely
/// differ from the canonical list.
fn current_view<'a>(
    merge_enabled: bool,
    rows_data: &'a [UsageRow],
    display_rows: &'a [UsageRow],
) -> &'a [UsageRow] {
    if merge_enabled {
        display_rows
    } else {
        rows_data
    }
}

/// The change-highlight fingerprint of a row: the token buckets only (never
/// cost, so a fuzzy-price shift can't flicker a row).
///
/// Reasoning is folded into the second field so a Gemini session whose only
/// delta lands in `thoughts_tokens` still registers as a change. When merging is
/// on this is computed over the summed row, so a collapsed base name highlights
/// whenever **any** of its folded-in provider variants grows — a base name that
/// looks idle can flash because a hidden variant (a subagent, another provider
/// prefix, a background session) is being written. That is truthful, not a bug.
fn row_fingerprint(row: &UsageRow) -> (i64, i64, i64, i64) {
    (
        row.input_tokens,
        row.output_with_reasoning(),
        row.cache_read,
        row.cache_creation,
    )
}

/// Render a single usage frame from already-aggregated display state.
///
/// Kept separate from the refresh loop so both the periodic refresh and a
/// terminal resize can paint the latest data; `provider_rows` is rebuilt here
/// (a small set of borrow wrappers) rather than cached, since it borrows
/// from `provider_totals`.
///
/// # Errors
///
/// Returns an error if the underlying terminal draw call fails.
#[allow(clippy::too_many_arguments)]
fn render_usage_frame(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    rows_data: &[UsageRow],
    totals: &UsageTotals,
    provider_totals: &UsageProviderTotals,
    update_tracker: &UpdateTracker,
    sys: &System,
    pid: Pid,
    quota: &QuotaView,
    scroll: &mut ScrollState,
    merge_enabled: bool,
) -> anyhow::Result<()> {
    let provider_rows = build_provider_total_rows(provider_totals);

    let completed = terminal.draw(|f| {
        let area = f.area();
        if area.width < USAGE_MIN_W || area.height < USAGE_MIN_H {
            render_too_small(f, USAGE_MIN_W, USAGE_MIN_H);
            return;
        }

        // Drop the provider/quota band on short terminals so the scrollable
        // table keeps a usable height.
        // Decide how the band arranges the present quota panels (and whether the
        // slimmed Provider Usage table shares the row) from the terminal size,
        // then size the band accordingly. The band spans the full width, so the
        // arrange decision uses `area.width`.
        let n = quota.present.count();
        let arrange = arrange_band(area.width, area.height, n);
        // `band_enabled == false` (empty `quota_panels`) drops the whole band, so
        // the scrollable table takes the full height — not just the gauges hidden.
        let panels_height = visible_band_height(
            area.height,
            quota.band_enabled,
            &arrange,
            provider_rows.len(),
        );
        let chunks = main_layout(area, panels_height);

        let header = vec![
            "Model",
            "Input",
            "Output",
            "Cache Read",
            "Cache Write",
            "Total",
            "Cost (USD)",
        ];

        // One selectable row per model. The grand total lives only in the
        // summary bar below (it was redundant here and in the provider band).
        let rows: Vec<RatatuiRow> = rows_data
            .iter()
            .map(|row| {
                let style = if update_tracker.is_recently_updated(&row.model) {
                    Style::default().bg(RatatuiColor::Rgb(60, 80, 60)).bold()
                } else {
                    Style::default()
                };
                styled_row(
                    vec![
                        row.display_model.clone(),
                        format_compact(row.input_tokens),
                        format_compact(row.output_with_reasoning()),
                        format_compact(row.cache_read),
                        format_compact(row.cache_creation),
                        format_compact(row.total),
                        format_cost(row.cost),
                    ],
                    style,
                    1,
                )
            })
            .collect();

        let widths = [
            Constraint::Min(16),
            Constraint::Length(9),
            Constraint::Length(9),
            Constraint::Length(11),
            Constraint::Length(11),
            Constraint::Length(9),
            Constraint::Length(12),
        ];

        let row_count = rows.len();
        render_scrollable_table(
            f,
            chunks.table,
            header,
            rows,
            &widths,
            RatatuiColor::Green,
            row_count,
            scroll,
        );

        if let Some(panel_area) = chunks.panels {
            let grid = split_band(panel_area, &arrange, n);

            // The (slimmed) Provider Usage table is only shown when the band
            // keeps a cell for it; otherwise the panels take the whole band and
            // the scrollable per-model table above carries the per-provider view.
            if let Some(table_area) = grid.table {
                // Draw one outer border for the whole cell, then split its inside
                // into the provider table (top) and a stacked share bar pinned to
                // the bottom line, so both live inside the same box.
                let block = Block::default()
                    .borders(Borders::ALL)
                    .border_style(Style::default().fg(RatatuiColor::Magenta));
                let inner = block.inner(table_area);
                f.render_widget(block, table_area);

                let cells = RatatuiLayout::default()
                    .direction(Direction::Vertical)
                    .constraints([Constraint::Min(2), Constraint::Length(1)])
                    .split(inner);
                let (rows_area, bar_area) = (cells[0], cells[1]);

                // Drop the "All Providers" aggregate; the summary bar already
                // carries the grand totals.
                let mut totals_rows: Vec<RatatuiRow> = provider_rows
                    .iter()
                    .filter(|row| row.label != "All Providers")
                    .map(|row| {
                        create_provider_row(
                            vec![
                                row.label.to_string(),
                                format_compact(row.stats.total_tokens),
                                format_cost_compact(row.stats.total_cost),
                            ],
                            row.tui_color,
                            row.emphasize,
                        )
                    })
                    .collect();

                if totals_rows.is_empty() {
                    totals_rows.push(
                        RatatuiRow::new(vec![
                            "No provider data yet".to_string(),
                            "-".to_string(),
                            "-".to_string(),
                        ])
                        .style(Style::default().fg(RatatuiColor::DarkGray)),
                    );
                }

                let totals_header = vec!["Provider", "Tokens", "Cost"];
                let totals_widths = [
                    Constraint::Min(9),
                    Constraint::Length(11),
                    Constraint::Length(11),
                ];

                // Reuse the shared table builder but strip its own border (the
                // outer block above already draws it) by overriding the block.
                let totals_table = create_ratatui_table(
                    totals_rows,
                    totals_header,
                    &totals_widths,
                    RatatuiColor::Magenta,
                )
                .block(Block::default());
                f.render_widget(totals_table, rows_area);

                f.render_widget(
                    Paragraph::new(provider_share_bar(&provider_rows, bar_area.width)),
                    bar_area,
                );
            }

            // Render present panels in fixed order (Claude → Codex → Copilot →
            // Cursor) into the grid cells; a missing provider consumes no cell.
            let now = chrono::Local::now().timestamp();
            let mut idx = 0;
            if quota.present.claude {
                render_claude_quota(f, grid.panels[idx], quota.claude, now);
                idx += 1;
            }
            if quota.present.codex {
                render_codex_quota(f, grid.panels[idx], quota.codex, now);
                idx += 1;
            }
            if quota.present.copilot {
                render_copilot_quota(f, grid.panels[idx], quota.copilot, now);
                idx += 1;
            }
            if quota.present.cursor {
                render_cursor_quota(f, grid.panels[idx], quota.cursor, now);
            }
        }

        let total_cost_str = format_cost(totals.cost);
        let total_tokens_str = format_compact(totals.total);
        let entries_str = format!("{}", rows_data.len());

        let summary_items = vec![
            ("Total Cost:", total_cost_str.as_str(), RatatuiColor::Yellow),
            (
                "Total Tokens:",
                total_tokens_str.as_str(),
                RatatuiColor::Cyan,
            ),
            ("Models:", entries_str.as_str(), RatatuiColor::Blue),
        ];

        let summary = create_summary(summary_items, sys, pid, chunks.summary.width);
        f.render_widget(summary, chunks.summary);

        // When merged, the toggle un-merges, so label it "split" to match.
        let merge_hint = if merge_enabled {
            " split  "
        } else {
            " merge  "
        };
        f.render_widget(create_controls(&[("m", merge_hint)]), chunks.controls);
    })?;

    // ratatui can't embed the OSC 8 escape itself, so hyperlink the repo label
    // it just drew (a no-op on terminals without hyperlink support).
    overlay_repo_hyperlink(completed.buffer)?;

    Ok(())
}

/// Maps a usage percentage to a traffic-light color (green/yellow/red).
fn gauge_color(pct: f64) -> RatatuiColor {
    if pct >= 90.0 {
        RatatuiColor::Red
    } else if pct >= 70.0 {
        RatatuiColor::Yellow
    } else {
        RatatuiColor::Green
    }
}

/// Renders a 5-segment mini bar like `▰▰▱▱▱` (any usage shows one block).
fn mini_bar(pct: f64) -> String {
    let filled = ((pct / 20.0).ceil() as i64).clamp(0, 5) as usize;
    (0..5).map(|i| if i < filled { 'â–°' } else { 'â–±' }).collect()
}

/// Builds a horizontal stacked share bar filling `width` columns: one solid
/// colored segment per provider, sized by its token share of the total.
///
/// Each segment reuses the provider's `tui_color` so it lines up with the table
/// rows above. Segment widths use largest-remainder rounding so they always sum
/// to exactly `width`. Falls back to a dim placeholder bar when there is no
/// token data (or zero width).
fn provider_share_bar(rows: &[ProviderTotal<'_, ProviderStats>], width: u16) -> Line<'static> {
    let width = width as usize;
    // Providers that actually contributed tokens (skip the "All Providers"
    // aggregate and any empty provider).
    let segments: Vec<(RatatuiColor, i64)> = rows
        .iter()
        .filter(|row| row.label != "All Providers" && row.stats.total_tokens > 0)
        .map(|row| (row.tui_color, row.stats.total_tokens))
        .collect();
    let total: i64 = segments.iter().map(|(_, t)| *t).sum();

    if width == 0 || total <= 0 {
        return Line::from(Span::styled(
            "â–‘".repeat(width),
            Style::default().fg(RatatuiColor::DarkGray),
        ));
    }

    // Largest-remainder apportionment: floor each share, then hand the leftover
    // columns to the largest fractional remainders so the bar fills exactly.
    let mut widths: Vec<usize> = Vec::with_capacity(segments.len());
    let mut remainders: Vec<(usize, f64)> = Vec::with_capacity(segments.len());
    let mut used = 0usize;
    for (i, (_, tokens)) in segments.iter().enumerate() {
        let exact = *tokens as f64 / total as f64 * width as f64;
        let floor = exact.floor() as usize;
        widths.push(floor);
        remainders.push((i, exact - floor as f64));
        used += floor;
    }
    let mut leftover = width.saturating_sub(used);
    remainders.sort_by(|a, b| b.1.partial_cmp(&a.1).unwrap_or(std::cmp::Ordering::Equal));
    for (i, _) in remainders {
        if leftover == 0 {
            break;
        }
        widths[i] += 1;
        leftover -= 1;
    }

    let spans: Vec<Span<'static>> = segments
        .iter()
        .enumerate()
        .filter_map(|(i, (color, _))| {
            let w = widths[i];
            (w > 0).then(|| Span::styled("â–ˆ".repeat(w), Style::default().fg(*color)))
        })
        .collect();
    Line::from(spans)
}

/// Builds one gauge line: `5h     ▰▰▱▱▱   27%  ↻ 4h13m`.
///
/// The label is padded to a fixed width so the bars line up across `5h` / `7d`
/// and the longer per-model labels ("Opus" / "Sonnet").
fn quota_gauge_line(label: &str, w: &QuotaWindow, now: i64) -> Line<'static> {
    let pct = w.used_percent;
    let color = gauge_color(pct);
    let mut spans = vec![
        Span::styled(
            format!("{label:<6} "),
            Style::default().fg(RatatuiColor::Gray),
        ),
        Span::styled(mini_bar(pct), Style::default().fg(color)),
        Span::styled(format!(" {pct:>3.0}%"), Style::default().fg(color)),
    ];
    if let Some(reset) = w.resets_at_unix {
        spans.push(Span::styled(
            format!("  ↻ {}", format_duration_until(reset, now)),
            Style::default().fg(RatatuiColor::DarkGray),
        ));
    }
    Line::from(spans)
}

/// Like [`quota_gauge_line`] but labels the bar with a caller-supplied value
/// (e.g. `36/1500`) instead of a percentage, and carries no reset marker. `pct`
/// still drives the bar fill and its traffic-light color; used for the Copilot
/// request-count gauge, which shares the `prem` line's reset window.
fn quota_gauge_line_value(label: &str, pct: f64, value: &str) -> Line<'static> {
    let color = gauge_color(pct);
    Line::from(vec![
        Span::styled(
            format!("{label:<6} "),
            Style::default().fg(RatatuiColor::Gray),
        ),
        Span::styled(mini_bar(pct), Style::default().fg(color)),
        Span::styled(format!(" {value}"), Style::default().fg(color)),
    ])
}

/// Builds the "updated Xm ago" staleness line, from the last successful fetch.
///
/// Dimmed by default, escalating to yellow past 1h and red past 6h so a panel
/// stuck on stale data (e.g. persistent auth failure) reads as such.
fn staleness_line(fetched_at: i64, now: i64) -> Line<'static> {
    if fetched_at <= 0 {
        return dim_line("updated: never");
    }
    let age = (now - fetched_at).max(0);
    let color = if age > 6 * 3600 {
        RatatuiColor::Red
    } else if age > 3600 {
        RatatuiColor::Yellow
    } else {
        RatatuiColor::DarkGray
    };
    let ago = format_duration_until(now, fetched_at);
    let text = if ago == "now" {
        "updated just now".to_string()
    } else {
        format!("updated {ago} ago")
    };
    Line::from(Span::styled(text, Style::default().fg(color)))
}

/// A dim gray line for placeholder / hint text.
fn dim_line(text: &str) -> Line<'static> {
    Line::from(Span::styled(
        text.to_string(),
        Style::default().fg(RatatuiColor::DarkGray),
    ))
}

/// A red login-hint line shown when a provider's token needs a re-login.
fn login_hint_line(hint: &str) -> Line<'static> {
    Line::from(Span::styled(
        hint.to_string(),
        Style::default()
            .fg(RatatuiColor::Red)
            .add_modifier(Modifier::BOLD),
    ))
}

/// Resolved band arrangement (pure; independent of the band `Rect`).
enum BandArrange {
    /// One row: an optional Provider Usage table cell, then the panel cells.
    SingleRow { table: bool },
    /// Two rows: `top` panels on the first row, the rest on the second; a
    /// trailing empty cell on the second row is filled with the table.
    TwoRow { top: usize, table_in_hole: bool },
}

/// Decides the band arrangement from band width, terminal height, and the
/// number of present quota panels.
///
/// Preference order: table + all panels in one row → panels-only in one row
/// (table dropped as redundant with the scrollable table) → a two-row grid →
/// a last-resort even split that may clip a gauge tail but never panics.
fn arrange_band(w: u16, area_h: u16, n: usize) -> BandArrange {
    if n == 0 {
        return BandArrange::SingleRow { table: true };
    }
    let panels_w = PANEL_MIN_W.saturating_mul(n as u16);
    if w >= BAND_TABLE_MIN_W + panels_w {
        BandArrange::SingleRow { table: true }
    } else if w >= panels_w {
        BandArrange::SingleRow { table: false }
    } else if area_h >= PANELS_2ROW_MIN_H {
        let top = n.div_ceil(2);
        BandArrange::TwoRow {
            top,
            table_in_hole: top * 2 > n,
        }
    } else {
        BandArrange::SingleRow { table: false }
    }
}

/// The band height fed to `main_layout` (computed before the band `Rect` exists).
fn band_height(arrange: &BandArrange, provider_rows: usize) -> u16 {
    match arrange {
        // The rendered table omits the overall row already included in
        // `provider_rows`: border(2) + header/margin(2) + rows(-1) + bar(1).
        BandArrange::SingleRow { table: true } => (provider_rows as u16)
            .saturating_add(4)
            .max(QUOTA_PANEL_MIN_HEIGHT),
        BandArrange::SingleRow { table: false } => QUOTA_PANEL_MIN_HEIGHT,
        BandArrange::TwoRow { .. } => QUOTA_PANEL_MIN_HEIGHT.saturating_mul(2),
    }
}

fn visible_band_height(
    area_height: u16,
    band_enabled: bool,
    arrange: &BandArrange,
    provider_rows: usize,
) -> Option<u16> {
    if !band_enabled || area_height < USAGE_PANELS_MIN_H {
        return None;
    }

    let height = band_height(arrange, provider_rows);
    (area_height >= height.saturating_add(USAGE_NON_PANEL_MIN_H)).then_some(height)
}

/// The band split into an optional table cell plus one cell per present panel.
struct BandGrid {
    table: Option<Rect>,
    panels: Vec<Rect>,
}

/// Splits a horizontal rect into `k` equal columns.
fn split_even(area: Rect, k: usize) -> Vec<Rect> {
    if k == 0 {
        return Vec::new();
    }
    let cons = vec![Constraint::Ratio(1, k as u32); k];
    RatatuiLayout::default()
        .direction(Direction::Horizontal)
        .constraints(cons)
        .split(area)
        .to_vec()
}

/// Splits the resolved band `Rect` into the table cell + ordered panel cells.
///
/// `panels` always has exactly `n` entries so the render dispatch can index it
/// by present-provider order without bounds concerns.
fn split_band(band: Rect, arrange: &BandArrange, n: usize) -> BandGrid {
    match *arrange {
        BandArrange::SingleRow { table } => {
            let mut cons: Vec<Constraint> = Vec::new();
            if table {
                cons.push(Constraint::Min(BAND_TABLE_MIN_W));
            }
            // Give each panel an equal share of whatever the table leaves.
            let panel_span = if table {
                band.width.saturating_sub(BAND_TABLE_MIN_W)
            } else {
                band.width
            };
            let pw = if n > 0 {
                (panel_span / n as u16).max(PANEL_MIN_W)
            } else {
                PANEL_MIN_W
            };
            for _ in 0..n {
                cons.push(Constraint::Length(pw));
            }
            let cells = RatatuiLayout::default()
                .direction(Direction::Horizontal)
                .constraints(cons)
                .split(band);
            let (table_rect, off) = if table {
                (Some(cells[0]), 1)
            } else {
                (None, 0)
            };
            BandGrid {
                table: table_rect,
                panels: cells[off..off + n].to_vec(),
            }
        }
        BandArrange::TwoRow { top, table_in_hole } => {
            let rows = RatatuiLayout::default()
                .direction(Direction::Vertical)
                .constraints([
                    Constraint::Length(QUOTA_PANEL_MIN_HEIGHT),
                    Constraint::Length(QUOTA_PANEL_MIN_HEIGHT),
                ])
                .split(band);
            let bottom = n - top;
            let row0 = split_even(rows[0], top);
            let row1 = split_even(rows[1], bottom + table_in_hole as usize);
            let mut panels = row0;
            panels.extend_from_slice(&row1[..bottom]);
            let table_rect = table_in_hole.then(|| row1[bottom]);
            BandGrid {
                table: table_rect,
                panels,
            }
        }
    }
}

/// Builds a quota-panel block: provider title on the left, plus a red bold
/// `LIMIT` flag right-aligned in the top border when a cap is hit. Shared by
/// both panels so they flag limits identically.
fn quota_block(title: &str, border: RatatuiColor, limit_reached: bool) -> Block<'static> {
    let mut block = Block::default()
        .borders(Borders::ALL)
        .title(Line::from(title.to_string()))
        .border_style(Style::default().fg(border));
    if limit_reached {
        block = block.title(
            Line::from(Span::styled(
                "LIMIT ",
                Style::default()
                    .fg(RatatuiColor::Red)
                    .add_modifier(Modifier::BOLD),
            ))
            .right_aligned(),
        );
    }
    block
}

/// Renders the Claude quota panel (5h / 7d / scoped gauges + balance +
/// staleness + login hint).
fn render_claude_quota(f: &mut Frame, area: Rect, claude: &ClaudeQuotaSnapshot, now: i64) {
    let block = quota_block(" Claude ", CLAUDE_COLOR, claude.limit_reached);

    let mut lines: Vec<Line> = Vec::new();
    if let Some(plan) = &claude.plan_type {
        lines.push(plan_line(plan));
    }
    // Track windows separately so a lone Plan line does not count as "has data".
    let mut has_data = false;
    if let Some(w) = &claude.five_hour {
        lines.push(quota_gauge_line("5h", w, now));
        has_data = true;
    }
    if let Some(w) = &claude.seven_day {
        lines.push(quota_gauge_line("7d", w, now));
        has_data = true;
    }
    // The per-model weekly cap (Fable today) is volatile on Anthropic's side, so
    // it is only drawn when both the window and its model label are present.
    if let (Some(w), Some(label)) = (&claude.scoped_weekly, &claude.scoped_label) {
        lines.push(quota_gauge_line(label, w, now));
        has_data = true;
    }
    if has_data {
        lines.push(claude_balance_line(claude));
        lines.push(staleness_line(claude.fetched_at, now));
    }
    if claude.needs_login {
        lines.push(login_hint_line(CLAUDE_LOGIN_HINT));
    } else if !has_data {
        lines.push(dim_line("no rate-limit data"));
    }

    f.render_widget(Paragraph::new(lines).block(block), area);
}

/// Renders the Codex quota panel (plan, 5h / 7d gauges, credits, extras,
/// staleness).
fn render_codex_quota(f: &mut Frame, area: Rect, codex: &CodexQuotaSnapshot, now: i64) {
    let title = match codex.source {
        QuotaSource::Api => " Codex ",
        QuotaSource::SessionFallback => " Codex (session) ",
        QuotaSource::None => " Codex ",
    };
    let block = quota_block(title, CODEX_COLOR, codex.limit_reached == Some(true));

    let lines: Vec<Line> = if codex.source == QuotaSource::None {
        let mut v = vec![dim_line("no Codex quota")];
        if codex.needs_login {
            v.push(login_hint_line(CODEX_LOGIN_HINT));
        } else {
            v.push(dim_line("(no auth.json / sessions)"));
        }
        v
    } else {
        let mut v = vec![plan_line(codex.plan_type.as_deref().unwrap_or("?"))];

        if let Some(w) = &codex.primary {
            v.push(quota_gauge_line("5h", w, now));
        }
        if let Some(w) = &codex.secondary {
            v.push(quota_gauge_line("7d", w, now));
        }
        // Keep session-fallback data visible but flag the re-login (S3).
        if codex.needs_login {
            v.push(login_hint_line(CODEX_LOGIN_HINT));
        } else {
            v.push(credits_line(codex));
            if let Some(extra) = codex_extras_line(codex) {
                v.push(extra);
            }
        }
        v.push(staleness_line(codex.fetched_at, now));
        v
    };

    f.render_widget(Paragraph::new(lines).block(block), area);
}

/// Renders the Copilot quota panel (plan, premium percent gauge, premium
/// request-count gauge, staleness + login hint).
fn render_copilot_quota(f: &mut Frame, area: Rect, copilot: &CopilotQuotaSnapshot, now: i64) {
    let block = quota_block(" Copilot ", COPILOT_COLOR, copilot.limit_reached);

    let mut lines: Vec<Line> = Vec::new();
    if let Some(plan) = &copilot.plan_type {
        lines.push(plan_line(plan));
    }
    if let Some(w) = &copilot.premium {
        lines.push(quota_gauge_line("prem", w, now));
        // A second gauge showing the premium requests as used/total counts.
        if let (Some(rem), Some(total)) = (copilot.premium_remaining, copilot.premium_entitlement)
            && total > 0
        {
            let used = (total - rem).max(0);
            let pct = (used as f64 / total as f64) * 100.0;
            lines.push(quota_gauge_line_value(
                "reqs",
                pct,
                &format!("{used}/{total}"),
            ));
        }
    } else if copilot.premium_unlimited {
        lines.push(dim_line("premium: unlimited"));
    }
    let has_content = !lines.is_empty();
    if has_content {
        lines.push(staleness_line(copilot.fetched_at, now));
    }
    if copilot.needs_login {
        lines.push(login_hint_line(COPILOT_LOGIN_HINT));
    } else if !has_content {
        lines.push(dim_line("no Copilot quota"));
    }

    f.render_widget(Paragraph::new(lines).block(block), area);
}

/// Renders the Cursor quota panel (plan, total / auto / api gauges, optional
/// on-demand spend, staleness + login hint).
fn render_cursor_quota(f: &mut Frame, area: Rect, cursor: &CursorQuotaSnapshot, now: i64) {
    let block = quota_block(" Cursor ", CURSOR_COLOR, cursor.limit_reached);

    let mut lines: Vec<Line> = Vec::new();
    if let Some(plan) = &cursor.plan_type {
        lines.push(plan_line(plan));
    }
    if let Some(w) = &cursor.total {
        lines.push(quota_gauge_line("total", w, now));
    }
    if let Some(w) = &cursor.auto {
        lines.push(quota_gauge_line("auto", w, now));
    }
    if let Some(w) = &cursor.api {
        lines.push(quota_gauge_line("api", w, now));
    }
    if let Some(d) = cursor.on_demand_dollars {
        lines.push(dim_line(&format!("on-demand: ${d:.2}")));
    }
    let has_content = !lines.is_empty();
    if has_content {
        lines.push(staleness_line(cursor.fetched_at, now));
    }
    if cursor.needs_login {
        lines.push(login_hint_line(CURSOR_LOGIN_HINT));
    } else if !has_content {
        lines.push(dim_line("no Cursor quota"));
    }

    f.render_widget(Paragraph::new(lines).block(block), area);
}

/// Builds the `Plan: <tier>` line shared by both panels.
fn plan_line(plan: &str) -> Line<'static> {
    Line::from(Span::styled(
        format!("Plan: {plan}"),
        Style::default().fg(RatatuiColor::Gray),
    ))
}

/// Builds the credits line for the Codex panel.
fn credits_line(codex: &CodexQuotaSnapshot) -> Line<'static> {
    let mut s = String::from("Credits: ");
    if codex.unlimited == Some(true) {
        s.push_str("unlimited");
    } else if let Some(bal) = &codex.credits_balance {
        s.push_str(bal);
    } else {
        s.push('-');
    }
    if let Some(n) = codex.reset_credits_available
        && n > 0
    {
        s.push_str(&format!("  +{n} reset"));
    }
    Line::from(Span::styled(s, Style::default().fg(RatatuiColor::Gray)))
}

/// Builds the optional Codex extras line (`~L-H msgs  ·  cap $X`), shown only
/// when the account has credit-funded messages or a configured spend cap.
fn codex_extras_line(codex: &CodexQuotaSnapshot) -> Option<Line<'static>> {
    let mut parts: Vec<String> = Vec::new();
    if let Some((low, high)) = codex.approx_messages {
        if low == high {
            parts.push(format!("~{low} msgs"));
        } else {
            parts.push(format!("~{low}-{high} msgs"));
        }
    }
    if let Some(cap) = codex.spend_limit {
        let cap_str = if cap.fract() == 0.0 {
            format!("${cap:.0}")
        } else {
            format!("${cap:.2}")
        };
        parts.push(format!("cap {cap_str}"));
    }
    if parts.is_empty() {
        return None;
    }
    Some(Line::from(Span::styled(
        parts.join("  ·  "),
        Style::default().fg(RatatuiColor::DarkGray),
    )))
}

/// Builds the balance line for the Claude panel (mirrors Codex's credits line).
fn claude_balance_line(claude: &ClaudeQuotaSnapshot) -> Line<'static> {
    let mut s = String::from("Balance: ");
    match &claude.balance {
        Some(b) => s.push_str(b),
        None => s.push('-'),
    }
    if let Some(used) = &claude.spend_used {
        s.push_str(&format!("    {used} used"));
    }
    Line::from(Span::styled(s, Style::default().fg(RatatuiColor::Gray)))
}

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

    fn stats(tokens: i64) -> ProviderStats {
        ProviderStats {
            total_tokens: tokens,
            total_cost: 0.0,
            days_count: 1,
        }
    }

    #[test]
    fn share_bar_fills_exact_width() {
        let (c, x, p) = (stats(710), stats(210), stats(80));
        let rows = vec![
            ProviderTotal::new(Provider::ClaudeCode, &c, false),
            ProviderTotal::new(Provider::Codex, &x, false),
            ProviderTotal::new(Provider::Copilot, &p, false),
        ];
        let bar = provider_share_bar(&rows, 20);
        let total: usize = bar.spans.iter().map(|s| s.content.chars().count()).sum();
        assert_eq!(total, 20, "segments must fill the whole bar width");
        // Largest share (Claude) gets the widest segment.
        assert!(bar.spans[0].content.chars().count() >= bar.spans[1].content.chars().count());
    }

    #[test]
    fn share_bar_placeholder_when_no_tokens() {
        let empty = stats(0);
        let rows = vec![ProviderTotal::new(Provider::ClaudeCode, &empty, false)];
        let bar = provider_share_bar(&rows, 10);
        let total: usize = bar.spans.iter().map(|s| s.content.chars().count()).sum();
        assert_eq!(total, 10);
        assert_eq!(
            bar.spans.len(),
            1,
            "no-data bar is a single placeholder span"
        );
    }

    #[test]
    fn share_bar_zero_width_is_empty() {
        let c = stats(100);
        let rows = vec![ProviderTotal::new(Provider::ClaudeCode, &c, false)];
        let bar = provider_share_bar(&rows, 0);
        let total: usize = bar.spans.iter().map(|s| s.content.chars().count()).sum();
        assert_eq!(total, 0);
    }

    #[test]
    fn arrange_wide_keeps_table_in_one_row() {
        // Plenty of width for the table + 4 panels.
        match arrange_band(BAND_TABLE_MIN_W + PANEL_MIN_W * 4, 40, 4) {
            BandArrange::SingleRow { table } => assert!(table),
            _ => panic!("expected single row with table"),
        }
    }

    #[test]
    fn arrange_medium_drops_table_but_stays_one_row() {
        // Enough for 4 panels but not the table alongside them.
        match arrange_band(PANEL_MIN_W * 4, 40, 4) {
            BandArrange::SingleRow { table } => assert!(!table),
            _ => panic!("expected single row without table"),
        }
    }

    #[test]
    fn arrange_narrow_tall_wraps_to_two_rows() {
        match arrange_band(80, PANELS_2ROW_MIN_H, 4) {
            BandArrange::TwoRow { top, table_in_hole } => {
                assert_eq!(top, 2);
                assert!(!table_in_hole, "even count fills both rows");
            }
            _ => panic!("expected two-row grid"),
        }
    }

    #[test]
    fn arrange_three_panels_fills_hole_with_table() {
        match arrange_band(80, PANELS_2ROW_MIN_H, 3) {
            BandArrange::TwoRow { top, table_in_hole } => {
                assert_eq!(top, 2);
                assert!(table_in_hole, "odd count leaves a hole for the table");
            }
            _ => panic!("expected two-row grid"),
        }
    }

    #[test]
    fn arrange_narrow_short_falls_back_to_single_row() {
        // Too narrow for one row and too short for two: last-resort even split.
        match arrange_band(80, PANELS_2ROW_MIN_H - 1, 4) {
            BandArrange::SingleRow { table } => assert!(!table),
            _ => panic!("expected single-row fallback"),
        }
    }

    #[test]
    fn arrange_zero_panels_is_table_only() {
        match arrange_band(100, 40, 0) {
            BandArrange::SingleRow { table } => assert!(table),
            _ => panic!("expected table-only row"),
        }
    }

    #[test]
    fn band_height_preserves_all_provider_rows() {
        let arrange = BandArrange::SingleRow { table: true };

        assert_eq!(visible_band_height(22, true, &arrange, 8), Some(12));
        assert_eq!(visible_band_height(22, true, &arrange, 9), None);
        assert_eq!(visible_band_height(23, true, &arrange, 9), Some(13));
    }

    #[test]
    fn disabled_band_stays_hidden() {
        let arrange = BandArrange::SingleRow { table: true };
        assert_eq!(visible_band_height(40, false, &arrange, 9), None);
    }

    #[test]
    fn split_band_always_yields_exactly_n_panels() {
        let area = Rect::new(0, 0, 200, 16);
        for n in 0..=4 {
            let arrange = arrange_band(area.width, area.height, n);
            let grid = split_band(area, &arrange, n);
            assert_eq!(grid.panels.len(), n, "n={n}");
        }
    }

    #[test]
    fn split_band_two_row_three_panels_has_table_in_hole() {
        let area = Rect::new(0, 0, 80, 16);
        let arrange = BandArrange::TwoRow {
            top: 2,
            table_in_hole: true,
        };
        let grid = split_band(area, &arrange, 3);
        assert_eq!(grid.panels.len(), 3);
        assert!(grid.table.is_some(), "the hole is filled with the table");
    }
}