Skip to main content

agentmux_srv/server/account_episodes/
login_recheck.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A pane left signed out by a login that has since been signed in again clears itself (#47468).
5//!
6//! A pane whose last turn was refused on its login keeps that failure until a clean turn or a sign-in
7//! that srv saw ([`super::after_sign_in`]) clears it, and a signed-out pane holds its messages, so no
8//! turn can run to clear it. A person signing in from a pane's own CLI, or a credentials file that
9//! came back, reached neither: the pane stayed "Not authenticated" for hours after the account read
10//! signed in, and a restart did not help.
11//!
12//! On every tick, a signed-out pane whose account holds a token that is still good has its failure
13//! cleared and is told, as after a sign-in. An access token that expired is no longer good, so the
14//! token a turn was refused on for that reason cannot pass. A token the provider refuses for another
15//! reason (revoked, say) can: it is tried once for a pane per [`TRIED_MS`] and not again, so such a
16//! login costs one turn, not one a tick.
17
18use std::collections::HashMap;
19use std::sync::{LazyLock, Mutex};
20
21use crate::agents::failure::FailureClass;
22use crate::backend::agent_state::failure_of_block;
23use crate::backend::obj::Block;
24use crate::backend::storage::identities::SecretRef;
25use crate::identity::resolver::claude_token_expiry_ms;
26use crate::server::AppState;
27
28use super::machine::BlockedPane;
29use super::resume::Failed;
30use super::{canonical, AgentState};
31
32/// How long a try is remembered. Clearing a pane removes its failure, so the pane leaves the signed-out
33/// set at once: the memory has to outlive that, or a login the provider keeps refusing would be tried
34/// again at every failure.
35const TRIED_MS: i64 = 6 * 60 * 60 * 1000;
36
37/// For each pane, the token expiry it was last cleared for and when: the same token is not tried twice
38/// within [`TRIED_MS`].
39static TRIED: LazyLock<Mutex<HashMap<String, (i64, i64)>>> = LazyLock::new(Default::default);
40
41/// Whether the credentials file holds a token that is still good at `now_ms` (unix ms). The failure
42/// being cleared is a past one, so a token good now is not the expired one the turn was refused on; it
43/// can still be one the provider refuses for another reason (revoked), which [`first_try`] bounds.
44pub(super) fn is_good_token(expiry_ms: Option<i64>, now_ms: i64) -> bool {
45    expiry_ms.is_some_and(|expiry| expiry > now_ms)
46}
47
48/// Records that `expiry_ms` is tried for `block_id` at `now_ms`; `false` when it already was within
49/// [`TRIED_MS`]. Entries older than that are dropped.
50pub(super) fn first_try(tried: &mut HashMap<String, (i64, i64)>, block_id: &str, expiry_ms: i64, now_ms: i64) -> bool {
51    tried.retain(|_, (_, at)| now_ms - *at < TRIED_MS);
52    if tried.get(block_id).is_some_and(|(e, _)| *e == expiry_ms) {
53        return false;
54    }
55    tried.insert(block_id.to_string(), (expiry_ms, now_ms));
56    true
57}
58
59/// Clear the signed-out panes among `panes` whose login is new, and tell them. BLOCKING.
60pub(super) fn run(state: &AppState, panes: &[BlockedPane]) {
61    let signed_out: Vec<&BlockedPane> = panes.iter().filter(|p| matches!(p.state, AgentState::SignedOut) && canonical(&p.provider) == "claude").collect();
62    if signed_out.is_empty() {
63        return;
64    }
65    let accounts = state.id_store.identity_list(None).unwrap_or_default();
66    let now_ms = agentmux_common::time::now_ms();
67    let mut tried = TRIED.lock().unwrap_or_else(|e| e.into_inner());
68    let mut cleared = Vec::new();
69    for pane in signed_out {
70        let Some(account) = accounts.iter().find(|a| a.id == pane.account_id) else { continue };
71        let SecretRef::OAuthConfigDir { dir } = &account.secret_ref else { continue };
72        let expiry = claude_token_expiry_ms(dir);
73        let Some(block) = state.mstore.get::<Block>(&pane.block_id).ok().flatten() else { continue };
74        let Some(failure) = failure_of_block(&block).filter(|f| f.code == FailureClass::Auth) else { continue };
75        let Some(expiry) = expiry.filter(|_| is_good_token(expiry, now_ms)) else { continue };
76        if !first_try(&mut tried, &pane.block_id, expiry, now_ms) {
77            continue;
78        }
79        crate::backend::blockcontroller::core::persist_last_failure(&block.oid, None, &Some(state.mstore.clone()), &Some(state.event_bus.clone()));
80        cleared.push(Failed { block_id: block.oid.clone(), failed_at_ms: failure.at_ms });
81    }
82    drop(tried);
83    if !cleared.is_empty() {
84        tracing::info!(cleared = cleared.len(), "account episode: a login signed in again since a pane's turn failed cleared the pane's signed-out state");
85        super::after_clearing();
86        super::resume::start(cleared, now_ms);
87    }
88}
89
90#[cfg(test)]
91mod tests {
92    use super::*;
93
94    #[test]
95    fn a_token_good_now_passes() {
96        assert!(is_good_token(Some(9000), 2000));
97    }
98
99    #[test]
100    fn a_token_that_is_expired_missing_or_expiring_now_does_not() {
101        assert!(!is_good_token(Some(1500), 2000), "expired");
102        assert!(!is_good_token(Some(2000), 2000), "expiring this instant");
103        assert!(!is_good_token(None, 2000), "no token");
104    }
105
106    #[test]
107    fn a_token_is_tried_once_for_a_pane() {
108        let mut tried = HashMap::new();
109        assert!(first_try(&mut tried, "b1", 9000, 100));
110        assert!(!first_try(&mut tried, "b1", 9000, 200), "the same token again");
111        assert!(first_try(&mut tried, "b1", 12000, 300), "a newer token");
112        assert!(first_try(&mut tried, "b2", 9000, 400), "another pane");
113    }
114
115    #[test]
116    fn a_try_outlives_the_pane_leaving_the_signed_out_set() {
117        // Cleared at 100, the turn fails on the same token and the pane is signed out again much later,
118        // with other panes tried in between: still not tried again until the memory runs out.
119        let mut tried = HashMap::new();
120        assert!(first_try(&mut tried, "b1", 9000, 100));
121        assert!(first_try(&mut tried, "b2", 7000, 5_000), "another pane meanwhile");
122        assert!(!first_try(&mut tried, "b1", 9000, TRIED_MS - 1), "the same token inside the window");
123        assert!(first_try(&mut tried, "b1", 9000, TRIED_MS + 101), "after the window it is tried once more");
124    }
125}