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 "copilot" => Some(VendorId::Copilot),
106 "zai" => Some(VendorId::Zai),
107 "openrouter" => Some(VendorId::Openrouter),
108 "deepseek" => Some(VendorId::Deepseek),
109 "kimi" => Some(VendorId::Kimi),
110 "kilo" => Some(VendorId::Kilo),
111 "novita" => Some(VendorId::Novita),
112 "moonshot" => Some(VendorId::Moonshot),
113 "grok" => Some(VendorId::Grok),
114 "supergrok" => Some(VendorId::Supergrok),
115 "antigravity" => Some(VendorId::Antigravity),
116 "cursor" => Some(VendorId::Cursor),
117 "minimax" => Some(VendorId::Minimax),
118 "kiro" => Some(VendorId::Kiro),
119 "nous" => Some(VendorId::NousResearch),
120 "opencode-go" => Some(VendorId::OpenCodeGo),
121 "commandcode" => Some(VendorId::CommandCode),
122 "ollama" => Some(VendorId::Ollama),
123 _ => None,
124 }
125}
126
127#[cfg(test)]
128mod tests {
129 use super::*;
130 use tempfile::TempDir;
131
132 const CYCLE_SET: [VendorId; 4] = [
135 VendorId::Anthropic,
136 VendorId::Openai,
137 VendorId::Zai,
138 VendorId::Openrouter,
139 ];
140
141 #[test]
147 fn concurrent_cycles_do_not_lose_a_step() {
148 let td = TempDir::new().unwrap();
149 let path = td.path().join("active_vendor");
150 let start = VendorId::Anthropic;
151
152 const THREADS: usize = 4;
155 std::thread::scope(|s| {
156 for _ in 0..THREADS {
157 s.spawn(|| {
158 let _ = cycle_at(&path, &CYCLE_SET, start, 1);
159 });
160 }
161 });
162
163 let landed = read_from(&path).expect("a vendor must have been persisted");
164 assert_eq!(
165 landed,
166 start,
167 "{THREADS} single steps over {} vendors must return to the start; \
168 landing on {landed:?} means a step was lost to a race",
169 CYCLE_SET.len()
170 );
171 }
172
173 #[test]
174 fn parse_slug_round_trip() {
175 for id in VendorId::all() {
176 assert_eq!(parse_slug(id.slug()), Some(*id));
177 }
178 }
179
180 #[test]
181 fn parse_slug_unknown_returns_none() {
182 assert!(parse_slug("not-a-vendor").is_none());
183 assert!(parse_slug("").is_none());
184 }
185
186 #[test]
187 fn read_from_missing_or_garbage_returns_none() {
188 let td = TempDir::new().unwrap();
189 assert!(read_from(&td.path().join("active_vendor")).is_none());
191 let path = td.path().join("active_vendor");
193 write_to(&path, VendorId::Zai).unwrap();
194 assert_eq!(read_from(&path), Some(VendorId::Zai));
195 fs::write(&path, "not-a-vendor").unwrap();
197 assert!(read_from(&path).is_none());
198 }
199
200 #[test]
201 fn cycle_at_persists_state_across_calls() {
202 let td = TempDir::new().unwrap();
203 let path = td.path().join("active_vendor");
204
205 let v = cycle_at(&path, &CYCLE_SET, VendorId::Anthropic, 1).unwrap();
207 assert_eq!(v, VendorId::Openai);
208 assert_eq!(read_from(&path), Some(VendorId::Openai));
209
210 let v = cycle_at(&path, &CYCLE_SET, VendorId::Anthropic, 1).unwrap();
212 assert_eq!(v, VendorId::Zai);
213 assert_eq!(read_from(&path), Some(VendorId::Zai));
214 }
215
216 #[test]
217 fn cycle_at_wraps_forward_and_backward() {
218 let td = TempDir::new().unwrap();
219 let path = td.path().join("active_vendor");
220 write_to(&path, VendorId::Anthropic).unwrap();
221
222 assert_eq!(
224 cycle_at(&path, &CYCLE_SET, VendorId::Anthropic, -1).unwrap(),
225 VendorId::Openrouter
226 );
227 assert_eq!(
229 cycle_at(&path, &CYCLE_SET, VendorId::Anthropic, 1).unwrap(),
230 VendorId::Anthropic
231 );
232 }
233
234 #[test]
235 fn cycle_at_ignores_persisted_vendor_not_in_enabled_set() {
236 let td = TempDir::new().unwrap();
237 let path = td.path().join("active_vendor");
238 write_to(&path, VendorId::Deepseek).unwrap();
240 let enabled = [VendorId::Anthropic, VendorId::Openai];
241 let v = cycle_at(&path, &enabled, VendorId::Openai, 1).unwrap();
243 assert_eq!(v, VendorId::Anthropic);
244 }
245
246 #[test]
247 fn cycle_at_errors_on_empty_enabled() {
248 let td = TempDir::new().unwrap();
249 let path = td.path().join("active_vendor");
250 let res = cycle_at(&path, &[], VendorId::Anthropic, 1);
251 assert!(matches!(res, Err(AppError::Other(_))));
252 }
253}