Skip to main content

ai_usagebar/
active.rs

1//! Active-vendor state file. Set by `--cycle-next` / `--cycle-prev` (which
2//! Waybar's `on-scroll-up`/`on-scroll-down` invoke), read by the widget on
3//! every tick. The TUI does NOT consult this — it has its own tab state.
4//!
5//! On-disk shape: a single line with the vendor slug (e.g. `openai`). Located
6//! at `<cache-dir>/active_vendor`.
7
8use std::fs;
9use std::path::{Path, PathBuf};
10
11use crate::cache::atomic_write;
12use crate::error::{AppError, Result};
13use crate::vendor::VendorId;
14
15fn state_dir() -> Result<PathBuf> {
16    let base = directories::BaseDirs::new()
17        .ok_or_else(|| AppError::Other("could not resolve XDG cache dir".into()))?;
18    Ok(base.cache_dir().join("ai-usagebar"))
19}
20
21fn state_path() -> Result<PathBuf> {
22    Ok(state_dir()?.join("active_vendor"))
23}
24
25/// Read the persisted active vendor, if any. `None` means "no override —
26/// callers fall back to [ui] primary or anthropic".
27pub fn read() -> Option<VendorId> {
28    read_from(&state_path().ok()?)
29}
30
31/// Read the persisted active vendor from an explicit path. The real-path
32/// [`read`] is a thin wrapper over this; tests use this directly with a
33/// `TempDir`-backed path so they never touch `~/.cache/ai-usagebar`.
34pub fn read_from(path: &Path) -> Option<VendorId> {
35    let raw = fs::read_to_string(path).ok()?;
36    parse_slug(raw.trim())
37}
38
39/// Persist `vendor` as the active one. Atomic.
40pub fn write(vendor: VendorId) -> Result<()> {
41    write_to(&state_path()?, vendor)
42}
43
44/// Persist `vendor` to an explicit path. Atomic. Test-friendly counterpart
45/// to [`write`] (mirrors [`crate::cache::Cache::at`] vs `for_vendor`).
46pub fn write_to(path: &Path, vendor: VendorId) -> Result<()> {
47    atomic_write(path, vendor.slug().as_bytes())
48}
49
50/// Cycle the active vendor by `delta` positions through `enabled` (which
51/// preserves canonical order). Wraps. If no state exists, starts at `start`
52/// (usually `[ui] primary` or anthropic).
53pub fn cycle(enabled: &[VendorId], start: VendorId, delta: i32) -> Result<VendorId> {
54    cycle_at(&state_path()?, enabled, start, delta)
55}
56
57/// Cycle using an explicit state-file path. The real-path [`cycle`] is a thin
58/// wrapper over this; tests drive this with a `TempDir` path so the cycle +
59/// persistence logic is covered without reading or writing the real cache.
60pub fn cycle_at(
61    path: &Path,
62    enabled: &[VendorId],
63    start: VendorId,
64    delta: i32,
65) -> Result<VendorId> {
66    if enabled.is_empty() {
67        return Err(AppError::Other("no enabled vendors to cycle".into()));
68    }
69    let current = read_from(path)
70        .filter(|v| enabled.contains(v))
71        .unwrap_or(start);
72    let cur_idx = enabled.iter().position(|v| *v == current).unwrap_or(0);
73    let n = enabled.len() as i32;
74    let next_idx = ((cur_idx as i32 + delta).rem_euclid(n)) as usize;
75    let next = enabled[next_idx];
76    write_to(path, next)?;
77    Ok(next)
78}
79
80fn parse_slug(s: &str) -> Option<VendorId> {
81    match s {
82        "anthropic" => Some(VendorId::Anthropic),
83        "openai" => Some(VendorId::Openai),
84        "zai" => Some(VendorId::Zai),
85        "openrouter" => Some(VendorId::Openrouter),
86        "deepseek" => Some(VendorId::Deepseek),
87        _ => None,
88    }
89}
90
91#[cfg(test)]
92mod tests {
93    use super::*;
94    use tempfile::TempDir;
95
96    // Deliberately excludes Deepseek so the not-in-enabled-set fallback test
97    // below has a real vendor to persist that is outside this cycle set.
98    const CYCLE_SET: [VendorId; 4] = [
99        VendorId::Anthropic,
100        VendorId::Openai,
101        VendorId::Zai,
102        VendorId::Openrouter,
103    ];
104
105    #[test]
106    fn parse_slug_round_trip() {
107        for id in VendorId::all() {
108            assert_eq!(parse_slug(id.slug()), Some(*id));
109        }
110    }
111
112    #[test]
113    fn parse_slug_unknown_returns_none() {
114        assert!(parse_slug("not-a-vendor").is_none());
115        assert!(parse_slug("").is_none());
116    }
117
118    #[test]
119    fn read_from_missing_or_garbage_returns_none() {
120        let td = TempDir::new().unwrap();
121        // Missing file → None.
122        assert!(read_from(&td.path().join("active_vendor")).is_none());
123        // Round-trip a real slug.
124        let path = td.path().join("active_vendor");
125        write_to(&path, VendorId::Zai).unwrap();
126        assert_eq!(read_from(&path), Some(VendorId::Zai));
127        // Garbage content → None (not a known slug).
128        fs::write(&path, "not-a-vendor").unwrap();
129        assert!(read_from(&path).is_none());
130    }
131
132    #[test]
133    fn cycle_at_persists_state_across_calls() {
134        let td = TempDir::new().unwrap();
135        let path = td.path().join("active_vendor");
136
137        // No state yet → starts at `start`, steps forward to Openai.
138        let v = cycle_at(&path, &CYCLE_SET, VendorId::Anthropic, 1).unwrap();
139        assert_eq!(v, VendorId::Openai);
140        assert_eq!(read_from(&path), Some(VendorId::Openai));
141
142        // Next forward step reads the persisted Openai → Zai.
143        let v = cycle_at(&path, &CYCLE_SET, VendorId::Anthropic, 1).unwrap();
144        assert_eq!(v, VendorId::Zai);
145        assert_eq!(read_from(&path), Some(VendorId::Zai));
146    }
147
148    #[test]
149    fn cycle_at_wraps_forward_and_backward() {
150        let td = TempDir::new().unwrap();
151        let path = td.path().join("active_vendor");
152        write_to(&path, VendorId::Anthropic).unwrap();
153
154        // backward from Anthropic wraps to Openrouter
155        assert_eq!(
156            cycle_at(&path, &CYCLE_SET, VendorId::Anthropic, -1).unwrap(),
157            VendorId::Openrouter
158        );
159        // forward from Openrouter wraps back to Anthropic
160        assert_eq!(
161            cycle_at(&path, &CYCLE_SET, VendorId::Anthropic, 1).unwrap(),
162            VendorId::Anthropic
163        );
164    }
165
166    #[test]
167    fn cycle_at_ignores_persisted_vendor_not_in_enabled_set() {
168        let td = TempDir::new().unwrap();
169        let path = td.path().join("active_vendor");
170        // Persist a vendor that isn't in the enabled set → fall back to `start`.
171        write_to(&path, VendorId::Deepseek).unwrap();
172        let enabled = [VendorId::Anthropic, VendorId::Openai];
173        // start=Openai (idx 1), +1 wraps to idx 0 = Anthropic.
174        let v = cycle_at(&path, &enabled, VendorId::Openai, 1).unwrap();
175        assert_eq!(v, VendorId::Anthropic);
176    }
177
178    #[test]
179    fn cycle_at_errors_on_empty_enabled() {
180        let td = TempDir::new().unwrap();
181        let path = td.path().join("active_vendor");
182        let res = cycle_at(&path, &[], VendorId::Anthropic, 1);
183        assert!(matches!(res, Err(AppError::Other(_))));
184    }
185}