1use std::fs;
9use std::path::{Path, PathBuf};
10use std::time::Duration;
11
12use crate::cache::{acquire_lock, atomic_write};
13use crate::error::{AppError, Result};
14use crate::vendor::VendorId;
15
16const LOCK_TIMEOUT: Duration = Duration::from_secs(5);
21
22fn state_dir() -> Result<PathBuf> {
23 let base = directories::BaseDirs::new()
24 .ok_or_else(|| AppError::Other("could not resolve XDG cache dir".into()))?;
25 Ok(base.cache_dir().join("ai-usagebar"))
26}
27
28fn state_path() -> Result<PathBuf> {
29 Ok(state_dir()?.join("active_vendor"))
30}
31
32pub fn read() -> Option<VendorId> {
35 read_from(&state_path().ok()?)
36}
37
38pub fn read_from(path: &Path) -> Option<VendorId> {
42 let raw = fs::read_to_string(path).ok()?;
43 parse_slug(raw.trim())
44}
45
46pub fn write(vendor: VendorId) -> Result<()> {
48 write_to(&state_path()?, vendor)
49}
50
51pub fn write_to(path: &Path, vendor: VendorId) -> Result<()> {
54 atomic_write(path, vendor.slug().as_bytes())
55}
56
57pub fn cycle(enabled: &[VendorId], start: VendorId, delta: i32) -> Result<VendorId> {
61 cycle_at(&state_path()?, enabled, start, delta)
62}
63
64fn lock_path_for(state: &Path) -> PathBuf {
67 let mut p = state.as_os_str().to_os_string();
68 p.push(".lock");
69 PathBuf::from(p)
70}
71
72pub fn cycle_at(
76 path: &Path,
77 enabled: &[VendorId],
78 start: VendorId,
79 delta: i32,
80) -> Result<VendorId> {
81 if enabled.is_empty() {
82 return Err(AppError::Other("no enabled vendors to cycle".into()));
83 }
84 let _lock = acquire_lock(&lock_path_for(path), LOCK_TIMEOUT)?;
89 let current = read_from(path)
90 .filter(|v| enabled.contains(v))
91 .unwrap_or(start);
92 let cur_idx = enabled.iter().position(|v| *v == current).unwrap_or(0);
93 let n = enabled.len() as i32;
94 let next_idx = ((cur_idx as i32 + delta).rem_euclid(n)) as usize;
95 let next = enabled[next_idx];
96 write_to(path, next)?;
97 Ok(next)
98}
99
100fn parse_slug(s: &str) -> Option<VendorId> {
101 match s {
102 "anthropic" => Some(VendorId::Anthropic),
103 "anthropic_api" => Some(VendorId::AnthropicApi),
104 "openai" => Some(VendorId::Openai),
105 "zai" => Some(VendorId::Zai),
106 "openrouter" => Some(VendorId::Openrouter),
107 "deepseek" => Some(VendorId::Deepseek),
108 "kimi" => Some(VendorId::Kimi),
109 "kilo" => Some(VendorId::Kilo),
110 "novita" => Some(VendorId::Novita),
111 "moonshot" => Some(VendorId::Moonshot),
112 "grok" => Some(VendorId::Grok),
113 "antigravity" => Some(VendorId::Antigravity),
114 "cursor" => Some(VendorId::Cursor),
115 "minimax" => Some(VendorId::Minimax),
116 _ => None,
117 }
118}
119
120#[cfg(test)]
121mod tests {
122 use super::*;
123 use tempfile::TempDir;
124
125 const CYCLE_SET: [VendorId; 4] = [
128 VendorId::Anthropic,
129 VendorId::Openai,
130 VendorId::Zai,
131 VendorId::Openrouter,
132 ];
133
134 #[test]
140 fn concurrent_cycles_do_not_lose_a_step() {
141 let td = TempDir::new().unwrap();
142 let path = td.path().join("active_vendor");
143 let start = VendorId::Anthropic;
144
145 const THREADS: usize = 4;
148 std::thread::scope(|s| {
149 for _ in 0..THREADS {
150 s.spawn(|| {
151 let _ = cycle_at(&path, &CYCLE_SET, start, 1);
152 });
153 }
154 });
155
156 let landed = read_from(&path).expect("a vendor must have been persisted");
157 assert_eq!(
158 landed,
159 start,
160 "{THREADS} single steps over {} vendors must return to the start; \
161 landing on {landed:?} means a step was lost to a race",
162 CYCLE_SET.len()
163 );
164 }
165
166 #[test]
167 fn parse_slug_round_trip() {
168 for id in VendorId::all() {
169 assert_eq!(parse_slug(id.slug()), Some(*id));
170 }
171 }
172
173 #[test]
174 fn parse_slug_unknown_returns_none() {
175 assert!(parse_slug("not-a-vendor").is_none());
176 assert!(parse_slug("").is_none());
177 }
178
179 #[test]
180 fn read_from_missing_or_garbage_returns_none() {
181 let td = TempDir::new().unwrap();
182 assert!(read_from(&td.path().join("active_vendor")).is_none());
184 let path = td.path().join("active_vendor");
186 write_to(&path, VendorId::Zai).unwrap();
187 assert_eq!(read_from(&path), Some(VendorId::Zai));
188 fs::write(&path, "not-a-vendor").unwrap();
190 assert!(read_from(&path).is_none());
191 }
192
193 #[test]
194 fn cycle_at_persists_state_across_calls() {
195 let td = TempDir::new().unwrap();
196 let path = td.path().join("active_vendor");
197
198 let v = cycle_at(&path, &CYCLE_SET, VendorId::Anthropic, 1).unwrap();
200 assert_eq!(v, VendorId::Openai);
201 assert_eq!(read_from(&path), Some(VendorId::Openai));
202
203 let v = cycle_at(&path, &CYCLE_SET, VendorId::Anthropic, 1).unwrap();
205 assert_eq!(v, VendorId::Zai);
206 assert_eq!(read_from(&path), Some(VendorId::Zai));
207 }
208
209 #[test]
210 fn cycle_at_wraps_forward_and_backward() {
211 let td = TempDir::new().unwrap();
212 let path = td.path().join("active_vendor");
213 write_to(&path, VendorId::Anthropic).unwrap();
214
215 assert_eq!(
217 cycle_at(&path, &CYCLE_SET, VendorId::Anthropic, -1).unwrap(),
218 VendorId::Openrouter
219 );
220 assert_eq!(
222 cycle_at(&path, &CYCLE_SET, VendorId::Anthropic, 1).unwrap(),
223 VendorId::Anthropic
224 );
225 }
226
227 #[test]
228 fn cycle_at_ignores_persisted_vendor_not_in_enabled_set() {
229 let td = TempDir::new().unwrap();
230 let path = td.path().join("active_vendor");
231 write_to(&path, VendorId::Deepseek).unwrap();
233 let enabled = [VendorId::Anthropic, VendorId::Openai];
234 let v = cycle_at(&path, &enabled, VendorId::Openai, 1).unwrap();
236 assert_eq!(v, VendorId::Anthropic);
237 }
238
239 #[test]
240 fn cycle_at_errors_on_empty_enabled() {
241 let td = TempDir::new().unwrap();
242 let path = td.path().join("active_vendor");
243 let res = cycle_at(&path, &[], VendorId::Anthropic, 1);
244 assert!(matches!(res, Err(AppError::Other(_))));
245 }
246}