1use std::collections::HashMap;
20use std::sync::{Mutex, OnceLock};
21
22use crate::backend::mps::Broker;
23use crate::backend::providers::resolve_provider_alias;
24use crate::backend::storage::store::{IdentityAccount, SecretRef, Store};
25use crate::identity::resolver::{oauth_status, probe_oauth_status, OAuthProbeStatus};
26
27#[derive(Clone, Copy, PartialEq, Eq, Debug)]
29enum Seen {
30 In,
32 Wobble(i64),
34 Out,
36}
37
38#[derive(PartialEq, Eq, Debug)]
40enum Step {
41 Nothing,
42 Lost,
44 Back,
46}
47
48const LOOK_GAP_MS: i64 = 10_000;
52
53fn step(before: Option<Seen>, signed_in: bool, now_ms: i64) -> (Option<Seen>, Step) {
56 match (before, signed_in) {
57 (Some(Seen::Out), true) => (Some(Seen::In), Step::Back),
58 (_, true) => (Some(Seen::In), Step::Nothing),
59 (Some(Seen::In), false) => (Some(Seen::Wobble(now_ms)), Step::Nothing),
60 (Some(Seen::Wobble(at)), false) if now_ms - at >= LOOK_GAP_MS => (Some(Seen::Out), Step::Lost),
61 (Some(Seen::Wobble(at)), false) => (Some(Seen::Wobble(at)), Step::Nothing),
62 (Some(Seen::Out), false) => (Some(Seen::Out), Step::Nothing),
63 (None, false) => (None, Step::Nothing),
64 }
65}
66
67fn last_seen() -> &'static Mutex<HashMap<String, Seen>> {
69 static SEEN: OnceLock<Mutex<HashMap<String, Seen>>> = OnceLock::new();
70 SEEN.get_or_init(Default::default)
71}
72
73fn probe(account: &IdentityAccount, now_ms: i64) -> Option<OAuthProbeStatus> {
77 if resolve_provider_alias(&account.provider) != "claude" {
78 return None;
79 }
80 let SecretRef::OAuthConfigDir { dir } = &account.secret_ref else { return None };
81 probe_oauth_status("claude", dir, now_ms)
82}
83
84fn set_status(id_store: &Store, identity_store: &Store, broker: Option<&Broker>, account_id: &str, status: &str) {
85 for store in [id_store, identity_store] {
86 if let Err(e) = store.identity_set_status(account_id, status) {
87 tracing::warn!(target: "identity", account_id = %account_id, error = %e, "credential watch: status write failed");
88 }
89 }
90 if let Some(b) = broker {
91 b.publish_event::<crate::backend::mps_events::IdentityAccountsChanged>(&(), vec![], 0);
92 }
93}
94
95pub fn check(id_store: &Store, identity_store: &Store, broker: Option<&Broker>) -> Vec<String> {
98 check_in(last_seen(), id_store, identity_store, broker, agentmux_common::time::now_ms())
99}
100
101fn check_in(seen: &Mutex<HashMap<String, Seen>>, id_store: &Store, identity_store: &Store, broker: Option<&Broker>, now_ms: i64) -> Vec<String> {
103 let accounts = id_store.identity_list(None).unwrap_or_default();
104 let mut marked = Vec::new();
105 let mut seen = seen.lock().unwrap_or_else(|e| e.into_inner());
106 seen.retain(|id, _| accounts.iter().any(|a| &a.id == id));
107 for account in &accounts {
108 let Some(status) = probe(account, now_ms) else { continue };
109 let signed_in = status != OAuthProbeStatus::NeedsReauth;
110 let (next, what) = step(seen.get(&account.id).copied(), signed_in, now_ms);
111 match next {
112 Some(n) => seen.insert(account.id.clone(), n),
113 None => seen.remove(&account.id),
114 };
115 match what {
116 Step::Nothing => {}
117 Step::Lost => {
118 tracing::warn!(
119 target: "identity",
120 account_id = %account.id,
121 old_status = %account.status,
122 "credentials emptied: this Claude account had a sign-in and its credentials file has had no token on two looks in a row; agents on it work until they restart, then need a sign-in"
123 );
124 if account.status != oauth_status::NEEDS_REAUTH {
125 set_status(id_store, identity_store, broker, &account.id, oauth_status::NEEDS_REAUTH);
126 }
127 marked.push(account.id.clone());
128 }
129 Step::Back => {
130 if account.status == oauth_status::NEEDS_REAUTH {
131 tracing::info!(target: "identity", account_id = %account.id, "credentials are back: this Claude account reads signed in again");
132 set_status(id_store, identity_store, broker, &account.id, status.as_str());
133 }
134 if status == OAuthProbeStatus::Valid {
138 crate::identity::sign_in_hook::after_sign_in(&account.id);
139 }
140 }
141 }
142 }
143 marked
144}
145
146#[cfg(test)]
147mod tests {
148 use super::*;
149
150 fn account(id: &str, dir: &str) -> IdentityAccount {
151 IdentityAccount {
152 id: id.into(),
153 name: id.into(),
154 provider: "claude".into(),
155 kind: "oauth".into(),
156 display_name: String::new(),
157 secret_ref: SecretRef::OAuthConfigDir { dir: dir.into() },
158 context: serde_json::json!({}),
159 status: "ok".into(),
160 created_at: 0,
161 updated_at: 0,
162 }
163 }
164
165 const T: i64 = 5_000_000;
166 const TICK: i64 = 15_000;
167
168 fn write(dir: &std::path::Path, body: &str) {
169 std::fs::write(dir.join(".credentials.json"), body).unwrap();
170 }
171
172 #[test]
173 fn a_sign_in_is_lost_only_after_two_signed_out_looks_in_a_row() {
174 const T: i64 = 1_000_000;
175 assert_eq!(step(None, false, T), (None, Step::Nothing), "a first look at a signed-out account is not news");
176 assert_eq!(step(Some(Seen::In), false, T), (Some(Seen::Wobble(T)), Step::Nothing), "one bad read can be a CLI mid-write");
177 assert_eq!(step(Some(Seen::Wobble(T)), false, T + LOOK_GAP_MS), (Some(Seen::Out), Step::Lost));
178 assert_eq!(step(Some(Seen::Wobble(T)), true, T + LOOK_GAP_MS), (Some(Seen::In), Step::Nothing), "it came back: nothing to say");
179 assert_eq!(step(Some(Seen::Out), false, T), (Some(Seen::Out), Step::Nothing), "said once, not at every tick");
180 assert_eq!(step(Some(Seen::Out), true, T), (Some(Seen::In), Step::Back));
181 assert_eq!(step(Some(Seen::In), true, T), (Some(Seen::In), Step::Nothing));
182 }
183
184 #[test]
187 fn two_looks_close_together_are_one_look() {
188 const T: i64 = 1_000_000;
189 let (seen, _) = step(Some(Seen::In), false, T);
190 assert_eq!(step(seen, false, T + 1_500), (Some(Seen::Wobble(T)), Step::Nothing), "1.5 s later is the same rewrite");
191 assert_eq!(step(seen, false, T + LOOK_GAP_MS - 1), (Some(Seen::Wobble(T)), Step::Nothing));
192 assert_eq!(step(seen, false, T + LOOK_GAP_MS).1, Step::Lost);
193 }
194
195 #[test]
196 fn an_emptied_credentials_file_marks_the_account_once() {
197 let tmp = tempfile::tempdir().unwrap();
198 let dir = tmp.path().to_str().unwrap().to_string();
199 write(tmp.path(), r#"{"claudeAiOauth":{"accessToken":"a","refreshToken":"r","expiresAt":4102444800000}}"#);
200 let seen = Mutex::default();
201 let store = Store::open_in_memory().unwrap();
202 let other = Store::open_in_memory().unwrap();
203 let acct = account("watch-acct-1", &dir);
204 store.identity_upsert(&acct).unwrap();
205 other.identity_upsert(&acct).unwrap();
206
207 assert!(check_in(&seen, &store, &other, None, T).is_empty(), "signed in: nothing to say");
208
209 write(tmp.path(), r#"{"claudeAiOauth":{}}"#);
210 assert!(check_in(&seen, &store, &other, None, T + TICK).is_empty(), "the first signed-out look waits for a second");
211 assert_eq!(store.identity_list(None).unwrap()[0].status, "ok");
212 assert_eq!(check_in(&seen, &store, &other, None, T + 2 * TICK), vec!["watch-acct-1".to_string()]);
213 assert_eq!(store.identity_list(None).unwrap()[0].status, oauth_status::NEEDS_REAUTH);
214 assert_eq!(other.identity_list(None).unwrap()[0].status, oauth_status::NEEDS_REAUTH);
215
216 assert!(check_in(&seen, &store, &other, None, T + 3 * TICK).is_empty(), "said once, not at every tick");
217
218 write(tmp.path(), r#"{"claudeAiOauth":{"accessToken":"a","refreshToken":"r","expiresAt":4102444800000}}"#);
220 assert!(check_in(&seen, &store, &other, None, T + 4 * TICK).is_empty());
221 assert_eq!(store.identity_list(None).unwrap()[0].status, oauth_status::VALID);
222 }
223
224 #[test]
225 fn one_unreadable_look_does_not_mark_a_working_account() {
226 let tmp = tempfile::tempdir().unwrap();
227 let dir = tmp.path().to_str().unwrap().to_string();
228 let good = r#"{"claudeAiOauth":{"accessToken":"a","refreshToken":"r","expiresAt":4102444800000}}"#;
229 write(tmp.path(), good);
230 let seen = Mutex::default();
231 let store = Store::open_in_memory().unwrap();
232 store.identity_upsert(&account("watch-acct-3", &dir)).unwrap();
233 assert!(check_in(&seen, &store, &store, None, T).is_empty());
234
235 write(tmp.path(), "{ half written");
236 assert!(check_in(&seen, &store, &store, None, T + TICK).is_empty());
237 write(tmp.path(), good);
238 assert!(check_in(&seen, &store, &store, None, T + 2 * TICK).is_empty());
239 write(tmp.path(), "{ half written");
240 assert!(check_in(&seen, &store, &store, None, T + 3 * TICK).is_empty(), "two bad reads that are not in a row are not a wipe");
241 assert_eq!(store.identity_list(None).unwrap()[0].status, "ok");
242 }
243
244 #[test]
245 fn an_account_that_was_never_signed_in_is_not_reported() {
246 let tmp = tempfile::tempdir().unwrap();
247 write(tmp.path(), r#"{}"#);
248 let seen = Mutex::default();
249 let store = Store::open_in_memory().unwrap();
250 let acct = account("watch-acct-2", tmp.path().to_str().unwrap());
251 store.identity_upsert(&acct).unwrap();
252 for i in 0..3 {
253 assert!(check_in(&seen, &store, &store, None, T + i * TICK).is_empty());
254 }
255 }
256}