1use chrono::{DateTime, Utc};
13use ratatui::Frame;
14use ratatui::layout::{Constraint, Layout, Rect};
15use ratatui::style::{Modifier, Style};
16use ratatui::text::{Line, Span};
17use ratatui::widgets::Paragraph;
18use ratatui_bubbletea_components::{Progress, Spinner, SpinnerFrames};
19use ratatui_bubbletea_theme::BubbleTheme;
20
21use crate::countdown;
22use crate::format::local_time_hms;
23use crate::pacing::{self, PaceSeverity};
24use crate::pango::severity_for;
25use crate::theme::Theme;
26use crate::tui::app::TabState;
27use crate::tui::style::{bubble_theme, color, progress_theme, severity_color};
28use crate::usage::VendorSnapshot;
29
30pub enum Section {
33 Title { left: String, right: Option<String> },
38 Metric {
40 label: String,
41 pct: u16,
42 severity: PaceSeverity,
43 value_label: String,
44 footnote: String,
45 },
46 Text { label: String, value: String },
48 Block { label: String, body: Vec<String> },
50 Spacer,
52}
53
54pub(crate) struct SectionProjection {
59 pub section: Section,
60 pub reset_at: Option<DateTime<Utc>>,
61}
62
63struct SectionBuilder(Vec<SectionProjection>);
64
65impl SectionBuilder {
66 fn new(sections: Vec<Section>) -> Self {
67 Self(
68 sections
69 .into_iter()
70 .map(|section| {
71 assert!(
72 !matches!(section, Section::Metric { .. }),
73 "metric sections must declare reset metadata with push_metric"
74 );
75 SectionProjection {
76 section,
77 reset_at: None,
78 }
79 })
80 .collect(),
81 )
82 }
83
84 fn push(&mut self, section: Section) {
85 assert!(
86 !matches!(section, Section::Metric { .. }),
87 "metric sections must declare reset metadata with push_metric"
88 );
89 self.0.push(SectionProjection {
90 section,
91 reset_at: None,
92 });
93 }
94
95 fn push_metric(&mut self, section: Section, reset_at: Option<DateTime<Utc>>) {
96 assert!(matches!(section, Section::Metric { .. }));
97 self.0.push(SectionProjection { section, reset_at });
98 }
99}
100
101pub fn compact_cells(snapshot: &VendorSnapshot) -> (String, Vec<(String, PaceSeverity)>) {
107 let pct = |label: &str, p: i32| (format!("{label} {p}%"), severity_for(p));
108 let money = |v: f64| (format!("${v:.2}"), PaceSeverity::Low);
109 let ccy = |v: f64, c: &str| {
110 let s = match c {
111 "USD" => format!("${v:.2}"),
112 "CNY" => format!("¥{v:.2}"),
113 _ => format!("{v:.2} {c}"),
114 };
115 (s, PaceSeverity::Low)
116 };
117 let (plan, mut cells) = match snapshot {
118 VendorSnapshot::Anthropic(s) => {
119 let mut cells = vec![
120 pct("S", s.session.utilization_pct),
121 pct("W", s.weekly.utilization_pct),
122 ];
123 if let Some(sonnet) = &s.sonnet {
124 cells.push(pct("Son", sonnet.utilization_pct));
125 }
126 (s.plan.clone(), cells)
127 }
128 VendorSnapshot::AnthropicApi(s) => {
129 let cell = match s.pct() {
130 Some(p) => pct("spend", p),
131 None => (format!("${:.2}/mo", s.spent), PaceSeverity::Low),
132 };
133 (String::new(), vec![cell])
134 }
135 VendorSnapshot::Openai(s) => {
136 let mut cells = Vec::new();
137 if let Some(w) = &s.session {
138 cells.push(pct("5h", w.utilization_pct));
139 }
140 if let Some(w) = &s.weekly {
141 cells.push(pct("7d", w.utilization_pct));
142 }
143 if cells.is_empty() {
144 cells.push(("—".into(), PaceSeverity::Low));
145 }
146 (s.plan.clone(), cells)
147 }
148 VendorSnapshot::Zai(s) => {
149 let mut cells = Vec::new();
150 if let Some(w) = &s.session {
151 cells.push(pct("S", w.utilization_pct));
152 }
153 if let Some(w) = &s.weekly {
154 cells.push(pct("W", w.utilization_pct));
155 }
156 if cells.is_empty() {
157 cells.push(("—".into(), PaceSeverity::Low));
158 }
159 (s.plan.clone(), cells)
160 }
161 VendorSnapshot::Openrouter(s) => (String::new(), vec![money(s.balance())]),
162 VendorSnapshot::Deepseek(s) => (String::new(), vec![ccy(s.balance, &s.currency)]),
163 VendorSnapshot::Kimi(s) => (
164 s.plan.clone().unwrap_or_default(),
165 vec![pct("wk", s.weekly_pct()), pct("5h", s.window_pct())],
166 ),
167 VendorSnapshot::Kilo(s) => (String::new(), vec![money(s.balance)]),
168 VendorSnapshot::Novita(s) => (String::new(), vec![money(s.available)]),
169 VendorSnapshot::Moonshot(s) => (String::new(), vec![ccy(s.available, &s.currency)]),
170 VendorSnapshot::Grok(s) => (String::new(), vec![money(s.balance)]),
171 VendorSnapshot::SuperGrok(s) => (s.plan.clone(), vec![pct(s.period.short(), s.weekly_pct)]),
172 VendorSnapshot::Antigravity(s) => (
173 s.plan.clone(),
174 vec![
175 pct("S", s.session.utilization_pct),
176 pct("W", s.weekly.utilization_pct),
177 ],
178 ),
179 VendorSnapshot::Cursor(s) => (
180 s.plan.clone(),
181 vec![pct("auto", s.auto_pct), pct("premium", s.api_pct)],
182 ),
183 VendorSnapshot::Minimax(s) => (
184 s.plan.clone(),
185 vec![
186 pct("S", s.session.utilization_pct),
187 pct("W", s.weekly.utilization_pct),
188 ],
189 ),
190 VendorSnapshot::Kiro(s) => (s.plan.clone(), vec![pct("credits", s.pct())]),
191 VendorSnapshot::NousResearch(s) => {
192 let cell = s
193 .usage_percent()
194 .map(|value| pct("usage", value.round().clamp(0.0, 100.0) as i32))
195 .unwrap_or_else(|| ("—".into(), PaceSeverity::Low));
196 (s.plan.clone().unwrap_or_default(), vec![cell])
197 }
198 VendorSnapshot::OpenCodeGo(s) => {
199 let cells = [
200 ("rolling", s.rolling.as_ref()),
201 ("weekly", s.weekly.as_ref()),
202 ("monthly", s.monthly.as_ref()),
203 ]
204 .into_iter()
205 .filter_map(|(label, window)| {
206 window.map(|window| pct(label, window.percent.round().clamp(0.0, 100.0) as i32))
207 })
208 .collect();
209 ("OpenCode Go".into(), cells)
210 }
211 };
212
213 for (text, _) in &mut cells {
214 *text = crate::display::sanitize_untrusted_field(text);
215 }
216 (crate::display::sanitize_untrusted_field(&plan), cells)
217}
218
219pub fn headline_pct(snapshot: &VendorSnapshot) -> Option<i32> {
224 match snapshot {
225 VendorSnapshot::Anthropic(s) => [
226 Some(s.session.utilization_pct),
227 Some(s.weekly.utilization_pct),
228 s.sonnet.as_ref().map(|w| w.utilization_pct),
229 ]
230 .into_iter()
231 .flatten()
232 .max(),
233 VendorSnapshot::AnthropicApi(s) => s.pct(),
234 VendorSnapshot::Openai(s) => [
235 s.session.as_ref().map(|w| w.utilization_pct),
236 s.weekly.as_ref().map(|w| w.utilization_pct),
237 ]
238 .into_iter()
239 .flatten()
240 .max(),
241 VendorSnapshot::Zai(s) => [
242 s.session.as_ref().map(|w| w.utilization_pct),
243 s.weekly.as_ref().map(|w| w.utilization_pct),
244 ]
245 .into_iter()
246 .flatten()
247 .max(),
248 VendorSnapshot::Kimi(s) => Some(s.weekly_pct().max(s.window_pct())),
249 VendorSnapshot::Antigravity(s) => {
250 Some(s.session.utilization_pct.max(s.weekly.utilization_pct))
251 }
252 VendorSnapshot::Cursor(s) => (!s.unlimited).then_some(s.total_pct),
253 VendorSnapshot::Minimax(s) => Some(s.session.utilization_pct.max(s.weekly.utilization_pct)),
254 VendorSnapshot::Kiro(s) => Some(s.pct()),
255 VendorSnapshot::NousResearch(s) => s
256 .usage_percent()
257 .map(|value| value.round().clamp(0.0, 100.0) as i32),
258 VendorSnapshot::OpenCodeGo(s) => [
259 s.rolling
260 .as_ref()
261 .map(|window| window.percent.round() as i32),
262 s.weekly
263 .as_ref()
264 .map(|window| window.percent.round() as i32),
265 s.monthly
266 .as_ref()
267 .map(|window| window.percent.round() as i32),
268 ]
269 .into_iter()
270 .flatten()
271 .max(),
272 VendorSnapshot::SuperGrok(s) => Some(s.weekly_pct),
273 VendorSnapshot::Openrouter(_)
274 | VendorSnapshot::Deepseek(_)
275 | VendorSnapshot::Kilo(_)
276 | VendorSnapshot::Novita(_)
277 | VendorSnapshot::Moonshot(_)
278 | VendorSnapshot::Grok(_) => None,
279 }
280}
281
282pub fn sections_for(tab: &TabState, now: DateTime<Utc>, pace_tolerance: u32) -> Vec<Section> {
284 sections_with_metadata_for(tab, now, pace_tolerance)
285 .into_iter()
286 .map(|projected| projected.section)
287 .collect()
288}
289
290pub(crate) fn sections_with_metadata_for(
293 tab: &TabState,
294 now: DateTime<Utc>,
295 pace_tolerance: u32,
296) -> Vec<SectionProjection> {
297 let mut sections = match tab {
298 TabState::Loading => SectionBuilder::new(vec![
299 Section::Spacer,
300 Section::Text {
301 label: "".into(),
302 value: " Loading…".into(),
303 },
304 ]),
305 TabState::Error(e) => SectionBuilder::new(vec![
306 Section::Spacer,
307 Section::Text {
308 label: "Error".into(),
309 value: e.clone(),
310 },
311 Section::Spacer,
312 Section::Text {
313 label: "".into(),
314 value: "Press `r` to retry, `q` to quit.".into(),
315 },
316 ]),
317 TabState::Ready(r) => {
318 let snapshot = &r.snapshot;
319 let last_error = &r.last_error;
320 let mut sections = match snapshot {
321 VendorSnapshot::Anthropic(s) => anthropic_sections(s, now, pace_tolerance),
322 VendorSnapshot::AnthropicApi(s) => anthropic_api_sections(s),
323 VendorSnapshot::Openai(s) => openai_sections(s, now, pace_tolerance),
324 VendorSnapshot::Zai(s) => zai_sections(s, now),
325 VendorSnapshot::Openrouter(s) => openrouter_sections(s),
326 VendorSnapshot::Deepseek(s) => deepseek_sections(s),
327 VendorSnapshot::Kimi(s) => kimi_sections(s, now, pace_tolerance),
328 VendorSnapshot::Kilo(s) => kilo_sections(s),
329 VendorSnapshot::Novita(s) => novita_sections(s),
330 VendorSnapshot::Moonshot(s) => moonshot_sections(s),
331 VendorSnapshot::Grok(s) => grok_sections(s),
332 VendorSnapshot::SuperGrok(s) => supergrok_sections(s, now),
333 VendorSnapshot::Antigravity(s) => antigravity_sections(s, now),
334 VendorSnapshot::Cursor(s) => cursor_sections(s, now),
335 VendorSnapshot::Minimax(s) => minimax_sections(s, now, pace_tolerance),
336 VendorSnapshot::Kiro(s) => kiro_sections(s, now),
337 VendorSnapshot::NousResearch(s) => nous_sections(s, now),
338 VendorSnapshot::OpenCodeGo(s) => opencode_go_sections(s, now),
339 };
340 let updated = match r.fetched_at {
344 Some(at) => format!("Updated {}", local_time_hms(at)),
345 None => "Updated —".to_string(),
346 };
347 if let Some(SectionProjection {
348 section: Section::Title { right, .. },
349 ..
350 }) = sections.0.first_mut()
351 {
352 *right = Some(updated);
353 }
354 if let Some((label, msg)) = warning_label(snapshot, last_error) {
356 sections.push(Section::Spacer);
357 sections.push(Section::Text { label, value: msg });
358 }
359 sections
360 }
361 };
362 for projected in &mut sections.0 {
363 sanitize_section(&mut projected.section);
364 }
365 sections.0
366}
367
368fn sanitize_section(section: &mut Section) {
371 let clean = |value: &mut String| {
372 *value = crate::display::sanitize_untrusted_field(value);
373 };
374 match section {
375 Section::Title { left, right } => {
376 clean(left);
377 if let Some(right) = right {
378 clean(right);
379 }
380 }
381 Section::Metric {
382 label,
383 value_label,
384 footnote,
385 ..
386 } => {
387 clean(label);
388 clean(value_label);
389 clean(footnote);
390 }
391 Section::Text { label, value } => {
392 clean(label);
393 clean(value);
394 }
395 Section::Block { label, body } => {
396 clean(label);
397 for line in body {
398 clean(line);
399 }
400 }
401 Section::Spacer => {}
402 }
403}
404
405fn warning_label(
409 snapshot: &VendorSnapshot,
410 last_error: &Option<(u16, String)>,
411) -> Option<(String, String)> {
412 let (code, message) = last_error.as_ref()?;
413 if *code != 0 {
414 return Some((format!("HTTP {code}"), message.clone()));
415 }
416 if message.is_empty() {
417 return None;
418 }
419 let label = if matches!(snapshot, VendorSnapshot::Kimi(_))
420 && matches!(
421 crate::kimi::vendor::warning_kind(*code, message),
422 crate::kimi::vendor::WarningKind::SchemaDrift
423 ) {
424 "Kimi API schema drift"
425 } else {
426 "Warning"
427 };
428 let value = if label == message {
431 String::new()
432 } else {
433 message.clone()
434 };
435 Some((label.into(), value))
436}
437
438fn anthropic_api_sections(s: &crate::usage::AnthropicApiSnapshot) -> SectionBuilder {
439 let mut v = SectionBuilder::new(vec![Section::Title {
440 left: "Anthropic API".into(),
441 right: None,
442 }]);
443 match (s.limit.filter(|l| *l > 0.0), s.pct()) {
444 (Some(limit), Some(pct)) => {
445 let p = pct.clamp(0, 100) as u16;
446 v.push_metric(
447 Section::Metric {
448 label: "Spend (mo)".into(),
449 pct: p,
450 severity: severity_for(pct),
451 value_label: format!("${:.2} of ${:.0}", s.spent, limit),
452 footnote: format!("{pct}% of monthly limit"),
453 },
454 None,
455 );
456 }
457 _ => {
458 v.push(Section::Text {
459 label: "Spend (mo)".into(),
460 value: format!("${:.2}", s.spent),
461 });
462 }
463 }
464 v.push(Section::Spacer);
465 v.push(Section::Text {
466 label: "".into(),
467 value: "Month-to-date cost via the Admin usage API.".into(),
468 });
469 v.push(Section::Text {
470 label: "".into(),
471 value: "Prepaid credit balance is Console-only (no API).".into(),
472 });
473 v.push(Section::Text {
474 label: "".into(),
475 value: "Excludes Priority Tier cost (not reported by this API).".into(),
476 });
477 v
478}
479
480fn anthropic_sections(
481 s: &crate::usage::AnthropicSnapshot,
482 now: DateTime<Utc>,
483 tol: u32,
484) -> SectionBuilder {
485 let mut v = SectionBuilder::new(vec![Section::Title {
486 left: format!("Claude {}", s.plan),
487 right: None,
488 }]);
489
490 push_window(&mut v, "Session (5h)", &s.session, now, tol, true);
491 push_window(&mut v, "Weekly (7d)", &s.weekly, now, tol, true);
492 if let Some(w) = &s.sonnet {
493 push_window(&mut v, "Sonnet only", w, now, tol, false);
494 }
495 for sw in &s.scoped {
496 push_window(
497 &mut v,
498 &format!("{} (7d)", sw.label),
499 &sw.window,
500 now,
501 tol,
502 false,
503 );
504 }
505 if let Some(e) = &s.extra {
506 v.push(Section::Spacer);
507 let pct = e.percent().clamp(0, 100) as u16;
508 let (value_label, footnote) = match e.fmt_limit() {
512 Some(l) => (
513 format!("{} of {}", e.fmt_spent(), l),
514 format!("{pct}% of monthly limit consumed"),
515 ),
516 None => (e.fmt_spent(), "no monthly limit reported".to_string()),
517 };
518 v.push_metric(
519 Section::Metric {
520 label: "Extra usage".into(),
521 pct,
522 severity: severity_for(pct as i32),
523 value_label,
524 footnote,
525 },
526 None,
527 );
528 }
529 v
530}
531
532fn openai_sections(
533 s: &crate::usage::OpenAiSnapshot,
534 now: DateTime<Utc>,
535 tol: u32,
536) -> SectionBuilder {
537 let mut v = SectionBuilder::new(vec![Section::Title {
538 left: s.plan.clone(),
539 right: None,
540 }]);
541 if let Some(session) = &s.session {
542 push_window(&mut v, "Codex 5h", session, now, tol, true);
543 }
544 if let Some(weekly) = &s.weekly {
545 push_window(&mut v, "Codex weekly", weekly, now, tol, true);
546 }
547 if s.session.is_none() && s.weekly.is_none() {
548 v.push(Section::Spacer);
549 v.push(Section::Text {
550 label: "".into(),
551 value: " no usage windows reported".into(),
552 });
553 }
554 if let Some(cr) = &s.code_review {
555 push_window(&mut v, "Code review", cr, now, tol, false);
556 }
557 if let Some(c) = &s.credits {
558 v.push(Section::Spacer);
559 let balance = if c.unlimited {
560 "unlimited".into()
561 } else {
562 c.balance.clone()
563 };
564 let mut body = vec![format!("balance: {}", balance)];
565 if let Some((lo, hi)) = c.approx_local_messages {
566 body.push(format!("≈ {lo}-{hi} local messages"));
567 }
568 if let Some((lo, hi)) = c.approx_cloud_messages {
569 body.push(format!("≈ {lo}-{hi} cloud messages"));
570 }
571 v.push(Section::Block {
572 label: "Credits".into(),
573 body,
574 });
575 }
576 v
577}
578
579fn zai_sections(s: &crate::usage::ZaiSnapshot, now: DateTime<Utc>) -> SectionBuilder {
580 let mut v = SectionBuilder::new(vec![Section::Title {
581 left: s.plan.clone(),
582 right: None,
583 }]);
584 if let Some(w) = &s.session {
585 push_window(&mut v, "Session (5h)", w, now, 5, false);
586 }
587 if let Some(w) = &s.weekly {
588 push_window(&mut v, "Weekly", w, now, 5, false);
589 }
590 if let Some(w) = &s.mcp {
591 push_window(&mut v, "MCP tools (monthly)", w, now, 5, false);
592 }
593 if s.session.is_none() && s.weekly.is_none() && s.mcp.is_none() {
594 v.push(Section::Spacer);
595 v.push(Section::Text {
596 label: "".into(),
597 value: " no usage windows reported".into(),
598 });
599 }
600 v
601}
602
603fn openrouter_sections(s: &crate::usage::OpenRouterSnapshot) -> SectionBuilder {
604 let mut v = SectionBuilder::new(vec![Section::Title {
605 left: s.label.clone(),
606 right: None,
607 }]);
608 let pct = s.consumed_pct().clamp(0, 100) as u16;
609 v.push(Section::Spacer);
610 v.push_metric(
611 Section::Metric {
612 label: "Credit balance".into(),
613 pct,
614 severity: severity_for(pct as i32),
615 value_label: format!("${:.2}", s.balance()),
616 footnote: format!(
617 "${:.2} of ${:.2} used ({pct}%)",
618 s.total_usage, s.total_credits
619 ),
620 },
621 None,
622 );
623 v.push(Section::Spacer);
624 v.push(Section::Block {
625 label: "Usage by period".into(),
626 body: vec![format!(
627 "today ${:.2} · week ${:.2} · month ${:.2}",
628 s.usage_daily, s.usage_weekly, s.usage_monthly
629 )],
630 });
631 if let (Some(limit), Some(rem)) = (s.limit, s.limit_remaining) {
632 v.push(Section::Spacer);
633 v.push(Section::Block {
634 label: "Per-key limit".into(),
635 body: vec![format!("${:.2} of ${:.2} remaining", rem, limit)],
636 });
637 }
638 v.push(Section::Spacer);
639 v.push(Section::Block {
640 label: "Tier".into(),
641 body: vec![if s.is_free_tier {
642 "free tier".into()
643 } else {
644 "paid tier".into()
645 }],
646 });
647 v
648}
649
650fn antigravity_sections(
654 s: &crate::usage::AntigravitySnapshot,
655 now: DateTime<Utc>,
656) -> SectionBuilder {
657 use crate::antigravity::vendor::{GROUP_PRIMARY, GROUP_THIRD_PARTY};
658
659 let mut v = SectionBuilder::new(vec![Section::Title {
660 left: s.plan.clone(),
661 right: None,
662 }]);
663 for (heading, primary, third_party) in [
664 ("Session", &s.session, s.third_party_session.as_ref()),
665 ("Weekly", &s.weekly, s.third_party_weekly.as_ref()),
666 ] {
667 v.push(Section::Spacer);
668 v.push(Section::Text {
669 label: heading.into(),
670 value: String::new(),
671 });
672 push_window(&mut v, GROUP_PRIMARY, primary, now, 5, false);
673 if let Some(w) = third_party {
674 push_window(&mut v, GROUP_THIRD_PARTY, w, now, 5, false);
675 }
676 }
677 v
678}
679
680fn cursor_sections(s: &crate::usage::CursorSnapshot, now: DateTime<Utc>) -> SectionBuilder {
681 let mut v = SectionBuilder::new(vec![Section::Title {
682 left: format!("Cursor {}", s.plan),
683 right: None,
684 }]);
685 if s.unlimited {
686 v.push(Section::Spacer);
687 v.push(Section::Text {
688 label: "Plan".into(),
689 value: "Unlimited — pools don't cap".into(),
690 });
691 } else {
692 v.push(Section::Spacer);
694 v.push_metric(
695 Section::Metric {
696 label: "Cursor Models".into(),
697 pct: s.auto_pct.clamp(0, 100) as u16,
698 severity: severity_for(s.auto_pct),
699 value_label: format!("{}%", s.auto_pct),
700 footnote: "Auto + Composer".into(),
701 },
702 s.reset_at,
703 );
704 v.push(Section::Spacer);
705 v.push_metric(
706 Section::Metric {
707 label: "Other Models".into(),
708 pct: s.api_pct.clamp(0, 100) as u16,
709 severity: severity_for(s.api_pct),
710 value_label: format!("{}%", s.api_pct),
711 footnote: format!(
712 "Named / API models · on-demand {}",
713 if s.on_demand_enabled { "on" } else { "off" }
714 ),
715 },
716 s.reset_at,
717 );
718 }
719 v.push(Section::Spacer);
720 v.push(Section::Text {
721 label: "Resets".into(),
722 value: countdown::format(s.reset_at, now),
723 });
724 v
725}
726
727fn nous_sections(s: &crate::nous::types::AccountSnapshot, now: DateTime<Utc>) -> SectionBuilder {
728 let mut sections = SectionBuilder::new(vec![Section::Title {
729 left: "Nous Research".into(),
730 right: None,
731 }]);
732 if let Some(value) = s.usage_percent() {
733 let pct = value.round().clamp(0.0, 100.0) as i32;
734 sections.push_metric(
735 Section::Metric {
736 label: "Usage".into(),
737 pct: pct as u16,
738 severity: severity_for(pct),
739 value_label: format!("{pct}%"),
740 footnote: "current period".into(),
741 },
742 s.current_period_end,
743 );
744 }
745 sections.push(Section::Spacer);
746 if let Some(remaining) = s.credits_remaining {
747 sections.push(Section::Text {
748 label: "Subscription credits".into(),
749 value: format!("{remaining:.2} remaining"),
750 });
751 }
752 if let Some(purchased) = s.purchased_credits_remaining {
753 sections.push(Section::Text {
754 label: "Top-up credits".into(),
755 value: format!("{purchased:.2} remaining"),
756 });
757 }
758 if let Some(total_usable) = s.total_usable_credits {
759 sections.push(Section::Text {
760 label: "Total usable credits".into(),
761 value: format!("{total_usable:.2}"),
762 });
763 }
764 if let Some(period_end) = s.current_period_end {
765 sections.push(Section::Text {
766 label: "Renews".into(),
767 value: countdown::format(Some(period_end), now),
768 });
769 }
770 sections
771}
772
773fn opencode_go_sections(
774 s: &crate::opencode_go::types::Usage,
775 now: DateTime<Utc>,
776) -> SectionBuilder {
777 let mut sections = SectionBuilder::new(vec![Section::Title {
778 left: "OpenCode Go".into(),
779 right: None,
780 }]);
781 for (label, window) in [
782 ("Rolling", s.rolling.as_ref()),
783 ("Weekly", s.weekly.as_ref()),
784 ("Monthly", s.monthly.as_ref()),
785 ] {
786 if let Some(window) = window {
787 let pct = window.percent.round().clamp(0.0, 100.0) as i32;
788 sections.push_metric(
789 Section::Metric {
790 label: label.into(),
791 pct: pct as u16,
792 severity: severity_for(pct),
793 value_label: format!("{pct}%"),
794 footnote: String::new(),
795 },
796 Some(window.resets_at),
797 );
798 sections.push(Section::Text {
799 label: "Resets".into(),
800 value: countdown::format(Some(window.resets_at), now),
801 });
802 }
803 }
804 sections
805}
806
807fn kiro_sections(s: &crate::usage::KiroSnapshot, now: DateTime<Utc>) -> SectionBuilder {
812 let pct = s.pct();
813 let mut v = SectionBuilder::new(vec![
814 Section::Title {
815 left: format!("Kiro {}", s.plan),
816 right: None,
817 },
818 Section::Spacer,
819 ]);
820 v.push_metric(
821 Section::Metric {
822 label: "Credits".into(),
823 pct: pct.clamp(0, 100) as u16,
824 severity: severity_for(pct),
825 value_label: format!("{pct}%"),
826 footnote: format!("{:.2} of {:.0}", s.used, s.limit),
827 },
828 s.reset_at,
829 );
830 v.push(Section::Spacer);
831 v.push(Section::Text {
832 label: "Resets".into(),
833 value: countdown::format(s.reset_at, now),
834 });
835 v
836}
837
838fn minimax_sections(
843 s: &crate::usage::MinimaxSnapshot,
844 now: DateTime<Utc>,
845 tol: u32,
846) -> SectionBuilder {
847 use crate::minimax::vendor::{POOL_GENERAL, POOL_VIDEO};
848
849 let mut v = SectionBuilder::new(vec![Section::Title {
850 left: s.plan.clone(),
851 right: None,
852 }]);
853 for (heading, general, video) in [
854 ("Session", &s.session, s.video_session.as_ref()),
855 ("Weekly", &s.weekly, s.video_weekly.as_ref()),
856 ] {
857 v.push(Section::Spacer);
858 v.push(Section::Text {
859 label: heading.into(),
860 value: String::new(),
861 });
862 push_window(&mut v, POOL_GENERAL, general, now, tol, true);
863 if let Some(w) = video {
864 push_window(&mut v, POOL_VIDEO, w, now, tol, true);
865 }
866 }
867 v
868}
869
870fn kilo_sections(s: &crate::usage::KiloSnapshot) -> SectionBuilder {
871 SectionBuilder::new(vec![
872 Section::Title {
873 left: s.label.clone(),
874 right: None,
875 },
876 Section::Spacer,
877 Section::Text {
878 label: "Balance".into(),
879 value: format!("${:.2}", s.balance),
880 },
881 ])
882}
883
884fn novita_sections(s: &crate::usage::NovitaSnapshot) -> SectionBuilder {
885 let mut v = SectionBuilder::new(vec![
886 Section::Title {
887 left: "Novita".into(),
888 right: None,
889 },
890 Section::Spacer,
891 Section::Text {
892 label: "Balance".into(),
893 value: format!("${:.2}", s.available),
894 },
895 Section::Block {
896 label: "Breakdown".into(),
897 body: vec![format!(
898 "top-up ${:.2} · credit limit ${:.2}",
899 s.cash, s.credit_limit
900 )],
901 },
902 ]);
903 if s.outstanding > 0.0 {
904 v.push(Section::Spacer);
905 v.push(Section::Block {
906 label: "Owed".into(),
907 body: vec![format!("${:.2}", s.outstanding)],
908 });
909 }
910 v
911}
912
913fn moonshot_sections(s: &crate::usage::MoonshotSnapshot) -> SectionBuilder {
914 let cur = &s.currency;
915 let fmt = |v: f64| match cur.as_str() {
916 "USD" => format!("${v:.2}"),
917 "CNY" => format!("¥{v:.2}"),
918 _ => format!("{v:.2} {cur}"),
919 };
920 SectionBuilder::new(vec![
921 Section::Title {
922 left: "Kimi (Moonshot)".into(),
923 right: None,
924 },
925 Section::Spacer,
926 Section::Text {
927 label: "Balance".into(),
928 value: fmt(s.available),
929 },
930 Section::Block {
931 label: "Breakdown".into(),
932 body: vec![format!("cash {} · voucher {}", fmt(s.cash), fmt(s.voucher))],
933 },
934 ])
935}
936
937fn grok_sections(s: &crate::usage::GrokSnapshot) -> SectionBuilder {
938 SectionBuilder::new(vec![
939 Section::Title {
940 left: "Grok (xAI)".into(),
941 right: None,
942 },
943 Section::Spacer,
944 Section::Text {
945 label: "Prepaid balance".into(),
946 value: format!("${:.2}", s.balance),
947 },
948 ])
949}
950
951fn supergrok_sections(s: &crate::usage::SuperGrokSnapshot, now: DateTime<Utc>) -> SectionBuilder {
952 let pct = s.weekly_pct;
953 let mut v = SectionBuilder::new(vec![
954 Section::Title {
955 left: s.plan.clone(),
956 right: None,
957 },
958 Section::Spacer,
959 ]);
960 v.push_metric(
961 Section::Metric {
962 label: format!("{} Build credits", s.period.label()),
963 pct: pct.clamp(0, 100) as u16,
964 severity: severity_for(pct),
965 value_label: format!("{pct}%"),
966 footnote: String::new(),
967 },
968 s.reset_at,
969 );
970 v.push(Section::Spacer);
971 v.push(Section::Text {
972 label: "Resets".into(),
973 value: countdown::format(s.reset_at, now),
974 });
975 if let Some(bal) = s.prepaid_balance {
976 v.push(Section::Spacer);
977 v.push(Section::Text {
978 label: "Prepaid API".into(),
979 value: format!("${bal:.2}"),
980 });
981 }
982 v
983}
984
985fn deepseek_sections(s: &crate::usage::DeepseekSnapshot) -> SectionBuilder {
986 let currency = &s.currency;
987 let fmt = |v: f64| match currency.as_str() {
988 "USD" => format!("${v:.2}"),
989 "CNY" => format!("¥{v:.2}"),
990 _ => format!("{v:.2} {currency}"),
991 };
992 let avail = if s.is_available {
993 "available"
994 } else {
995 "unavailable"
996 };
997 let mut v = SectionBuilder::new(vec![Section::Title {
998 left: "DeepSeek".into(),
999 right: None,
1000 }]);
1001 v.push(Section::Spacer);
1002 v.push(Section::Text {
1003 label: "Balance".into(),
1004 value: fmt(s.balance),
1005 });
1006 v.push(Section::Block {
1007 label: "Breakdown".into(),
1008 body: vec![format!(
1009 "granted {} · topped-up {}",
1010 fmt(s.granted),
1011 fmt(s.topped_up)
1012 )],
1013 });
1014 v.push(Section::Spacer);
1015 v.push(Section::Block {
1016 label: "API".into(),
1017 body: vec![avail.into()],
1018 });
1019 v
1020}
1021
1022fn kimi_sections(s: &crate::usage::KimiSnapshot, now: DateTime<Utc>, _tol: u32) -> SectionBuilder {
1023 let plan = s.plan.as_deref().unwrap_or("Kimi");
1024 let mut v = SectionBuilder::new(vec![Section::Title {
1025 left: plan.into(),
1026 right: None,
1027 }]);
1028
1029 let weekly_pct = s.weekly_pct().clamp(0, 100) as u16;
1030 v.push(Section::Spacer);
1031 v.push_metric(
1032 Section::Metric {
1033 label: "Weekly quota".into(),
1034 pct: weekly_pct,
1035 severity: severity_for(s.weekly_pct()),
1036 value_label: format!("{} / {}", s.weekly_used, s.weekly_limit),
1037 footnote: format!(
1038 "{} remaining · reset {}",
1039 s.weekly_remaining,
1040 countdown::format(s.weekly_reset_at, now)
1041 ),
1042 },
1043 s.weekly_reset_at,
1044 );
1045
1046 if s.window_limit > 0 {
1047 let window_pct = s.window_pct().clamp(0, 100) as u16;
1048 v.push(Section::Spacer);
1049 v.push_metric(
1050 Section::Metric {
1051 label: "Rolling window (5h)".into(),
1052 pct: window_pct,
1053 severity: severity_for(s.window_pct()),
1054 value_label: format!("{} / {}", s.window_used, s.window_limit),
1055 footnote: format!(
1056 "{} remaining · reset {}",
1057 s.window_remaining,
1058 countdown::format(s.window_reset_at, now)
1059 ),
1060 },
1061 s.window_reset_at,
1062 );
1063 }
1064
1065 v
1066}
1067
1068fn push_window(
1069 sections: &mut SectionBuilder,
1070 label: &str,
1071 w: &crate::usage::UsageWindow,
1072 now: DateTime<Utc>,
1073 tol: u32,
1074 show_pacing: bool,
1075) {
1076 let pct = w.utilization_pct.clamp(0, 100) as u16;
1077 let reset_text = countdown::format(w.resets_at, now);
1078 let footnote = if show_pacing {
1079 let p = pacing::calc(w.utilization_pct, w.resets_at, now, w.window_duration, tol);
1080 format!(
1081 "Resets in {} · {}% elapsed · {}",
1082 reset_text, p.elapsed_pct, p.point_label
1083 )
1084 } else {
1085 format!("Resets in {}", reset_text)
1086 };
1087 sections.push(Section::Spacer);
1088 sections.push_metric(
1089 Section::Metric {
1090 label: label.into(),
1091 pct,
1092 severity: severity_for(pct as i32),
1093 value_label: format!("{pct}%"),
1094 footnote,
1095 },
1096 w.resets_at,
1097 );
1098}
1099
1100pub fn render(f: &mut Frame, area: Rect, theme: &Theme, sections: &[Section]) {
1108 if sections.is_empty() {
1109 return;
1110 }
1111 let bubble = bubble_theme(theme);
1112 let pin_last =
1115 matches!(sections.last(), Some(Section::Text { value, .. }) if value.contains("Updated"));
1116
1117 let body_end = if pin_last {
1118 sections.len() - 1
1119 } else {
1120 sections.len()
1121 };
1122 let mut constraints: Vec<Constraint> =
1123 sections[..body_end].iter().map(section_height).collect();
1124
1125 if pin_last {
1126 constraints.push(Constraint::Min(0)); constraints.push(section_height(sections.last().unwrap()));
1128 } else {
1129 constraints.push(Constraint::Min(0));
1130 }
1131
1132 let chunks = Layout::default()
1133 .direction(ratatui::layout::Direction::Vertical)
1134 .constraints(constraints)
1135 .split(area);
1136
1137 for (i, s) in sections[..body_end].iter().enumerate() {
1138 render_section(f, chunks[i], theme, &bubble, s);
1139 }
1140 if pin_last {
1141 render_section(
1142 f,
1143 chunks[chunks.len() - 1],
1144 theme,
1145 &bubble,
1146 sections.last().unwrap(),
1147 );
1148 }
1149}
1150
1151fn section_height(s: &Section) -> Constraint {
1152 match s {
1153 Section::Title { .. } => Constraint::Length(2),
1154 Section::Metric { .. } => Constraint::Length(3),
1155 Section::Text { .. } => Constraint::Length(1),
1156 Section::Block { body, .. } => Constraint::Length(1 + body.len() as u16),
1157 Section::Spacer => Constraint::Length(1),
1158 }
1159}
1160
1161fn render_section(f: &mut Frame, area: Rect, theme: &Theme, bubble: &BubbleTheme, s: &Section) {
1162 match s {
1163 Section::Title { left, right } => {
1164 let left_line = Line::from(Span::styled(
1167 format!(" {} {left}", bubble.symbols.selected),
1168 bubble.title,
1169 ));
1170 f.render_widget(Paragraph::new(left_line), area);
1171 if let Some(rt) = right {
1172 let right_line =
1173 Line::from(Span::styled(format!("{rt} "), bubble.muted)).right_aligned();
1174 f.render_widget(Paragraph::new(right_line), area);
1175 }
1176 }
1177 Section::Metric {
1178 label,
1179 pct,
1180 severity,
1181 value_label,
1182 footnote,
1183 } => render_metric(
1184 f,
1185 area,
1186 theme,
1187 bubble,
1188 label,
1189 *pct,
1190 *severity,
1191 value_label,
1192 footnote,
1193 ),
1194 Section::Text { label, value } => {
1195 if label.is_empty() && value.contains("Loading") {
1196 render_loading(f, area, bubble);
1197 return;
1198 }
1199 if label == "Error" {
1200 let line = Line::from(vec![
1201 bubble.error(format!(" {} ", bubble.symbols.cross)),
1202 Span::styled(value.clone(), bubble.error.add_modifier(Modifier::BOLD)),
1203 ]);
1204 f.render_widget(Paragraph::new(line), area);
1205 return;
1206 }
1207 let mut spans = Vec::new();
1208 if !label.is_empty() {
1209 spans.push(Span::styled(
1210 format!(" {label} "),
1211 bubble.text.add_modifier(Modifier::BOLD),
1212 ));
1213 }
1214 spans.push(Span::styled(value.clone(), bubble.muted));
1215 f.render_widget(Paragraph::new(Line::from(spans)), area);
1216 }
1217 Section::Block { label, body } => render_block(f, area, bubble, label, body),
1218 Section::Spacer => {}
1219 }
1220}
1221
1222fn render_loading(f: &mut Frame, area: Rect, bubble: &BubbleTheme) {
1223 let frames = SpinnerFrames::DOTS;
1224 let frame_count = frames.frames().len().max(1);
1225 let frame = chrono::Utc::now().timestamp_millis().unsigned_abs() as usize / 120;
1226 let mut spinner = Spinner::new()
1227 .frames(frames)
1228 .label("Fetching usage data")
1229 .theme(*bubble);
1230 for _ in 0..(frame % frame_count) {
1231 spinner.tick();
1232 }
1233 f.render_widget(&spinner, area);
1234}
1235
1236#[allow(clippy::too_many_arguments)]
1237fn render_metric(
1238 f: &mut Frame,
1239 area: Rect,
1240 theme: &Theme,
1241 bubble: &BubbleTheme,
1242 label: &str,
1243 pct: u16,
1244 severity: PaceSeverity,
1245 value_label: &str,
1246 footnote: &str,
1247) {
1248 let bar_color = severity_color(theme, bubble, severity);
1249 let bar_empty = color(&theme.bar_empty).unwrap_or(bubble.palette.selected_background);
1250
1251 let inner = Layout::default()
1252 .direction(ratatui::layout::Direction::Vertical)
1253 .constraints([
1254 Constraint::Length(1),
1255 Constraint::Length(1),
1256 Constraint::Length(1),
1257 ])
1258 .split(area);
1259
1260 let label_line = Line::from(Span::styled(
1262 format!(" {label}"),
1263 bubble.text.add_modifier(Modifier::BOLD),
1264 ));
1265 f.render_widget(Paragraph::new(label_line), inner[0]);
1266
1267 let row = inner[1];
1269 let value_w = value_label.chars().count() as u16 + 2;
1270 let gauge_area = Rect {
1271 x: row.x + 2,
1272 y: row.y,
1273 width: row.width.saturating_sub(value_w + 4),
1274 height: 1,
1275 };
1276 let value_area = Rect {
1277 x: gauge_area.x + gauge_area.width + 1,
1278 y: row.y,
1279 width: value_w,
1280 height: 1,
1281 };
1282 let progress_theme = progress_theme(*bubble, bar_color, bar_empty);
1283 let progress = Progress::from_percent(pct)
1284 .theme(progress_theme)
1285 .show_percentage(false);
1286 f.render_widget(&progress, gauge_area);
1287 let value = Paragraph::new(Line::from(Span::styled(
1288 value_label.to_string(),
1289 Style::default().fg(bar_color).add_modifier(Modifier::BOLD),
1290 )));
1291 f.render_widget(value, value_area);
1292
1293 let foot = Line::from(Span::styled(format!(" {footnote}"), bubble.muted));
1295 f.render_widget(Paragraph::new(foot), inner[2]);
1296}
1297
1298fn render_block(f: &mut Frame, area: Rect, bubble: &BubbleTheme, label: &str, body: &[String]) {
1299 let mut lines = vec![Line::from(Span::styled(
1300 format!(" {label}"),
1301 bubble.text.add_modifier(Modifier::BOLD),
1302 ))];
1303 for b in body {
1304 lines.push(Line::from(Span::styled(format!(" {b}"), bubble.muted)));
1305 }
1306 f.render_widget(Paragraph::new(lines), area);
1307}
1308
1309#[cfg(test)]
1310mod tests {
1311 use super::*;
1312 use crate::usage::{
1313 AnthropicSnapshot, Cents, ExtraUsage, KimiSnapshot, OpenAiCredits, OpenAiSnapshot,
1314 OpenAiSource, OpenRouterSnapshot, UsageWindow, ZaiSnapshot,
1315 };
1316 use chrono::TimeZone;
1317
1318 fn now() -> DateTime<Utc> {
1319 Utc.with_ymd_and_hms(2026, 5, 23, 12, 0, 0).unwrap()
1320 }
1321
1322 fn ready(snapshot: VendorSnapshot) -> TabState {
1323 TabState::Ready(Box::new(crate::tui::app::ReadyTab {
1324 snapshot,
1325 stale: false,
1326 last_error: None,
1327 fetched_at: Some(now() - chrono::Duration::seconds(15)),
1328 }))
1329 }
1330
1331 #[test]
1332 fn anthropic_sections_include_all_three_windows_when_present() {
1333 let snap = AnthropicSnapshot {
1334 plan: "Max 20x".into(),
1335 session: UsageWindow {
1336 utilization_pct: 60,
1337 resets_at: Some(now() + chrono::Duration::hours(1)),
1338 window_duration: chrono::Duration::hours(5),
1339 },
1340 weekly: UsageWindow {
1341 utilization_pct: 30,
1342 resets_at: Some(now() + chrono::Duration::days(3)),
1343 window_duration: chrono::Duration::days(7),
1344 },
1345 sonnet: Some(UsageWindow {
1346 utilization_pct: 5,
1347 resets_at: Some(now() + chrono::Duration::hours(2)),
1348 window_duration: chrono::Duration::days(7),
1349 }),
1350 scoped: vec![],
1351 extra: Some(ExtraUsage {
1352 limit: Some(Cents(5000)),
1353 spent: Cents(250),
1354 currency: None,
1355 decimal_places: Some(2),
1356 }),
1357 };
1358 let sections = sections_for(&ready(VendorSnapshot::Anthropic(snap)), now(), 5);
1359 assert_eq!(sections.len(), 9);
1362 assert!(matches!(sections[0], Section::Title { .. }));
1363 if let Section::Title { right, .. } = §ions[0] {
1365 assert!(right.as_deref().is_some_and(|r| r.starts_with("Updated ")));
1366 } else {
1367 panic!("expected first section to be Title");
1368 }
1369 let metric_count = sections
1370 .iter()
1371 .filter(|s| matches!(s, Section::Metric { .. }))
1372 .count();
1373 assert_eq!(metric_count, 4);
1374 }
1375
1376 #[test]
1377 fn anthropic_uncapped_extra_shows_spend_without_a_denominator() {
1378 let snap = AnthropicSnapshot {
1381 plan: "Pro".into(),
1382 session: UsageWindow {
1383 utilization_pct: 10,
1384 resets_at: None,
1385 window_duration: chrono::Duration::hours(5),
1386 },
1387 weekly: UsageWindow {
1388 utilization_pct: 20,
1389 resets_at: None,
1390 window_duration: chrono::Duration::days(7),
1391 },
1392 sonnet: None,
1393 scoped: vec![],
1394 extra: Some(ExtraUsage {
1395 limit: None,
1396 spent: Cents(14157),
1397 currency: Some("BRL".into()),
1398 decimal_places: Some(2),
1399 }),
1400 };
1401 let sections = sections_for(&ready(VendorSnapshot::Anthropic(snap)), now(), 5);
1402 let extra = sections
1403 .iter()
1404 .find_map(|s| match s {
1405 Section::Metric {
1406 label,
1407 pct,
1408 value_label,
1409 footnote,
1410 ..
1411 } if label == "Extra usage" => Some((*pct, value_label.clone(), footnote.clone())),
1412 _ => None,
1413 })
1414 .expect("uncapped extra usage must still render a section");
1415 assert_eq!(extra.0, 0);
1416 assert_eq!(extra.1, "R$141.57");
1418 assert!(
1419 !extra.1.contains(" of "),
1420 "no denominator to show: {}",
1421 extra.1
1422 );
1423 assert_eq!(extra.2, "no monthly limit reported");
1424 }
1425
1426 #[test]
1427 fn anthropic_omits_sonnet_and_extra_when_absent() {
1428 let snap = AnthropicSnapshot {
1429 plan: "Pro".into(),
1430 session: UsageWindow {
1431 utilization_pct: 10,
1432 resets_at: None,
1433 window_duration: chrono::Duration::hours(5),
1434 },
1435 weekly: UsageWindow {
1436 utilization_pct: 5,
1437 resets_at: None,
1438 window_duration: chrono::Duration::days(7),
1439 },
1440 sonnet: None,
1441 scoped: vec![],
1442 extra: None,
1443 };
1444 let sections = sections_for(&ready(VendorSnapshot::Anthropic(snap)), now(), 5);
1445 let metric_count = sections
1446 .iter()
1447 .filter(|s| matches!(s, Section::Metric { .. }))
1448 .count();
1449 assert_eq!(metric_count, 2);
1450 }
1451
1452 #[test]
1453 fn openrouter_always_has_balance_metric_and_period_block() {
1454 let snap = OpenRouterSnapshot {
1455 label: "OR".into(),
1456 total_credits: 100.0,
1457 total_usage: 25.0,
1458 usage_daily: 1.0,
1459 usage_weekly: 5.0,
1460 usage_monthly: 25.0,
1461 is_free_tier: false,
1462 limit: None,
1463 limit_remaining: None,
1464 };
1465 let sections = sections_for(&ready(VendorSnapshot::Openrouter(snap)), now(), 5);
1466 assert!(matches!(sections[0], Section::Title { .. }));
1467 assert!(
1468 sections
1469 .iter()
1470 .any(|s| matches!(s, Section::Metric { label, .. } if label == "Credit balance"))
1471 );
1472 assert!(
1473 sections
1474 .iter()
1475 .any(|s| matches!(s, Section::Block { label, .. } if label == "Usage by period"))
1476 );
1477 }
1478
1479 #[test]
1480 fn zai_no_windows_renders_message() {
1481 let snap = ZaiSnapshot {
1482 plan: "GLM".into(),
1483 session: None,
1484 weekly: None,
1485 mcp: None,
1486 };
1487 let sections = sections_for(&ready(VendorSnapshot::Zai(snap)), now(), 5);
1488 assert!(sections.iter().any(|s| matches!(
1489 s,
1490 Section::Text { value, .. } if value.contains("no usage windows reported")
1491 )));
1492 }
1493
1494 #[test]
1495 fn openai_no_windows_renders_message() {
1496 let snap = OpenAiSnapshot {
1497 plan: "ChatGPT Plus".into(),
1498 session: None,
1499 weekly: None,
1500 code_review: None,
1501 credits: None,
1502 source: OpenAiSource::CodexOauth,
1503 };
1504 let sections = sections_for(&ready(VendorSnapshot::Openai(snap)), now(), 5);
1505 assert!(sections.iter().any(|s| matches!(
1506 s,
1507 Section::Text { value, .. } if value.contains("no usage windows reported")
1508 )));
1509 }
1510
1511 #[test]
1512 fn loading_state_yields_loading_section() {
1513 let sections = sections_for(&TabState::Loading, now(), 5);
1514 assert!(sections.iter().any(|s| matches!(
1515 s,
1516 Section::Text { value, .. } if value.contains("Loading")
1517 )));
1518 }
1519
1520 #[test]
1521 fn error_state_includes_retry_hint() {
1522 let sections = sections_for(&TabState::Error("token expired".into()), now(), 5);
1523 assert!(sections.iter().any(|s| matches!(
1524 s,
1525 Section::Text { value, .. } if value.contains("token expired")
1526 )));
1527 assert!(sections.iter().any(|s| matches!(
1528 s,
1529 Section::Text { value, .. } if value.contains("`r` to retry")
1530 )));
1531 }
1532
1533 #[test]
1534 fn openai_with_credits_renders_block() {
1535 let snap = OpenAiSnapshot {
1536 plan: "ChatGPT Plus".into(),
1537 session: Some(UsageWindow {
1538 utilization_pct: 1,
1539 resets_at: None,
1540 window_duration: chrono::Duration::hours(5),
1541 }),
1542 weekly: Some(UsageWindow {
1543 utilization_pct: 0,
1544 resets_at: None,
1545 window_duration: chrono::Duration::days(7),
1546 }),
1547 code_review: None,
1548 credits: Some(OpenAiCredits {
1549 balance: "$5.00".into(),
1550 has_credits: true,
1551 unlimited: false,
1552 approx_local_messages: Some((100, 200)),
1553 approx_cloud_messages: Some((30, 50)),
1554 }),
1555 source: OpenAiSource::CodexOauth,
1556 };
1557 let sections = sections_for(&ready(VendorSnapshot::Openai(snap)), now(), 5);
1558 assert!(
1559 sections
1560 .iter()
1561 .any(|s| matches!(s, Section::Block { label, .. } if label == "Credits"))
1562 );
1563 }
1564
1565 #[test]
1566 fn openai_weekly_only_omits_session_section() {
1567 let snap = OpenAiSnapshot {
1568 plan: "ChatGPT Prolite".into(),
1569 session: None,
1570 weekly: Some(UsageWindow {
1571 utilization_pct: 66,
1572 resets_at: None,
1573 window_duration: chrono::Duration::days(7),
1574 }),
1575 code_review: None,
1576 credits: None,
1577 source: OpenAiSource::CodexOauth,
1578 };
1579 let sections = sections_for(&ready(VendorSnapshot::Openai(snap)), now(), 5);
1580 assert!(sections.iter().any(|section| matches!(
1581 section,
1582 Section::Metric { label, .. } if label == "Codex weekly"
1583 )));
1584 assert!(!sections.iter().any(|section| matches!(
1585 section,
1586 Section::Metric { label, .. } if label == "Codex 5h"
1587 )));
1588 }
1589
1590 #[test]
1591 fn kimi_sections_include_weekly_and_window_with_used_over_limit() {
1592 let now = now();
1593 let snap = KimiSnapshot {
1594 plan: Some("LEVEL_INTERMEDIATE".into()),
1595 weekly_limit: 100,
1596 weekly_used: 26,
1597 weekly_remaining: 74,
1598 weekly_reset_at: Some(now + chrono::Duration::days(4)),
1599 window_limit: 100,
1600 window_used: 15,
1601 window_remaining: 85,
1602 window_reset_at: Some(now + chrono::Duration::hours(2)),
1603 };
1604 let sections = sections_for(&ready(VendorSnapshot::Kimi(snap)), now, 5);
1605 let metrics: Vec<_> = sections
1606 .iter()
1607 .filter(|s| matches!(s, Section::Metric { .. }))
1608 .collect();
1609 assert_eq!(metrics.len(), 2);
1610 assert!(sections.iter().any(|s| matches!(
1611 s,
1612 Section::Metric { label, .. } if label == "Weekly quota"
1613 )));
1614 assert!(sections.iter().any(|s| matches!(
1615 s,
1616 Section::Metric { label, .. } if label == "Rolling window (5h)"
1617 )));
1618
1619 let find_footnote = |label: &str| -> (String, String) {
1620 sections
1621 .iter()
1622 .find_map(|s| match s {
1623 Section::Metric {
1624 label: l,
1625 value_label,
1626 footnote,
1627 ..
1628 } if l == label => Some((value_label.clone(), footnote.clone())),
1629 _ => None,
1630 })
1631 .unwrap_or_else(|| panic!("missing metric {label}"))
1632 };
1633
1634 let (weekly_value, weekly_footnote) = find_footnote("Weekly quota");
1635 assert_eq!(weekly_value, "26 / 100");
1636 assert!(weekly_footnote.contains("74 remaining"));
1637 assert!(
1638 weekly_footnote.contains("4d 0h"),
1639 "weekly reset countdown: {weekly_footnote}"
1640 );
1641 assert!(!weekly_footnote.contains("2026-05-27T")); let (window_value, window_footnote) = find_footnote("Rolling window (5h)");
1644 assert_eq!(window_value, "15 / 100");
1645 assert!(window_footnote.contains("85 remaining"));
1646 assert!(
1647 window_footnote.contains("2h 00m"),
1648 "window reset countdown: {window_footnote}"
1649 );
1650 assert!(!window_footnote.contains("2026-05-23T14")); }
1652
1653 #[test]
1654 fn kimi_sections_omit_window_when_limit_zero() {
1655 let snap = KimiSnapshot {
1656 plan: None,
1657 weekly_limit: 100,
1658 weekly_used: 10,
1659 weekly_remaining: 90,
1660 weekly_reset_at: None,
1661 window_limit: 0,
1662 window_used: 0,
1663 window_remaining: 0,
1664 window_reset_at: None,
1665 };
1666 let sections = sections_for(&ready(VendorSnapshot::Kimi(snap)), now(), 5);
1667 let metric_count = sections
1668 .iter()
1669 .filter(|s| matches!(s, Section::Metric { .. }))
1670 .count();
1671 assert_eq!(metric_count, 1);
1672 }
1673
1674 fn cursor_snap() -> crate::usage::CursorSnapshot {
1675 crate::usage::CursorSnapshot {
1676 plan: "Ultra".into(),
1677 auto_pct: 98,
1678 api_pct: 100,
1679 total_pct: 99,
1680 unlimited: false,
1681 on_demand_enabled: false,
1682 reset_at: Some(now() + chrono::Duration::days(9)),
1683 }
1684 }
1685
1686 #[test]
1687 fn compact_cells_flatten_key_metrics_for_the_overview() {
1688 let (plan, cells) = compact_cells(&VendorSnapshot::Cursor(cursor_snap()));
1690 assert_eq!(plan, "Ultra");
1691 assert_eq!(cells[0].0, "auto 98%");
1692 assert_eq!(cells[1].0, "premium 100%");
1693 assert_eq!(cells[1].1, PaceSeverity::Critical); let (plan, cells) = compact_cells(&VendorSnapshot::Kilo(crate::usage::KiloSnapshot {
1697 label: "Kilo".into(),
1698 balance: 8.42,
1699 }));
1700 assert!(plan.is_empty());
1701 assert_eq!(cells, vec![("$8.42".to_string(), PaceSeverity::Low)]);
1702 }
1703
1704 #[test]
1705 fn terminal_controls_are_removed_from_detail_and_overview_fields() {
1706 let error = TabState::Error("bad\x1b]52;c;Y2FuYXJ5\x07 value".into());
1707 let sections = sections_for(&error, now(), 5);
1708 assert!(matches!(
1709 §ions[1],
1710 Section::Text { value, .. }
1711 if value == "bad]52;c;Y2FuYXJ5 value"
1712 && !value.chars().any(|ch| ch.is_control())
1713 ));
1714
1715 let mut snapshot = cursor_snap();
1716 snapshot.plan = "Ultra\x1b[2J\x07".into();
1717 let (plan, _) = compact_cells(&VendorSnapshot::Cursor(snapshot));
1718 assert_eq!(plan, "Ultra[2J");
1719 assert!(!plan.chars().any(char::is_control));
1720 }
1721
1722 #[test]
1723 fn headline_pct_is_the_worst_window_or_combined_total() {
1724 assert_eq!(
1726 headline_pct(&VendorSnapshot::Cursor(cursor_snap())),
1727 Some(99)
1728 );
1729
1730 let kilo = VendorSnapshot::Kilo(crate::usage::KiloSnapshot {
1732 label: "Kilo".into(),
1733 balance: 8.42,
1734 });
1735 assert_eq!(headline_pct(&kilo), None);
1736 }
1737
1738 #[test]
1739 fn cursor_sections_show_both_pools_and_reset() {
1740 let sections = sections_for(&ready(VendorSnapshot::Cursor(cursor_snap())), now(), 5);
1741 let metrics: Vec<_> = sections
1742 .iter()
1743 .filter_map(|s| match s {
1744 Section::Metric {
1745 label, value_label, ..
1746 } => Some((label.clone(), value_label.clone())),
1747 _ => None,
1748 })
1749 .collect();
1750 assert_eq!(metrics.len(), 2, "two pools");
1751 assert!(
1752 metrics
1753 .iter()
1754 .any(|(l, v)| l == "Cursor Models" && v == "98%")
1755 );
1756 assert!(
1757 metrics
1758 .iter()
1759 .any(|(l, v)| l == "Other Models" && v == "100%")
1760 );
1761 assert!(sections.iter().any(|s| matches!(
1762 s,
1763 Section::Text { label, value } if label == "Resets" && value.contains("9d")
1764 )));
1765 }
1766
1767 #[test]
1768 fn cursor_unlimited_plan_shows_no_pool_bars() {
1769 let mut snap = cursor_snap();
1770 snap.unlimited = true;
1771 let sections = sections_for(&ready(VendorSnapshot::Cursor(snap)), now(), 5);
1772 let metric_count = sections
1773 .iter()
1774 .filter(|s| matches!(s, Section::Metric { .. }))
1775 .count();
1776 assert_eq!(metric_count, 0);
1777 assert!(sections.iter().any(|s| matches!(
1778 s,
1779 Section::Text { value, .. } if value.contains("Unlimited")
1780 )));
1781 }
1782
1783 fn kiro_snap() -> crate::usage::KiroSnapshot {
1784 crate::usage::KiroSnapshot {
1785 plan: "KIRO POWER".into(),
1786 used: 9943.38,
1787 limit: 10000.0,
1788 reset_at: Some(now() + chrono::Duration::days(1)),
1789 }
1790 }
1791
1792 #[test]
1793 fn kiro_compact_cell_shows_the_credit_percentage() {
1794 let (plan, cells) = compact_cells(&VendorSnapshot::Kiro(kiro_snap()));
1795 assert_eq!(plan, "KIRO POWER");
1796 assert_eq!(
1797 cells,
1798 vec![("credits 99%".to_string(), PaceSeverity::Critical)]
1799 );
1800 }
1801
1802 #[test]
1803 fn kiro_headline_pct_is_the_credit_percentage() {
1804 assert_eq!(headline_pct(&VendorSnapshot::Kiro(kiro_snap())), Some(99));
1805 }
1806
1807 #[test]
1808 fn kiro_sections_show_the_credit_metric_and_reset() {
1809 let sections = sections_for(&ready(VendorSnapshot::Kiro(kiro_snap())), now(), 5);
1810 let metrics: Vec<_> = sections
1811 .iter()
1812 .filter_map(|s| match s {
1813 Section::Metric {
1814 label, value_label, ..
1815 } => Some((label.clone(), value_label.clone())),
1816 _ => None,
1817 })
1818 .collect();
1819 assert_eq!(metrics, vec![("Credits".to_string(), "99%".to_string())]);
1820 assert!(sections.iter().any(|s| matches!(
1821 s,
1822 Section::Text { label, value } if label == "Resets" && value.contains("1d")
1823 )));
1824 }
1825
1826 #[test]
1827 fn schema_drift_and_generic_code_zero_diagnostics_are_visible_without_http_labels() {
1828 let snap = KimiSnapshot {
1829 plan: None,
1830 weekly_limit: 100,
1831 weekly_used: 10,
1832 weekly_remaining: 90,
1833 weekly_reset_at: None,
1834 window_limit: 0,
1835 window_used: 0,
1836 window_remaining: 0,
1837 window_reset_at: None,
1838 };
1839 let mut schema = ready(VendorSnapshot::Kimi(snap.clone()));
1840 let TabState::Ready(tab) = &mut schema else {
1841 unreachable!()
1842 };
1843 tab.last_error = Some((0, crate::kimi::fetch::SCHEMA_DRIFT_MESSAGE.into()));
1844 let schema_sections = sections_for(&schema, now(), 5);
1845 assert!(schema_sections.iter().any(|section| matches!(
1846 section,
1847 Section::Text { label, value } if label == "Kimi API schema drift" && value.is_empty()
1848 )));
1849
1850 let mut generic = ready(VendorSnapshot::Kimi(snap));
1851 let TabState::Ready(tab) = &mut generic else {
1852 unreachable!()
1853 };
1854 tab.last_error = Some((0, "cache lock unavailable".into()));
1855 let generic_sections = sections_for(&generic, now(), 5);
1856 assert!(generic_sections.iter().any(|section| matches!(
1857 section,
1858 Section::Text { label, value } if label == "Warning" && value == "cache lock unavailable"
1859 )));
1860 assert!(!generic_sections.iter().any(|section| matches!(
1861 section,
1862 Section::Text { label, .. } if label.starts_with("HTTP")
1863 )));
1864
1865 let http = warning_label(
1866 &VendorSnapshot::Kimi(KimiSnapshot {
1867 plan: None,
1868 weekly_limit: 0,
1869 weekly_used: 0,
1870 weekly_remaining: 0,
1871 weekly_reset_at: None,
1872 window_limit: 0,
1873 window_used: 0,
1874 window_remaining: 0,
1875 window_reset_at: None,
1876 }),
1877 &Some((503, "service unavailable".into())),
1878 );
1879 assert_eq!(
1880 http,
1881 Some(("HTTP 503".into(), "service unavailable".into()))
1882 );
1883 }
1884}