Skip to main content

agentmux_srv/server/account_episodes/
login_expiry.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! A login that expired: its agents move to a valid login by themselves, and the one that was
5//! mid-turn carries on.
6//!
7//! An account whose sign-in status is `expired`, `needs_reauth` or `invalid` can't run an agent. The
8//! agents on it:
9//! - move to another valid login of the same account first (the same stable id, so the same plan
10//!   and quota), else to another signed-in account of the provider that can run (never one marked
11//!   "never fail over to this"; `agent:accountfailover` turns it all off), as `agent.account.switch`
12//!   does, once their turn is over;
13//! - get one note that says so; one whose turn died on the expired login gets, as the note, a turn
14//!   of its own: "your last step may not have finished: check git status and your PR first", so it
15//!   carries on instead of sitting idle (a compaction that failed on the login is a turn that
16//!   compacts again on the new one);
17//! - are the person's business once: one notification, and a row in the account strip with the
18//!   sign-in action, until the login is signed in again.
19
20use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
21use std::sync::{LazyLock, Mutex};
22
23use crate::agents::failure::FailureClass;
24use crate::backend::agent_state::AgentState;
25use crate::backend::agent_state::failure_of_block;
26use crate::backend::obj::Block;
27use crate::backend::storage::identities::IdentityAccount;
28use crate::identity::stable_account::stable_account_id;
29use crate::server::app_api::agent_spawn::{account_blocks, account_label_in};
30use crate::server::AppState;
31
32use super::failover::{self, ACTOR_EXPIRED};
33use super::machine::BlockedPane;
34use super::moves::signed_in;
35use super::switch::{open_panes, AccountSwitchStatus, AccountSwitchWhen, META_PENDING_ACCOUNT};
36use super::{canonical, AccountAvailability, AccountAvailabilityEvent};
37
38/// The logins whose agents were moved off after they expired, with when: the person is told once
39/// for each, and the strip shows it until it is signed in again.
40pub(super) static TOLD: LazyLock<Mutex<HashMap<String, u64>>> = LazyLock::new(Default::default);
41
42/// Whether a sign-in status means the login can't run an agent.
43pub(super) fn expired(status: &str) -> bool {
44    matches!(status, "expired" | "needs_reauth" | "invalid")
45}
46
47/// Whether the login is lost, not merely out of date. `needs_reauth` and `invalid` say the provider
48/// refused it. `expired` can be an access token the CLI refreshes by itself (a spawn stores it so), so
49/// it counts only once a pane's run on it was refused: `refused` are the accounts of those panes.
50fn lost(a: &IdentityAccount, refused: &HashSet<&str>) -> bool {
51    match a.status.as_str() {
52        "needs_reauth" | "invalid" => true,
53        "expired" => refused.contains(a.id.as_str()),
54        _ => false,
55    }
56}
57
58/// Of `blocks`, the ones whose turn died on a refused sign-in: read before the move clears it.
59pub(super) fn interrupted(blocks: &[Block]) -> Vec<String> {
60    blocks.iter().filter(|b| failure_of_block(b).is_some_and(|f| f.code == FailureClass::Auth)).map(|b| b.oid.clone()).collect()
61}
62
63/// Where the agents of `from` go: a signed-in login of the same account (stable id) that nothing
64/// blocks, else another signed-in account of its provider that can run. `blocked` is
65/// `account_blocks` (an account a pane found out of quota or signed out); `left` says an account an
66/// agent was just moved off over its limit, which no pane has re-tested.
67pub(super) fn choose<'a>(
68    accounts: &'a [IdentityAccount],
69    blocked: &HashMap<String, String>,
70    left: &dyn Fn(&str) -> bool,
71    from: &IdentityAccount,
72) -> Option<&'a IdentityAccount> {
73    let provider = canonical(&from.provider);
74    let usable = |a: &&IdentityAccount| {
75        a.id != from.id && canonical(&a.provider) == provider && signed_in(&a.status) && !failover::is_never(a) && !blocked.contains_key(&a.id) && !left(&a.id)
76    };
77    let oldest = |a: &&IdentityAccount| (a.created_at, a.id.clone());
78    let same_account = stable_account_id(from);
79    same_account
80        .as_ref()
81        .and_then(|sid| accounts.iter().filter(usable).filter(|a| stable_account_id(a).as_ref() == Some(sid)).min_by_key(oldest))
82        .or_else(|| accounts.iter().filter(usable).min_by_key(oldest))
83}
84
85/// What the agent whose turn was cut off is told, as the turn it starts.
86pub(super) fn resume_note(to_label: &str) -> String {
87    let to = crate::backend::reactive::sanitize::quote_in_system_note(to_label);
88    format!("[AgentMux] Your login expired, so AgentMux moved you to {to}. Your last step may not have finished: check git status and your PR first, then carry on.")
89}
90
91/// Start the turn of each of `block_ids` (panes just restarted on `to_label`) with [`resume_note`],
92/// once its agent has registered.
93pub(super) fn resume(block_ids: &[String], to_label: &str) {
94    let Ok(runtime) = tokio::runtime::Handle::try_current() else { return };
95    for block_id in block_ids {
96        let (block_id, text) = (block_id.clone(), resume_note(to_label));
97        runtime.spawn(async move {
98            if crate::backend::limit_wake::tell_when_registered(&block_id, &text).await {
99                tracing::info!(block_id = %block_id, "login expiry: told the agent to carry on");
100            } else {
101                // Held for the agent's next turn: the move still gets said, though nothing started a turn.
102                tracing::info!(block_id = %block_id, "login expiry: the agent didn't start, so the note is held for its next turn");
103                crate::backend::blockcontroller::system_note_into_turn_or_hold(&block_id, "failover:resume", &text);
104            }
105        });
106    }
107}
108
109/// The open agents on each account, by the links their spawn resolves through (their own, or the
110/// seeded template's an agent inherits).
111fn agents_by_account(state: &AppState) -> BTreeMap<String, BTreeSet<String>> {
112    let defs: HashMap<String, crate::backend::storage::store::AgentDefinition> =
113        state.mstore.agent_def_list().unwrap_or_default().into_iter().map(|d| (d.id.clone(), d)).collect();
114    let open: BTreeSet<String> = super::tab_blocks(&state.mstore)
115        .iter()
116        .map(|b| crate::backend::obj::meta_get_string(&b.meta, "agentId", ""))
117        .filter(|id| !id.is_empty())
118        .collect();
119    let mut out: BTreeMap<String, BTreeSet<String>> = BTreeMap::new();
120    for def_id in open {
121        let Some(def) = defs.get(&def_id) else { continue };
122        let links = crate::identity::resolver::effective_identity_links(&state.mstore, &state.identity_store, def).unwrap_or_default();
123        for link in links {
124            out.entry(link.account_id).or_default().insert(def_id.clone());
125        }
126    }
127    out
128}
129
130/// Move the agents of each lost login. Runs with every episode refresh; `panes` are its blocked panes.
131/// BLOCKING.
132pub(super) fn run(state: &AppState, panes: &[BlockedPane]) {
133    if !failover::enabled(state) {
134        return;
135    }
136    let accounts = super::fresh::identity_list(state).unwrap_or_default();
137    forget_signed_in(state, &accounts);
138    let refused: HashSet<&str> = panes.iter().filter(|p| p.state == AgentState::SignedOut).map(|p| p.account_id.as_str()).collect();
139    let gone: Vec<&IdentityAccount> =
140        accounts.iter().filter(|a| lost(a, &refused) && crate::backend::providers::get_provider(&canonical(&a.provider)).is_some()).collect();
141    if gone.is_empty() {
142        return;
143    }
144    let by_account = agents_by_account(state);
145    let blocked = account_blocks(state, &accounts);
146    let now_ms = agentmux_common::time::now_ms_u64();
147    let left = |id: &str| failover::recently_left(id, now_ms);
148    for from in gone {
149        let provider = canonical(&from.provider);
150        let same_provider: Vec<IdentityAccount> = accounts.iter().filter(|a| canonical(&a.provider) == provider).cloned().collect();
151        let mut moved = 0usize;
152        for def_id in by_account.get(&from.id).into_iter().flatten() {
153            let open = open_panes(state, def_id);
154            // Nothing runs, or a move is queued already.
155            if open.is_empty() || open.iter().any(|b| b.meta.get(META_PENDING_ACCOUNT).is_some_and(|v| v.is_string())) {
156                continue;
157            }
158            let Some(to) = choose(&accounts, &blocked, &left, from) else {
159                tracing::debug!(def_id = %def_id, "login expiry: no valid login to move to");
160                continue;
161            };
162            match super::switch::switch_to(state, ACTOR_EXPIRED, def_id, to, &provider, &same_provider, AccountSwitchWhen::AfterTurn) {
163                Ok(r) if matches!(r.status, AccountSwitchStatus::Switched | AccountSwitchStatus::Queued) => moved += 1,
164                Ok(_) => {}
165                Err(e) => tracing::warn!(def_id = %def_id, error = %e, "login expiry: the move failed"),
166            }
167        }
168        if moved > 0 {
169            tell_person(state, from, moved);
170        }
171    }
172}
173
174/// The notice: once per login until it is signed in again, never naming it (a notification can show on
175/// a locked screen); the strip row names it and has the sign-in action.
176fn tell_person(state: &AppState, from: &IdentityAccount, moved: usize) {
177    let first = TOLD.lock().unwrap_or_else(|e| e.into_inner()).insert(from.id.clone(), agentmux_common::time::now_ms_u64()).is_none();
178    if !first {
179        return;
180    }
181    tracing::info!(provider = %from.provider, moved, "login expiry: a login expired and its agents moved");
182    super::publish(state, event_of(from, "signed_out"));
183    if let Some(router) = crate::backend::notify::router::get(&state.broker) {
184        let agents = if moved == 1 { "1 agent".to_string() } else { format!("{moved} agents") };
185        router.account_unavailable(&notice_key(&from.id), format!("A login expired, so {agents} moved to another login. Sign in again to use it."));
186    }
187}
188
189fn notice_key(account_id: &str) -> String {
190    format!("login:{}", crate::backend::notify::policy::tag_for(account_id))
191}
192
193fn event_of(a: &IdentityAccount, state: &str) -> AccountAvailabilityEvent {
194    AccountAvailabilityEvent { account_id: a.id.clone(), provider: canonical(&a.provider), state: state.to_string(), resets_at_ms: None, agents: Vec::new(), tasks: Vec::new() }
195}
196
197/// A login told about that is signed in again (or gone): its notice comes down and the strip row ends.
198fn forget_signed_in(state: &AppState, accounts: &[IdentityAccount]) {
199    let ended: Vec<String> = {
200        let told = TOLD.lock().unwrap_or_else(|e| e.into_inner());
201        told.keys().filter(|id| !accounts.iter().any(|a| &a.id == *id && expired(&a.status))).cloned().collect()
202    };
203    for id in ended {
204        TOLD.lock().unwrap_or_else(|e| e.into_inner()).remove(&id);
205        if let Some(router) = crate::backend::notify::router::get(&state.broker) {
206            router.resolve(&notice_key(&id), crate::backend::notify::policy::Family::Account);
207        }
208        if let Some(a) = accounts.iter().find(|a| a.id == id) {
209            super::publish(state, event_of(a, "ok"));
210        }
211    }
212}
213
214/// The strip's rows for the logins told about that still need signing in: no agents (they moved), so
215/// the row offers the sign-in, not a move. Not for a login an open episode shows already.
216pub(super) fn rows(state: &AppState, shown: &[String]) -> Vec<AccountAvailability> {
217    let told: Vec<(String, u64)> = TOLD.lock().unwrap_or_else(|e| e.into_inner()).iter().map(|(id, at)| (id.clone(), *at)).collect();
218    let accounts = super::fresh::identity_list(state).unwrap_or_default();
219    let mut out: Vec<AccountAvailability> = told
220        .into_iter()
221        .filter(|(id, _)| !shown.contains(id))
222        .filter_map(|(id, since_ms)| {
223            let a = accounts.iter().find(|a| a.id == id && expired(&a.status))?;
224            let same_provider: Vec<IdentityAccount> = accounts.iter().filter(|o| canonical(&o.provider) == canonical(&a.provider)).cloned().collect();
225            Some(AccountAvailability {
226                account_id: a.id.clone(),
227                account_label: account_label_in(a, &same_provider),
228                provider: canonical(&a.provider),
229                state: "signed_out".to_string(),
230                resets_at_ms: None,
231                limit_window: None,
232                since_ms,
233                agents: Vec::new(),
234                tasks: Vec::new(),
235                candidates: Vec::new(),
236                agent_ids: Vec::new(),
237                block_ids: Vec::new(),
238            })
239        })
240        .collect();
241    out.sort_by(|a, b| (a.since_ms, &a.account_id).cmp(&(b.since_ms, &b.account_id)));
242    out
243}