Skip to main content

agentmux_srv/server/account_episodes/
fresh.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The sign-in of each account as its credentials file says now, not as the store last recorded it.
5//!
6//! The store's status is written at a spawn, and by the credential watch only when a file is
7//! emptied, and the watch needs two looks. A file emptied since the last spawn left the store at
8//! `valid`: the account list showed a sign-in a restart would find dead, and a switch moved an agent
9//! onto it. Every read that decides where an agent may go reads the file again.
10
11use crate::backend::providers::resolve_provider_alias;
12use crate::backend::storage::identities::{IdentityAccount, SecretRef};
13use crate::identity::resolver::{probe_oauth_status, OAuthProbeStatus};
14use crate::server::AppState;
15
16const REREAD_GAP: std::time::Duration = std::time::Duration::from_millis(100);
17
18/// `account`'s status read from its credentials file. Only what the file proves moves it: no token
19/// in it is `needs_reauth`, and a live token turns a stored `expired` back to `valid`. A lapsed
20/// access token with a refresh token is left as stored, because the CLI renews it by itself and the
21/// file cannot say whether that will work. `invalid` (a provider refusal), `needs_reauth` and
22/// `unknown` are not re-read, and an account the file cannot speak for (no config dir, a Keychain on
23/// macOS) keeps the stored status.
24fn status_now(account: &IdentityAccount, now_ms: i64) -> String {
25    status_after(account, now_ms, || std::thread::sleep(REREAD_GAP))
26}
27
28/// [`status_now`], with what happens between the two looks given (a pause, in production).
29fn status_after(account: &IdentityAccount, now_ms: i64, between_looks: impl FnOnce()) -> String {
30    let SecretRef::OAuthConfigDir { dir } = &account.secret_ref else { return account.status.clone() };
31    if !matches!(account.status.as_str(), "valid" | "ok" | "expired") {
32        return account.status.clone();
33    }
34    let provider = resolve_provider_alias(&account.provider);
35    let mut read = probe_oauth_status(provider, dir, now_ms);
36    if read == Some(OAuthProbeStatus::NeedsReauth) {
37        // A CLI rewriting the file can leave it unreadable for a moment: look again before trusting it.
38        between_looks();
39        read = probe_oauth_status(provider, dir, now_ms);
40    }
41    match read {
42        Some(OAuthProbeStatus::NeedsReauth) => "needs_reauth".to_string(),
43        Some(OAuthProbeStatus::Valid) if account.status == "expired" => "valid".to_string(),
44        _ => account.status.clone(),
45    }
46}
47
48/// `accounts` with each status read from its file now.
49pub(super) fn refreshed(mut accounts: Vec<IdentityAccount>, now_ms: i64) -> Vec<IdentityAccount> {
50    for a in &mut accounts {
51        a.status = status_now(a, now_ms);
52    }
53    accounts
54}
55
56/// Every account on this machine, statuses read now. BLOCKING (store and file reads).
57pub(super) fn identity_list(state: &AppState) -> Result<Vec<IdentityAccount>, String> {
58    let all = state.id_store.identity_list(None).map_err(|e| e.to_string())?;
59    Ok(refreshed(all, agentmux_common::time::now_ms()))
60}
61
62#[cfg(test)]
63mod tests {
64    use super::*;
65
66    const NOW: i64 = 5_000_000;
67
68    fn account(dir: &std::path::Path, status: &str) -> IdentityAccount {
69        IdentityAccount {
70            id: "fresh-1".into(),
71            name: "fresh-1".into(),
72            provider: "claude".into(),
73            kind: "oauth".into(),
74            display_name: String::new(),
75            secret_ref: SecretRef::OAuthConfigDir { dir: dir.to_str().unwrap().into() },
76            context: serde_json::json!({}),
77            status: status.into(),
78            created_at: 0,
79            updated_at: 0,
80        }
81    }
82
83    fn read(file: &str, status: &str) -> String {
84        let tmp = tempfile::tempdir().unwrap();
85        std::fs::write(tmp.path().join(".credentials.json"), file).unwrap();
86        status_now(&account(tmp.path(), status), NOW)
87    }
88
89    #[test]
90    fn a_lapsed_access_token_that_can_renew_is_left_as_stored() {
91        let lapsed = format!(r#"{{"claudeAiOauth":{{"accessToken":"a","refreshToken":"r","expiresAt":{}}}}}"#, NOW - 1);
92        assert_eq!(read(&lapsed, "valid"), "valid");
93        assert_eq!(read(&lapsed, "expired"), "expired");
94    }
95
96    #[test]
97    fn an_emptied_file_is_signed_out_whatever_the_store_says() {
98        assert_eq!(read(r#"{"claudeAiOauth":{}}"#, "valid"), "needs_reauth");
99        assert_eq!(read(r#"{"claudeAiOauth":{}}"#, "ok"), "needs_reauth");
100    }
101
102    #[test]
103    fn a_file_that_is_whole_again_on_the_second_look_is_not_signed_out() {
104        let tmp = tempfile::tempdir().unwrap();
105        let file = tmp.path().join(".credentials.json");
106        std::fs::write(&file, "{ half written").unwrap();
107        let whole = format!(r#"{{"claudeAiOauth":{{"accessToken":"a","refreshToken":"r","expiresAt":{}}}}}"#, NOW + 3_600_000);
108        // The writer finishes between the two looks: done in the pause itself, not by a thread racing a clock
109        // (on a loaded machine the thread can be late, or the second look can catch the file mid-write).
110        assert_eq!(status_after(&account(tmp.path(), "valid"), NOW, || std::fs::write(&file, &whole).unwrap()), "valid");
111        let once = std::cell::Cell::new(0);
112        assert_eq!(status_after(&account(tmp.path(), "valid"), NOW, || once.set(once.get() + 1)), "valid", "a file that is whole stays valid");
113        assert_eq!(once.get(), 0, "and is not looked at twice");
114    }
115
116    #[test]
117    fn a_live_token_keeps_ok_and_turns_a_stored_expired_back_to_valid() {
118        let live = format!(r#"{{"claudeAiOauth":{{"accessToken":"a","refreshToken":"r","expiresAt":{}}}}}"#, NOW + 3_600_000);
119        assert_eq!(read(&live, "ok"), "ok");
120        assert_eq!(read(&live, "expired"), "valid");
121    }
122
123    #[test]
124    fn a_refusal_and_an_unchecked_account_stay_as_stored() {
125        let live = format!(r#"{{"claudeAiOauth":{{"accessToken":"a","refreshToken":"r","expiresAt":{}}}}}"#, NOW + 3_600_000);
126        for stored in ["invalid", "needs_reauth", "unknown"] {
127            assert_eq!(read(&live, stored), stored);
128        }
129    }
130
131    #[test]
132    fn an_account_with_no_config_dir_keeps_its_status() {
133        let mut a = account(std::path::Path::new("x"), "valid");
134        a.secret_ref = SecretRef::Keychain { service: "s".into(), account: "a".into() };
135        assert_eq!(status_now(&a, NOW), "valid");
136    }
137}