Skip to main content

agentmux_srv_core/identity/
credential_watch.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A Claude sign-in that is lost while agents run on it is noticed when it happens, not at the
5//! next spawn.
6//!
7//! The Claude CLI keeps its token in memory, so an account whose credentials file is emptied (two
8//! CLIs raced a refresh, a sign-out in another window) keeps working until its agents restart.
9//! The one probe of the file runs at spawn (`oauth_probe`), so for hours nothing said the sign-in
10//! was gone, and the first sign of it was every agent failing at the next upgrade.
11//!
12//! [`check`] runs on the account tick. It probes each Claude account's config dir. A CLI that is
13//! rewriting the file can leave it unreadable for a moment, so a signed-out reading counts only
14//! when a look at least [`LOOK_GAP_MS`] later says the same; then it logs once, marks the account `needs_reauth`
15//! (Connectors shows Reconnect) and tells the account list to reload. An account it marked that
16//! reads signed in again is put back. It never logs a token value (the probe it calls withholds them from transcripts), never writes the credentials
17//! file, and does not start a sign-in.
18
19use 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/// What the ticks have made of an account's sign-in so far.
28#[derive(Clone, Copy, PartialEq, Eq, Debug)]
29enum Seen {
30    /// Signed in on the last look.
31    In,
32    /// Signed out once after being signed in, at this time (ms): a look [`LOOK_GAP_MS`] later decides.
33    Wobble(i64),
34    /// Signed out twice running, after being signed in: it was reported.
35    Out,
36}
37
38/// What a tick does with an account.
39#[derive(PartialEq, Eq, Debug)]
40enum Step {
41    Nothing,
42    /// The sign-in is lost: say so and mark the account.
43    Lost,
44    /// A reported account is signed in again: put its status back.
45    Back,
46}
47
48/// How far apart the two signed-out looks must be. `check` runs on every account refresh, which
49/// an agent's failure or turn end brings forward by a second or two, so the count of looks alone
50/// would not outlast a rewrite; this is the account tick (15 s) less a little.
51const LOOK_GAP_MS: i64 = 10_000;
52
53/// The next [`Seen`] and what to do, from the last one and this reading at `now_ms`. A first
54/// look, or an account that was never signed in, is not news.
55fn 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
67/// What each account's sign-in has been on the last looks, by account id.
68fn 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
73/// The account's probe: `Valid` or `Expired` (a renewable token) is signed in, `NeedsReauth` is
74/// not. `None` when the file cannot tell (a platform that keeps it in a keychain, or not a Claude
75/// account).
76fn 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
95/// Look at every Claude account once and act on the ones whose sign-in was lost or came back.
96/// BLOCKING (file and store reads). Returns the ids it marked, for tests.
97pub 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
101/// [`check`] over the given history and clock, so a test keeps its own.
102fn 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                // The credentials came back with a token that is good now: the agents it signed out are
135                // signed in again (#47468). An expired one proves nothing; the pane re-check handles it
136                // once a newer token is there.
137                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    /// An agent's turn end brings the account refresh forward by a second or two, so two looks that
185    /// close together are one rewrite, not two.
186    #[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        // The sign-in comes back (the user signed in again): the status is put back.
219        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}