agentmux_srv/server/account_episodes/
failover.rs1use std::collections::BTreeMap;
20
21use serde::{Deserialize, Serialize};
22
23use crate::backend::agent_state::AgentState;
24use crate::backend::obj::Block;
25use crate::backend::storage::identities::IdentityAccount;
26use crate::server::AppState;
27
28use super::accounts::pick;
29use super::machine::BlockedPane;
30use super::moves::signed_in;
31use super::switch::{open_panes, AccountSwitchWhen, META_PENDING_ACCOUNT};
32use super::{agent_name, canonical};
33
34pub const SETTING: &str = "agent:accountfailover";
36pub(super) const ACTOR: &str = "failover";
38pub(super) const ACTOR_EXPIRED: &str = "failover:expired";
40
41pub(super) fn is_actor(actor: &str) -> bool {
43 actor == ACTOR || actor == ACTOR_EXPIRED
44}
45pub use crate::backend::storage::identities::NEVER_FAILOVER;
47
48pub fn is_never(a: &IdentityAccount) -> bool {
50 a.context.get(NEVER_FAILOVER).and_then(|v| v.as_bool()).unwrap_or(false)
51}
52
53#[derive(Debug, Clone, Deserialize, ts_rs::TS)]
55#[ts(export, export_to = "../../../frontend/types/rpc/")]
56pub struct IdentityAccountSetFailoverReq {
57 pub account_id: String,
58 pub allow: bool,
60}
61
62#[derive(Debug, Clone, Serialize, ts_rs::TS)]
64#[ts(export, export_to = "../../../frontend/types/rpc/")]
65pub struct IdentityAccountSetFailoverResult {
66 pub account_id: String,
67 pub allow: bool,
68}
69
70pub(super) fn set_failover(state: &AppState, req: &IdentityAccountSetFailoverReq) -> Result<IdentityAccountSetFailoverResult, String> {
72 let found = state.id_store.identity_set_never_failover(&req.account_id, !req.allow).map_err(|e| format!("identity.account.set_failover: {e}"))?;
73 if !found {
74 return Err(format!("identity.account.set_failover: no account {:?}", req.account_id));
75 }
76 super::refresh_soon();
77 Ok(IdentityAccountSetFailoverResult { account_id: req.account_id.clone(), allow: req.allow })
78}
79
80static LEFT: std::sync::LazyLock<std::sync::Mutex<std::collections::HashMap<String, u64>>> = std::sync::LazyLock::new(Default::default);
84const UNKNOWN_RESET_MS: u64 = 60 * 60_000;
86
87fn remember_left(pane: &BlockedPane, now_ms: u64) {
88 let until = pane.resets_at_ms.unwrap_or(now_ms + UNKNOWN_RESET_MS);
89 LEFT.lock().unwrap_or_else(|e| e.into_inner()).insert(pane.account_id.clone(), until);
90}
91
92pub(super) fn recently_left(account_id: &str, now_ms: u64) -> bool {
93 let mut left = LEFT.lock().unwrap_or_else(|e| e.into_inner());
94 left.retain(|_, until| *until > now_ms);
95 left.contains_key(account_id)
96}
97
98pub(super) fn enabled(state: &AppState) -> bool {
99 state.config_watcher.extra_bool(SETTING).unwrap_or(true)
100}
101
102fn target<'a>(state: &AppState, accounts: &'a [IdentityAccount], pane: &BlockedPane, now_ms: u64) -> Result<&'a IdentityAccount, String> {
105 let usable: Vec<IdentityAccount> =
106 accounts.iter().filter(|a| canonical(&a.provider) == pane.provider && signed_in(&a.status) && !is_never(a) && !recently_left(&a.id, now_ms)).cloned().collect();
107 let chosen = pick(state, &usable, "any with quota", std::slice::from_ref(&pane.account_id), &pane.provider)?;
108 accounts.iter().find(|a| a.id == chosen.id).ok_or_else(|| "the account is gone".to_string())
109}
110
111pub(super) fn run(state: &AppState, panes: &[BlockedPane]) {
115 if !enabled(state) {
116 return;
117 }
118 let mut by_agent: BTreeMap<&str, &BlockedPane> = BTreeMap::new();
119 for pane in panes.iter().filter(|p| p.state == AgentState::Limited && !p.agent_id.is_empty()) {
120 by_agent.entry(pane.agent_id.as_str()).or_insert(pane);
121 }
122 if by_agent.is_empty() {
123 return;
124 }
125 let accounts = super::fresh::identity_list(state).unwrap_or_default();
126 for (def_id, pane) in by_agent {
127 if open_panes(state, def_id).iter().any(|b| b.meta.get(META_PENDING_ACCOUNT).is_some_and(|v| v.is_string())) {
128 continue;
129 }
130 let now_ms = agentmux_common::time::now_ms_u64();
131 let to = match target(state, &accounts, pane, now_ms) {
132 Ok(to) => to,
133 Err(why) => {
134 tracing::debug!(agent = %pane.agent_name, "account failover: no account to move to: {why}");
135 continue;
136 }
137 };
138 let same_provider: Vec<IdentityAccount> = accounts.iter().filter(|a| canonical(&a.provider) == pane.provider).cloned().collect();
139 match super::switch::switch_to(state, ACTOR, def_id, to, &pane.provider, &same_provider, AccountSwitchWhen::AfterTurn) {
140 Ok(_) => remember_left(pane, now_ms),
141 Err(e) => tracing::warn!(agent = %pane.agent_name, error = %e, "account failover: the move failed"),
142 }
143 }
144}
145
146pub(super) fn notify(state: &AppState, def_id: &str, to_label: &str, blocks: &[Block], expired: bool, woken: &[String]) {
151 let Some(first) = blocks.first() else { return };
152 let name = agent_name(&state.mstore, first);
153 let to = crate::backend::reactive::sanitize::quote_in_system_note(to_label);
154 let key = format!("failover:{def_id}");
155 let why = if expired { "Your login expired" } else { "Your account hit its usage limit" };
156 let own = format!("[AgentMux] {why}, so AgentMux moved you to {to}. Your conversation goes on there.");
157 for block in blocks.iter().filter(|b| !woken.contains(&b.oid)) {
158 crate::backend::blockcontroller::system_note_into_turn_or_hold(&block.oid, &key, &own);
159 }
160 let Some(lead) = crate::server::app_api::agent_spawn::worker_of(&state.mstore, def_id) else { return };
161 let Some(lead_pane) = open_panes(state, &lead).into_iter().next() else { return };
162 let who = crate::backend::reactive::sanitize::quote_in_system_note(&name);
163 let text = if expired {
164 format!("[AgentMux] {who}'s login expired, so AgentMux moved it to {to}.")
165 } else {
166 format!("[AgentMux] {who} hit its usage limit, so AgentMux moved it to {to}.")
167 };
168 crate::backend::blockcontroller::system_note_into_turn_or_hold(&lead_pane.oid, &key, &text);
169}