ai-usagebar 0.16.0

Waybar widget + TUI for AI plan usage across Anthropic, OpenAI, Z.AI, OpenRouter, DeepSeek, Kimi, and Antigravity
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
//! TUI rendering — Bubble Tea-style shell + vendor detail card + footer.

use ratatui::Frame;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::text::{Line, Span};
use ratatui::widgets::Paragraph;
use ratatui_bubbletea_components::{Help, KeyBinding, ListItem, SelectList};

use crate::format::local_time_hms;
use crate::tui::app::App;
use crate::tui::app::TabId;
use crate::tui::app::TabState;
use crate::tui::panels;
use crate::tui::style::bubble_theme;
use crate::vendor::VendorId;

const WIDE_LAYOUT_MIN_WIDTH: u16 = 86;
const SIDEBAR_WIDTH: u16 = 28;

pub fn draw(f: &mut Frame, app: &App) {
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(3), // header
            Constraint::Min(1),    // nav + active panel
            Constraint::Length(1), // footer
        ])
        .split(f.area());

    draw_header(f, app, chunks[0]);
    draw_body(f, app, chunks[1]);
    draw_footer(f, app, chunks[2]);

    // Settings still floats on top of everything.
    if let Some(s) = &app.settings {
        crate::tui::settings::render(f, f.area(), s, &app.theme);
    }
}

/// The dashboard body, plus the context view docked into it when open: `full`
/// takes it over, `split` sits beside it, `bottom` sits below it.
fn draw_body(f: &mut Frame, app: &App, area: Rect) {
    use crate::config::ContextLayout;
    use crate::tui::context;

    let Some(state) = &app.context else {
        draw_main(f, app, area);
        return;
    };
    match state.layout {
        ContextLayout::Full => context::render(f, area, state, &app.theme),
        ContextLayout::Split => {
            let cols = Layout::default()
                .direction(Direction::Horizontal)
                .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
                .split(area);
            draw_main(f, app, cols[0]);
            context::render(f, cols[1], state, &app.theme);
        }
        ContextLayout::Bottom => {
            let rows = Layout::default()
                .direction(Direction::Vertical)
                .constraints([Constraint::Percentage(50), Constraint::Percentage(50)])
                .split(area);
            draw_main(f, app, rows[0]);
            context::render(f, rows[1], state, &app.theme);
        }
    }
}

fn vendor_label(id: VendorId) -> &'static str {
    match id {
        VendorId::Anthropic => "Claude",
        VendorId::AnthropicApi => "Anthropic API",
        VendorId::Openai => "OpenAI",
        VendorId::Zai => "GLM (Z.AI)",
        VendorId::Openrouter => "OpenRouter",
        VendorId::Deepseek => "DeepSeek",
        VendorId::Kimi => "Kimi",
        VendorId::Kilo => "Kilo",
        VendorId::Novita => "Novita",
        VendorId::Moonshot => "Moonshot",
        VendorId::Grok => "Grok",
        VendorId::Antigravity => "Antigravity",
    }
}

fn compact_vendor_label(id: VendorId) -> &'static str {
    match id {
        VendorId::Anthropic => "Claude",
        VendorId::AnthropicApi => "Anthropic API",
        VendorId::Openai => "OpenAI",
        VendorId::Zai => "Z.AI",
        VendorId::Openrouter => "OpenRouter",
        VendorId::Deepseek => "DeepSeek",
        VendorId::Kimi => "Kimi",
        VendorId::Kilo => "Kilo",
        VendorId::Novita => "Novita",
        VendorId::Moonshot => "Moonshot",
        VendorId::Grok => "Grok",
        VendorId::Antigravity => "Antigravity",
    }
}

/// Tab label for the header/sidebar/detail title. A named Anthropic account
/// (#14/#17) appends its label, e.g. `Claude · work`; a plain vendor tab is
/// just the vendor name.
fn tab_label(tab: &TabId) -> String {
    match &tab.account {
        Some(acct) => format!("{} · {}", vendor_label(tab.vendor), acct),
        None => vendor_label(tab.vendor).to_string(),
    }
}

