use std::time::Duration;
use chrono::Utc;
use reqwest::Client;
use crate::cache::DEFAULT_TTL;
use crate::config::Config;
use crate::error::Result;
use crate::theme::Theme;
use crate::vendor::{VendorId, VendorOutcome};
#[derive(Debug, Clone)]
pub enum TabState {
Loading,
Ready(Box<ReadyTab>),
Error(String),
}
#[derive(Debug, Clone)]
pub struct ReadyTab {
pub snapshot: crate::usage::VendorSnapshot,
pub stale: bool,
pub last_error: Option<(u16, String)>,
pub fetched_at: Option<chrono::DateTime<chrono::Utc>>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TabId {
pub vendor: VendorId,
pub account: Option<String>,
}
impl TabId {
pub fn vendor(vendor: VendorId) -> Self {
Self {
vendor,
account: None,
}
}
pub fn account(label: impl Into<String>) -> Self {
Self {
vendor: VendorId::Anthropic,
account: Some(label.into()),
}
}
}
pub fn tabs_from_config(config: &Config) -> Vec<TabId> {
let mut tabs = Vec::new();
for vendor in config.enabled_vendors() {
tabs.push(TabId::vendor(vendor));
if vendor == VendorId::Anthropic {
for acct in &config.anthropic.accounts {
tabs.push(TabId::account(acct.label.clone()));
}
}
}
tabs
}
#[derive(Debug)]
pub struct App {
pub tabs_meta: Vec<TabId>,
pub active: usize,
pub tabs: Vec<TabState>,
pub tab_generation: u64,
pub theme: Theme,
pub last_refresh: chrono::DateTime<chrono::Utc>,
pub quit: bool,
pub settings: Option<crate::tui::settings::SettingsState>,
}
impl App {
pub fn new(tabs_meta: Vec<TabId>) -> Self {
Self::with_theme(tabs_meta, Theme::default().merged_with_omarchy())
}
pub fn with_theme(tabs_meta: Vec<TabId>, theme: Theme) -> Self {
let n = tabs_meta.len();
Self {
tabs_meta,
active: 0,
tabs: vec![TabState::Loading; n],
tab_generation: 0,
theme,
last_refresh: Utc::now(),
quit: false,
settings: None,
}
}
pub fn new_with_primary(tabs_meta: Vec<TabId>, primary: Option<VendorId>) -> Self {
let mut app = Self::new(tabs_meta);
app.select_primary(primary);
app
}
pub fn active_tab_id(&self) -> Option<&TabId> {
self.tabs_meta.get(self.active)
}
pub fn active_vendor(&self) -> Option<VendorId> {
self.tabs_meta.get(self.active).map(|t| t.vendor)
}
pub fn set_tabs(&mut self, tabs_meta: Vec<TabId>) {
self.tab_generation = self.tab_generation.wrapping_add(1);
self.active = self.active.min(tabs_meta.len().saturating_sub(1));
self.tabs = vec![TabState::Loading; tabs_meta.len()];
self.tabs_meta = tabs_meta;
}
pub fn apply_refresh(&mut self, generation: u64, tab: &TabId, state: TabState) -> bool {
if generation != self.tab_generation {
return false;
}
let Some(index) = self.tabs_meta.iter().position(|current| current == tab) else {
return false;
};
self.tabs[index] = state;
self.last_refresh = Utc::now();
true
}
pub fn select_primary(&mut self, primary: Option<VendorId>) {
if let Some(p) = primary
&& let Some(idx) = self.tabs_meta.iter().position(|t| t.vendor == p)
{
self.active = idx;
}
}
pub fn next_tab(&mut self) {
if !self.tabs_meta.is_empty() {
self.active = (self.active + 1) % self.tabs_meta.len();
}
}
pub fn prev_tab(&mut self) {
if !self.tabs_meta.is_empty() {
self.active = (self.active + self.tabs_meta.len() - 1) % self.tabs_meta.len();
}
}
}
pub async fn refresh_one(client: &Client, config: &Config, tab: &TabId) -> TabState {
match build_outcome(client, config, tab).await {
Ok(outcome) => {
let now = Utc::now();
let fetched_at = outcome
.cache_age
.map(|age| now - chrono::Duration::from_std(age).unwrap_or_default());
TabState::Ready(Box::new(ReadyTab {
snapshot: outcome.snapshot,
stale: outcome.stale,
last_error: outcome.last_error,
fetched_at,
}))
}
Err(e) => TabState::Error(e.to_string()),
}
}
async fn build_outcome(client: &Client, config: &Config, tab: &TabId) -> Result<VendorOutcome> {
match tab.vendor {
VendorId::Anthropic => {
let (creds_target, cache) = match tab.account.as_deref() {
Some(label) => config.anthropic.account_target(label)?,
None => {
let target = match config.anthropic.credentials_path.clone() {
Some(p) => crate::anthropic::creds::CredsTarget::Explicit(p),
None => crate::anthropic::creds::CredsTarget::Default(
crate::anthropic::creds::default_path().unwrap_or_default(),
),
};
(target, crate::cache::Cache::for_vendor("anthropic")?)
}
};
let endpoints = crate::anthropic::fetch::Endpoints::default();
let outcome = crate::anthropic::fetch_snapshot(
client,
&creds_target,
&cache,
&endpoints,
DEFAULT_TTL,
)
.await?;
Ok(crate::vendor::VendorOutcome {
snapshot: crate::usage::VendorSnapshot::Anthropic(outcome.snapshot),
stale: outcome.stale,
last_error: outcome.last_error,
cache_age: outcome.cache_age,
})
}
VendorId::Openrouter => {
let api_key = crate::config::resolve_api_key(
"OpenRouter",
&config.openrouter.api_key_env,
config.openrouter.api_key.as_deref(),
)?;
let cache = crate::cache::Cache::for_vendor("openrouter")?;
let endpoints = crate::openrouter::fetch::Endpoints::default();
let outcome = crate::openrouter::fetch_snapshot(
client,
&api_key,
&cache,
&endpoints,
DEFAULT_TTL,
)
.await?;
Ok(outcome.into())
}
VendorId::Zai => {
let api_key = crate::config::resolve_api_key(
"Zai",
&config.zai.api_key_env,
config.zai.api_key.as_deref(),
)?;
let cache = crate::cache::Cache::for_vendor("zai")?;
let endpoints = crate::zai::fetch::Endpoints::default();
let outcome = crate::zai::fetch_snapshot(
client,
&api_key,
&cache,
&endpoints,
DEFAULT_TTL,
config.zai.plan_tier.as_deref(),
)
.await?;
Ok(outcome.into())
}
VendorId::Openai => {
let cache = crate::cache::Cache::for_vendor("openai")?;
let creds_path = config
.openai
.codex_auth_path
.clone()
.unwrap_or_else(|| crate::openai::creds::default_path().unwrap_or_default());
let endpoints = crate::openai::fetch::Endpoints::default();
let outcome =
crate::openai::fetch_snapshot(client, &creds_path, &cache, &endpoints, DEFAULT_TTL)
.await?;
Ok(outcome.into())
}
VendorId::Deepseek => {
let api_key = crate::config::resolve_api_key(
"DeepSeek",
&config.deepseek.api_key_env,
config.deepseek.api_key.as_deref(),
)?;
let cache = crate::cache::Cache::for_vendor("deepseek")?;
let endpoints = crate::deepseek::fetch::Endpoints::default();
let outcome =
crate::deepseek::fetch_snapshot(client, &api_key, &cache, &endpoints, DEFAULT_TTL)
.await?;
Ok(outcome.into())
}
VendorId::Kimi => {
let api_key = crate::config::resolve_api_key(
"Kimi",
&config.kimi.api_key_env,
config.kimi.api_key.as_deref(),
)?;
let cache = crate::cache::Cache::for_vendor("kimi")?;
let endpoints = crate::kimi::fetch::Endpoints::default();
let outcome =
crate::kimi::fetch_snapshot(client, &api_key, &cache, &endpoints, DEFAULT_TTL)
.await?;
Ok(outcome.into())
}
}
}
pub const REFRESH_INTERVAL: Duration = Duration::from_secs(60);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn select_primary_moves_to_enabled_vendor() {
let mut app = App::with_theme(
vec![
TabId::vendor(VendorId::Anthropic),
TabId::vendor(VendorId::Openrouter),
],
Theme::default(),
);
app.select_primary(Some(VendorId::Openrouter));
assert_eq!(app.active_vendor(), Some(VendorId::Openrouter));
}
#[test]
fn select_primary_ignores_disabled_vendor() {
let mut app = App::with_theme(vec![TabId::vendor(VendorId::Anthropic)], Theme::default());
app.select_primary(Some(VendorId::Openai));
assert_eq!(app.active_vendor(), Some(VendorId::Anthropic));
}
fn config_with_accounts(labels: &[&str]) -> Config {
let mut config = Config::default();
config.openai.enabled = false;
config.zai.enabled = false;
config.openrouter.enabled = false;
config.anthropic.accounts = labels
.iter()
.map(|l| crate::config::AnthropicAccount {
label: (*l).to_string(),
credentials_path: format!("/creds/{l}.json").into(),
})
.collect();
config
}
#[test]
fn tabs_expand_anthropic_accounts_after_default() {
let tabs = tabs_from_config(&config_with_accounts(&["work", "personal"]));
assert_eq!(
tabs,
vec![
TabId::vendor(VendorId::Anthropic),
TabId::account("work"),
TabId::account("personal"),
]
);
}
#[test]
fn tabs_without_accounts_are_just_enabled_vendors() {
let config = Config::default();
let tabs = tabs_from_config(&config);
let vendors: Vec<VendorId> = tabs.iter().map(|t| t.vendor).collect();
assert_eq!(vendors, config.enabled_vendors());
assert!(tabs.iter().all(|t| t.account.is_none()));
}
#[test]
fn set_tabs_resets_states_and_clamps_selection() {
let mut app = App::with_theme(
tabs_from_config(&config_with_accounts(&["work", "personal"])),
Theme::default(),
);
app.active = 2; app.tabs[0] = TabState::Error("old".into());
app.set_tabs(tabs_from_config(&config_with_accounts(&[])));
assert_eq!(app.tabs_meta, vec![TabId::vendor(VendorId::Anthropic)]);
assert_eq!(app.active, 0, "selection clamped after shrink");
assert!(matches!(app.tabs[0], TabState::Loading));
}
#[test]
fn refresh_from_old_generation_is_discarded() {
let mut app = App::with_theme(vec![TabId::vendor(VendorId::Anthropic)], Theme::default());
let old_generation = app.tab_generation;
app.set_tabs(vec![TabId::vendor(VendorId::Openai)]);
assert!(!app.apply_refresh(
old_generation,
&TabId::vendor(VendorId::Anthropic),
TabState::Error("old result".into()),
));
assert!(matches!(app.tabs[0], TabState::Loading));
}
#[test]
fn refresh_identity_mismatch_is_discarded() {
let mut app = App::with_theme(vec![TabId::vendor(VendorId::Anthropic)], Theme::default());
let generation = app.tab_generation;
assert!(!app.apply_refresh(
generation,
&TabId::vendor(VendorId::Openai),
TabState::Error("wrong tab".into()),
));
assert!(matches!(app.tabs[0], TabState::Loading));
}
#[test]
fn refresh_identity_lands_at_new_index_after_same_generation_reorder() {
let anthropic = TabId::vendor(VendorId::Anthropic);
let openai = TabId::vendor(VendorId::Openai);
let mut app = App::with_theme(vec![anthropic.clone(), openai.clone()], Theme::default());
let generation = app.tab_generation;
app.tabs_meta.swap(0, 1);
app.tabs.swap(0, 1);
assert!(app.apply_refresh(generation, &anthropic, TabState::Error("ready".into())));
assert!(matches!(app.tabs[0], TabState::Loading));
assert!(matches!(&app.tabs[1], TabState::Error(message) if message == "ready"));
}
#[test]
fn select_primary_lands_on_default_account_tab() {
let app = {
let tabs = tabs_from_config(&config_with_accounts(&["work"]));
let mut a = App::with_theme(tabs, Theme::default());
a.select_primary(Some(VendorId::Anthropic));
a
};
assert_eq!(app.active, 0);
assert_eq!(
app.active_tab_id(),
Some(&TabId::vendor(VendorId::Anthropic))
);
}
}