1use std::path::{Path, PathBuf};
11
12use crate::backend::model_catalog::CatalogModel;
13
14pub const MODELS_CACHE_FILE: &str = "models_cache.json";
16const AUTH_FILE: &str = "auth.json";
18
19#[derive(serde::Deserialize)]
20struct Cache {
21 #[serde(default)]
22 fetched_at: String,
23 #[serde(default)]
24 models: Vec<CachedModel>,
25}
26
27#[derive(serde::Deserialize)]
28struct CachedModel {
29 #[serde(default)]
30 slug: String,
31 #[serde(default)]
32 display_name: String,
33 #[serde(default)]
34 visibility: String,
35 #[serde(default)]
36 priority: i64,
37 #[serde(default)]
38 default_reasoning_level: Option<String>,
39 #[serde(default)]
40 supported_reasoning_levels: Vec<ReasoningLevel>,
41}
42
43#[derive(serde::Deserialize)]
44struct ReasoningLevel {
45 #[serde(default)]
46 effort: String,
47}
48
49fn parse(contents: &str) -> Option<(String, Vec<CatalogModel>)> {
52 let cache: Cache = serde_json::from_str(contents).ok()?;
53 let mut listed: Vec<CachedModel> = cache
54 .models
55 .into_iter()
56 .filter(|m| m.visibility == "list" && !m.slug.is_empty())
57 .collect();
58 listed.sort_by_key(|m| m.priority);
59 let models = listed
60 .into_iter()
61 .map(|m| CatalogModel {
62 display_name: if m.display_name.is_empty() { m.slug.clone() } else { m.display_name },
63 id: m.slug,
64 efforts: m.supported_reasoning_levels.into_iter().map(|l| l.effort).filter(|e| !e.is_empty()).collect(),
65 default_effort: m.default_reasoning_level.filter(|e| !e.is_empty()),
66 })
67 .collect();
68 Some((cache.fetched_at, models))
69}
70
71pub fn models_every_account_lists(dirs: impl IntoIterator<Item = PathBuf>) -> Vec<CatalogModel> {
81 let mut lists: Vec<(String, Vec<CatalogModel>)> = Vec::new();
82 for d in dirs {
83 let list = std::fs::read_to_string(d.join(MODELS_CACHE_FILE))
84 .ok()
85 .and_then(|s| parse(&s))
86 .filter(|(_, models)| !models.is_empty());
87 match list {
88 Some(l) => lists.push(l),
89 None if d.join(AUTH_FILE).is_file() => return Vec::new(),
90 None => {}
91 }
92 }
93 lists.sort_by(|a, b| b.0.cmp(&a.0));
95 let Some(((_, newest), others)) = lists.split_first() else {
96 return Vec::new();
97 };
98 newest
99 .iter()
100 .filter_map(|m| {
101 let same: Vec<&CatalogModel> =
102 others.iter().map(|(_, list)| list.iter().find(|o| o.id == m.id)).collect::<Option<_>>()?;
103 let mut model = m.clone();
107 model.efforts.retain(|e| same.iter().all(|o| o.efforts.contains(e)));
108 if same.iter().any(|o| o.default_effort != model.default_effort)
109 || model.default_effort.as_ref().is_some_and(|d| !model.efforts.contains(d))
110 {
111 model.default_effort = None;
112 }
113 Some(model)
114 })
115 .collect()
116}
117
118pub fn forget_models_on_sign_in(dir: &Path) {
124 match std::fs::remove_file(dir.join(MODELS_CACHE_FILE)) {
125 Ok(()) => tracing::info!(target: "identity", dir = %dir.display(), "codex sign-in: dropped the old model list"),
126 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
127 Err(e) => tracing::warn!(target: "identity", dir = %dir.display(), error = %e, "codex sign-in: could not drop the old model list"),
128 }
129}
130
131pub fn codex_dirs(identities_dir: &Path, auth_dir_name: &str) -> Vec<PathBuf> {
137 std::fs::read_dir(identities_dir)
138 .map(|rd| rd.filter_map(|e| e.ok()).map(|e| e.path().join(auth_dir_name)).collect())
139 .unwrap_or_default()
140}
141
142pub fn installed_common_model_ids() -> Vec<String> {
147 #[cfg(any(test, feature = "test-support"))]
148 {
149 Vec::new()
150 }
151 #[cfg(not(any(test, feature = "test-support")))]
152 {
153 let Some(paths) = agentmux_common::DataPaths::from_env() else {
154 return Vec::new();
155 };
156 let Some(provider) = crate::backend::providers::get_provider("codex") else {
157 return Vec::new();
158 };
159 let dirs = codex_dirs(&paths.identities_dir(), provider.auth_dir_name);
160 models_every_account_lists(dirs).into_iter().map(|m| m.id).collect()
161 }
162}
163
164#[cfg(test)]
165mod tests {
166 use super::*;
167
168 fn cache(fetched_at: &str, models: &[(&str, &str, i64)]) -> String {
169 let models: Vec<serde_json::Value> = models
170 .iter()
171 .map(|(slug, vis, prio)| {
172 serde_json::json!({
173 "slug": slug, "display_name": slug.to_uppercase(), "visibility": vis, "priority": prio, "context_window": 1,
174 "default_reasoning_level": "medium",
175 "supported_reasoning_levels": [
176 { "effort": "low", "description": "Fast" },
177 { "effort": "medium", "description": "Balanced" },
178 { "effort": "ultra", "description": "Deepest" }
179 ]
180 })
181 })
182 .collect();
183 serde_json::json!({ "fetched_at": fetched_at, "client_version": "0.154.0", "models": models }).to_string()
184 }
185
186 #[test]
187 fn lists_the_visible_models_in_the_clis_order() {
188 let (_, models) = parse(&cache(
189 "2026-10-22T06:47:36Z",
190 &[("gpt-5.6-sol", "list", 6), ("hidden-review", "hide", 1), ("gpt-6-astra", "list", 2)],
191 ))
192 .unwrap();
193 let ids: Vec<&str> = models.iter().map(|m| m.id.as_str()).collect();
194 assert_eq!(ids, ["gpt-6-astra", "gpt-5.6-sol"]);
195 assert_eq!(models[0].display_name, "GPT-6-ASTRA");
196 }
197
198 #[test]
200 fn keeps_each_models_efforts_and_default() {
201 let (_, models) = parse(&cache("2026-10-22T06:47:36Z", &[("gpt-6-astra", "list", 2)])).unwrap();
202 assert_eq!(models[0].efforts, ["low", "medium", "ultra"]);
203 assert_eq!(models[0].default_effort.as_deref(), Some("medium"));
204 let bare = serde_json::json!({ "fetched_at": "x", "models": [{ "slug": "m", "visibility": "list" }] }).to_string();
206 let (_, models) = parse(&bare).unwrap();
207 assert!(models[0].efforts.is_empty());
208 assert_eq!(models[0].default_effort, None);
209 }
210
211 #[test]
212 fn offers_only_what_every_account_lists_in_the_newest_lists_order_and_skips_dirs_without_a_cache() {
213 let root = tempfile::tempdir().unwrap();
214 let (plus, pro, none) = (root.path().join("a"), root.path().join("b"), root.path().join("c"));
215 for d in [&plus, &pro, &none] {
216 std::fs::create_dir_all(d).unwrap();
217 }
218 std::fs::write(
219 plus.join(MODELS_CACHE_FILE),
220 cache("2026-10-21T00:00:00Z", &[("gpt-5.6-sol", "list", 6), ("gpt-6-astra", "list", 2)]),
221 )
222 .unwrap();
223 std::fs::write(
224 pro.join(MODELS_CACHE_FILE),
225 cache("2026-10-22T00:00:00Z", &[("gpt-6-astra", "list", 2), ("gpt-6-pro", "list", 1), ("gpt-5.6-sol", "list", 6)]),
226 )
227 .unwrap();
228 let ids = |models: Vec<CatalogModel>| models.into_iter().map(|m| m.id).collect::<Vec<_>>();
229 assert_eq!(ids(models_every_account_lists([plus.clone(), none, pro.clone()])), ["gpt-6-astra", "gpt-5.6-sol"]);
231 assert_eq!(ids(models_every_account_lists([pro])), ["gpt-6-pro", "gpt-6-astra", "gpt-5.6-sol"]);
233 }
234
235 #[test]
238 fn offers_only_the_effort_levels_every_account_takes() {
239 let root = tempfile::tempdir().unwrap();
240 let (a, b) = (root.path().join("a"), root.path().join("b"));
241 for d in [&a, &b] {
242 std::fs::create_dir_all(d).unwrap();
243 }
244 let with_levels = |fetched_at: &str, levels: &[&str], default: &str| {
245 let levels: Vec<serde_json::Value> = levels.iter().map(|l| serde_json::json!({ "effort": l })).collect();
246 serde_json::json!({ "fetched_at": fetched_at, "models": [{
247 "slug": "gpt-6-astra", "visibility": "list", "priority": 1,
248 "default_reasoning_level": default, "supported_reasoning_levels": levels
249 }] })
250 .to_string()
251 };
252 std::fs::write(a.join(MODELS_CACHE_FILE), with_levels("2026-10-22T00:00:00Z", &["low", "medium", "high", "ultra"], "low")).unwrap();
253 std::fs::write(b.join(MODELS_CACHE_FILE), with_levels("2026-10-21T00:00:00Z", &["low", "medium", "high"], "low")).unwrap();
254 let models = models_every_account_lists([a.clone(), b.clone()]);
255 assert_eq!(models[0].efforts, ["low", "medium", "high"], "no ultra: account b's model doesn't take it");
256 assert_eq!(models[0].default_effort.as_deref(), Some("low"), "both default to low");
257 std::fs::write(b.join(MODELS_CACHE_FILE), with_levels("2026-10-21T00:00:00Z", &["low", "medium", "high"], "medium")).unwrap();
259 assert_eq!(models_every_account_lists([a, b])[0].default_effort, None);
260 }
261
262 #[test]
263 fn a_signed_in_account_without_a_list_yet_makes_the_common_list_unknown() {
264 let root = tempfile::tempdir().unwrap();
265 let (old, fresh, other) = (root.path().join("a"), root.path().join("b"), root.path().join("c"));
266 for d in [&old, &fresh, &other] {
267 std::fs::create_dir_all(d).unwrap();
268 }
269 std::fs::write(old.join(MODELS_CACHE_FILE), cache("2026-10-22T00:00:00Z", &[("gpt-6-pro", "list", 1)])).unwrap();
270 assert_eq!(models_every_account_lists([old.clone(), fresh.clone(), other]).len(), 1);
272 std::fs::write(fresh.join(AUTH_FILE), "{}").unwrap();
274 assert!(models_every_account_lists([old, fresh]).is_empty());
275 }
276
277 #[test]
278 fn a_sign_in_forgets_the_old_list() {
279 let root = tempfile::tempdir().unwrap();
280 std::fs::write(root.path().join(MODELS_CACHE_FILE), cache("2026-10-22T00:00:00Z", &[("gpt-6-pro", "list", 1)])).unwrap();
281 std::fs::write(root.path().join(AUTH_FILE), "{}").unwrap();
282 forget_models_on_sign_in(root.path());
283 assert!(!root.path().join(MODELS_CACHE_FILE).exists());
284 assert!(root.path().join(AUTH_FILE).exists(), "only the list goes");
285 forget_models_on_sign_in(root.path()); assert!(models_every_account_lists([root.path().to_path_buf()]).is_empty(), "unknown until the CLI fetches it again");
287 }
288
289 #[test]
290 fn lists_that_share_nothing_offer_nothing() {
291 let root = tempfile::tempdir().unwrap();
292 let (a, b) = (root.path().join("a"), root.path().join("b"));
293 for (d, id) in [(&a, "gpt-5.5"), (&b, "gpt-6-astra")] {
294 std::fs::create_dir_all(d).unwrap();
295 std::fs::write(d.join(MODELS_CACHE_FILE), cache("2026-10-22T00:00:00Z", &[(id, "list", 1)])).unwrap();
296 }
297 assert!(models_every_account_lists([a, b]).is_empty());
298 }
299
300 #[test]
301 fn nothing_cached_or_unreadable_is_an_empty_list() {
302 let root = tempfile::tempdir().unwrap();
303 std::fs::write(root.path().join(MODELS_CACHE_FILE), "not json").unwrap();
304 assert!(models_every_account_lists([root.path().to_path_buf(), root.path().join("missing")]).is_empty());
305 }
306
307 #[test]
308 fn finds_every_accounts_codex_dir_but_not_the_old_shared_one() {
309 let root = tempfile::tempdir().unwrap();
310 let identities = root.path().join("identities");
311 std::fs::create_dir_all(identities.join("acct-1").join("codex")).unwrap();
312 std::fs::create_dir_all(identities.join("acct-2")).unwrap();
313 let dirs = codex_dirs(&identities, "codex");
314 assert!(dirs.contains(&identities.join("acct-1").join("codex")));
315 assert!(!dirs.iter().any(|d| d.starts_with(root.path().join("providers"))), "the shared provider dir is no account's");
316 }
317}