/// Compact variant for the narrow top-nav strip.
fn compact_tab_label(tab: &TabId) -> String {
    match &tab.account {
        Some(acct) => format!("{} · {}", compact_vendor_label(tab.vendor), acct),
        None => compact_vendor_label(tab.vendor).to_string(),
    }
}

fn draw_header(f: &mut Frame, app: &App, area: Rect) {
    let theme = bubble_theme(&app.theme);
    let block = theme.titled_block(" ai-usagebar ");
    let inner = block.inner(area);
    f.render_widget(block, area);

    let active = app
        .active_tab_id()
        .map(tab_label)
        .unwrap_or_else(|| "no vendor".to_string());
    let line = Line::from(vec![
        theme.accent("  Usage dashboard"),
        theme.muted(" · "),
        theme.span(format!("{} tabs", app.tabs_meta.len())),
        theme.muted(" · "),
        theme.span(format!("active {active}")),
        theme.muted(" · "),
        theme.muted(header_refresh_text(app)),
    ]);
    f.render_widget(Paragraph::new(line), inner);
}

/// The header's refresh stamp, read from the ACTIVE tab's own `fetched_at`.
///
/// This used to be a single `App::last_refresh` bumped by whichever vendor
/// finished last, so a tab that was still loading — or had failed minutes ago —
/// advertised a sibling's success as its own. A tab with no landed response has
/// no time to show, so it gets the same `—` the panels use for an unknown
/// fetched-at rather than a borrowed or invented one.
fn header_refresh_text(app: &App) -> String {
    let fetched_at = match app.tabs.get(app.active) {
        Some(TabState::Ready(ready)) => ready.fetched_at,
        _ => None,
    };
    match fetched_at {
        Some(at) => format!("last refresh {}", local_time_hms(at)),
        None => "last refresh —".to_string(),
    }
}

fn draw_main(f: &mut Frame, app: &App, area: Rect) {
    if area.width >= WIDE_LAYOUT_MIN_WIDTH {
        let chunks = Layout::default()
            .direction(Direction::Horizontal)
            .constraints([Constraint::Length(SIDEBAR_WIDTH), Constraint::Min(1)])
            .split(area);
        draw_sidebar(f, app, chunks[0]);
        draw_detail(f, app, chunks[1]);
    } else {
        let chunks = Layout::default()
            .direction(Direction::Vertical)
            .constraints([Constraint::Length(3), Constraint::Min(1)])
            .split(area);
        draw_top_nav(f, app, chunks[0]);
        draw_detail(f, app, chunks[1]);
    }
}

fn draw_sidebar(f: &mut Frame, app: &App, area: Rect) {
    let theme = bubble_theme(&app.theme);
    let block = theme
        .titled_block(" vendors ")
        .border_style(theme.focused_border);
    let inner = block.inner(area);
    f.render_widget(block, area);

    let items = app
        .tabs_meta
        .iter()
        .enumerate()
        .map(|(index, tab)| {
            ListItem::new(tab_label(tab)).description(tab_status(app.tabs.get(index)))
        })
        .collect::<Vec<_>>();
    let mut list = SelectList::new(items).theme(theme);
    list.select(Some(app.active));
    f.render_widget(&list, inner);
}

fn draw_top_nav(f: &mut Frame, app: &App, area: Rect) {
    let theme = bubble_theme(&app.theme);
    let block = theme
        .titled_block(" vendors ")
        .border_style(theme.focused_border);
    let inner = block.inner(area);
    f.render_widget(block, area);

    let mut spans = vec![theme.muted(" ")];
    for (index, tab) in app.tabs_meta.iter().enumerate() {
        if index > 0 {
            spans.push(theme.muted("  "));
        }
        let selected = index == app.active;
        let marker = if selected {
            theme.symbols.selected
        } else {
            theme.symbols.bullet
        };
        let marker_style = if selected { theme.accent } else { theme.muted };
        let label_style = if selected { theme.selected } else { theme.text };
        spans.push(Span::styled(marker, marker_style));
        spans.push(theme.span(" "));
        spans.push(Span::styled(compact_tab_label(tab), label_style));
    }
    f.render_widget(Paragraph::new(Line::from(spans)), inner);
}

fn draw_detail(f: &mut Frame, app: &App, area: Rect) {
    let theme = bubble_theme(&app.theme);
    let title = app
        .active_tab_id()
        .map(|tab| format!(" {} ", tab_label(tab)))
        .unwrap_or_else(|| " details ".to_string());
    let block = theme.titled_block(title);
    let inner = block.inner(area);
    f.render_widget(block, area);

    let Some(tab) = app.tabs.get(app.active) else {
        return;
    };
    let sections = panels::sections_for(tab, chrono::Utc::now(), 5);
    panels::render(f, inner, &app.theme, &sections);
}

fn tab_status(tab: Option<&TabState>) -> &'static str {
    match tab {
        Some(TabState::Loading) => "fetching",
        Some(TabState::Error(_)) => "error",
        Some(TabState::Ready(ready)) if ready.stale => "stale cache",
        Some(TabState::Ready(ready))
            if ready
                .last_error
                .as_ref()
                .is_some_and(|(code, _)| *code != 0) =>
        {
            "cached"
        }
        Some(TabState::Ready(_)) => "ready",
        None => "waiting",
    }
}

fn draw_footer(f: &mut Frame, app: &App, area: ratatui::layout::Rect) {
    // The "updated HH:MM:SS" suffix used to live here, but it was
    // (a) redundant with the per-tab "Updated …" now right-aligned on the
    // title row of every panel, and (b) prone to getting cropped on narrow
    // 875x600 windows. Keep the footer to just the keybinding hints.
    let theme = bubble_theme(&app.theme);
    let mut bindings = vec![
        KeyBinding::with_keys(["tab", "h/l"], "switch"),
        KeyBinding::new("r", "refresh"),
        KeyBinding::new("R", "refresh all"),
        KeyBinding::new("s", "settings"),
    ];
    if app.context_enabled {
        bindings.push(KeyBinding::new("c", "context"));
    }
    bindings.push(KeyBinding::with_keys(["q", "esc"], "quit"));
    let help = Help::new(bindings).theme(theme);
    f.render_widget(&help, area);
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::theme::Theme;
    use crate::tui::app::ReadyTab;
    use crate::usage::{OpenRouterSnapshot, VendorSnapshot};
    use chrono::{DateTime, TimeZone, Utc};

    fn ready_at(fetched_at: Option<DateTime<Utc>>) -> TabState {
        TabState::Ready(Box::new(ReadyTab {
            snapshot: VendorSnapshot::Openrouter(OpenRouterSnapshot {
                label: "test".into(),
                total_credits: 0.0,
                total_usage: 0.0,
                usage_daily: 0.0,
                usage_weekly: 0.0,
                usage_monthly: 0.0,
                is_free_tier: false,
                limit: None,
                limit_remaining: None,
            }),
            stale: false,
            last_error: None,
            fetched_at,
        }))
    }

    // `App::with_theme(.., Theme::default())` rather than `App::new`, which
    // would read the real Omarchy theme file + `$HOME`. The header stamp under
    // test is theme-agnostic.
    fn app_with(tabs: Vec<TabState>) -> App {
        let mut app = App::with_theme(
            vec![
                TabId::vendor(VendorId::Anthropic),
                TabId::vendor(VendorId::Openrouter),
            ],
            Theme::default(),
        );
        app.tabs = tabs;
        app
    }

    #[test]
    fn header_refresh_follows_the_active_tab() {
        let anthropic_at = Utc.with_ymd_and_hms(2026, 5, 23, 12, 0, 0).unwrap();
        let openrouter_at = Utc.with_ymd_and_hms(2026, 5, 23, 9, 30, 0).unwrap();
        let mut app = app_with(vec![
            ready_at(Some(anthropic_at)),
            ready_at(Some(openrouter_at)),
        ]);

        // Compare against the formatting helper, not a literal, so the test
        // doesn't depend on the machine's timezone.
        let anthropic_header = format!("last refresh {}", local_time_hms(anthropic_at));
        let openrouter_header = format!("last refresh {}", local_time_hms(openrouter_at));
        assert_ne!(anthropic_header, openrouter_header);

        assert_eq!(header_refresh_text(&app), anthropic_header);
        app.next_tab();
        assert_eq!(header_refresh_text(&app), openrouter_header);
    }

    #[test]
    fn header_refresh_is_dash_when_active_tab_never_fetched() {
        // The sibling's successful fetch is exactly what the old global clock
        // would have displayed here.
        let sibling = ready_at(Some(Utc.with_ymd_and_hms(2026, 5, 23, 12, 0, 0).unwrap()));
        let mut app = app_with(vec![TabState::Loading, sibling]);
        assert_eq!(header_refresh_text(&app), "last refresh —");

        app.tabs[0] = TabState::Error("401 Unauthorized".into());
        assert_eq!(header_refresh_text(&app), "last refresh —");
    }

    #[test]
    fn header_refresh_is_dash_when_ready_tab_has_no_fetched_at() {
        // Ready but the cache never reported an age — show nothing rather than
        // passing off "now" as a response time.
        let app = app_with(vec![ready_at(None), TabState::Loading]);
        assert_eq!(header_refresh_text(&app), "last refresh —");
    }

    fn app_with_context(layout: crate::config::ContextLayout) -> App {
        let mut app = app_with(vec![TabState::Loading, TabState::Loading]);
        app.context_enabled = true;
        app.context = Some({
            let mut state = crate::tui::context::ContextState::new(layout);
            state.apply_scan(0, Err("scan error".into()));
            state
        });
        app
    }

    fn body_text(app: &App) -> String {
        use ratatui::Terminal;
        use ratatui::backend::TestBackend;
        let mut terminal = Terminal::new(TestBackend::new(160, 40)).unwrap();
        terminal.draw(|frame| draw(frame, app)).unwrap();
        terminal
            .backend()
            .buffer()
            .content()
            .iter()
            .map(|cell| cell.symbol())
            .collect::<Vec<_>>()
            .concat()
    }

    #[test]
    fn full_layout_takes_the_body_and_hides_the_vendor_sidebar() {
        use crate::config::ContextLayout;
        let out = body_text(&app_with_context(ContextLayout::Full));
        assert!(out.contains("Claude context"), "{out}");
        assert!(
            !out.contains("vendors"),
            "full layout must not leave the dashboard around it"
        );
    }

    #[test]
    fn split_and_bottom_layouts_keep_the_dashboard_visible() {
        use crate::config::ContextLayout;
        for layout in [ContextLayout::Split, ContextLayout::Bottom] {
            let out = body_text(&app_with_context(layout));
            assert!(out.contains("Claude context"), "{layout:?}: {out}");
            assert!(out.contains("vendors"), "{layout:?}: {out}");
        }
    }

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

        fn rendered(mut app: App, enabled: bool) -> String {
            app.context_enabled = enabled;
            let mut terminal = Terminal::new(TestBackend::new(160, 24)).unwrap();
            terminal.draw(|frame| draw(frame, &app)).unwrap();
            terminal
                .backend()
                .buffer()
                .content()
                .iter()
                .map(|cell| cell.symbol())
                .collect::<Vec<_>>()
                .concat()
        }

        let disabled = rendered(app_with(vec![TabState::Loading, TabState::Loading]), false);
        assert!(!disabled.contains("context"));

        let enabled = rendered(app_with(vec![TabState::Loading, TabState::Loading]), true);
        assert!(enabled.contains("context"));
    }
}